@gjsify/cli 0.62.0 → 0.63.1-next.235

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/cli.gjs.mjs CHANGED
@@ -8,10 +8,10 @@ if(globalThis.__gjsifyBundleUrl??=import.meta.url,Symbol.dispose||(Symbol.dispos
8
8
  `)||``;this._write(`stderr`,`Trace:`,...t,`
9
9
  `+n)}profile(t){}profileEnd(t){}timeStamp(t){}},pe=new Console,log=(...t)=>pe.log(...t),info=(...t)=>pe.info(...t),me=__name$1((...t)=>pe.debug(...t),`debug`),warn=(...t)=>pe.warn(...t),error=(...t)=>pe.error(...t),dir=(t,n)=>pe.dir(t,n),dirxml=(...t)=>pe.dirxml(...t),table=(t,n)=>pe.table(t,n),clear=()=>pe.clear(),assert=(t,...n)=>pe.assert(t,...n),trace=(...t)=>pe.trace(...t),time=t=>pe.time(t),timeEnd=t=>pe.timeEnd(t),timeLog=(t,...n)=>pe.timeLog(t,...n),count=t=>pe.count(t),countReset=t=>pe.countReset(t),group=(...t)=>pe.group(...t),groupCollapsed=(...t)=>pe.groupCollapsed(...t),groupEnd=()=>pe.groupEnd(),profile=t=>{},profileEnd=t=>{},timeStamp=t=>{}}),ge,_e=__esmMin(()=>{he(),ge={log,info,debug:me,warn,error,dir,dirxml,table,time,timeEnd,timeLog,trace,assert,clear,count,countReset,group,groupCollapsed,groupEnd,profile,profileEnd,timeStamp}}),ve,ye=__esmMin(()=>{ve=__name$1(t=>{Promise.resolve().then(t)},`queueMicrotask`)});function isWindowsPath(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith(`\\\\`)}function lastPathSeparatorIndex(t){let n=t.lastIndexOf(`/`);return isWindowsPath(t)?Math.max(n,t.lastIndexOf(`\\`)):n}function splitPathComponents(t){return isWindowsPath(t)?t.split(/[\\/]/):t.split(`/`)}function pathToFileUrlHref(t,n){let S=n?.windows??isWindowsPath(t),C=S?t.replace(/\\/g,`/`):t;if(S&&C.startsWith(`//`)){let t=C.indexOf(`/`,2);return`file://${t===-1?C.slice(2):C.slice(2,t)}${encodePathForFileUrl(t===-1?``:C.slice(t))}`}return`${C.startsWith(`/`)?`file://`:`file:///`}${encodePathForFileUrl(C)}`}function encodePathForFileUrl(t){let n=``;for(let S of t)n+=be.test(S)?S:percentEncode$1(S);return n}function percentEncode$1(t){let n=``;for(let S of new TextEncoder().encode(t))n+=`%${S.toString(16).toUpperCase().padStart(2,`0`)}`;return n}var be,xe=__esmMin(()=>{be=/^[A-Za-z0-9!$&'()*+,\-./:;=@_]$/,__name$1(percentEncode$1,`percentEncode`)});function mapSysname(t){let n=t.trim();switch(n){case`Linux`:return`linux`;case`Darwin`:return`darwin`;case`FreeBSD`:return`freebsd`;case`OpenBSD`:return`openbsd`;case`NetBSD`:return`netbsd`;case`SunOS`:return`sunos`;case`AIX`:return`aix`;case`Haiku`:return`haiku`;default:return/^CYGWIN/i.test(n)?`cygwin`:/^(MINGW|MSYS|Windows)/i.test(n)?`win32`:void 0}}function mapMachine(t){let n=t.trim().toLowerCase();switch(n){case`x86_64`:case`amd64`:return`x64`;case`aarch64`:case`arm64`:return`arm64`;case`i386`:case`i486`:case`i586`:case`i686`:return`ia32`;case`ppc64le`:case`ppc64`:return`ppc64`;case`s390x`:return`s390x`;case`riscv64`:return`riscv64`;case`loongarch64`:return`loong64`;case`mipsel`:return`mipsel`;case`mips`:return`mips`;default:return n.startsWith(`arm`)?`arm`:void 0}}var Se=__esmMin(()=>{});function classOf(t){return Ce.call(t).slice(8,-1)}function throwDataCloneError(t){let n=globalThis.DOMException;if(typeof n==`function`)throw new n(t,`DataCloneError`);let S=Error(t);throw S.name=`DataCloneError`,S}function internalClone(t,n,S){if(t==null)return t;let C=typeof t;if(C===`boolean`||C===`number`||C===`string`||C===`bigint`)return t;C===`symbol`&&throwDataCloneError(`Symbol cannot be cloned`),C===`function`&&throwDataCloneError(`Function cannot be cloned`);let N=t;if(n.has(N))return n.get(N);let F=classOf(N);if(F===`Date`)return new Date(N.getTime());if(F===`RegExp`)return new RegExp(N.source,N.flags);if(F===`Boolean`||F===`Number`||F===`String`)return Object(N.valueOf());if(F===`BigInt`)return Object(BigInt.prototype.valueOf.call(N));if(N instanceof Error){let t=N,C=t.constructor?.name,F=new(C&&we[C]||we[t.name]||Error)(t.message);return F.name=t.name,`cause`in t&&Object.defineProperty(F,"cause",{value:internalClone(t.cause,n,S),writable:!0,enumerable:!1,configurable:!0}),F}if(F===`DOMException`){let t=globalThis.DOMException;if(typeof t==`function`){let n=N;return new t(n.message,n.name)}}if(F===`ArrayBuffer`){let t=N;if(S&&S.transferred.has(t)){let C=S.transferred.get(t);return n.set(N,C),C}(t.detached===!0||t.byteLength===0&&t.detached)&&throwDataCloneError(`ArrayBuffer is detached and cannot be cloned`);let C=t.slice(0);return n.set(N,C),C}if(F===`SharedArrayBuffer`||N&&typeof N==`object`&&N.constructor?.name===`SharedBuffer`)return N;if(F===`DataView`){let t=N,C=S?.viewSnapshots.get(N),F=internalClone(t.buffer,n,S),I=C?C.byteOffset:t.byteOffset,H=C?C.byteLength:t.byteLength,W=new DataView(F,I,H);return n.set(N,W),W}if(Te.has(F)){let t=N,C=S?.viewSnapshots.get(N),F=internalClone(t.buffer,n,S),I=t.constructor,H=new I(F,C?C.byteOffset:t.byteOffset,C?C.length:t.length);return n.set(N,H),H}if(F===`Map`){let t=new Map;n.set(N,t);for(let[C,F]of N)t.set(internalClone(C,n,S),internalClone(F,n,S));return t}if(F===`Set`){let t=new Set;n.set(N,t);for(let C of N)t.add(internalClone(C,n,S));return t}{let t=globalThis,n=t.Blob,S=t.File;if(typeof S==`function`&&N instanceof S){let t=N;return new S([N],t.name,{type:t.type,lastModified:t.lastModified})}if(typeof n==`function`&&N instanceof n)return new n([N],{type:N.type})}if(N instanceof WeakMap&&throwDataCloneError(`WeakMap cannot be cloned`),N instanceof WeakSet&&throwDataCloneError(`WeakSet cannot be cloned`),N instanceof WeakRef&&throwDataCloneError(`WeakRef cannot be cloned`),typeof globalThis.Promise==`function`&&N instanceof Promise&&throwDataCloneError(`Promise cannot be cloned`),F===`Array`){let t=N,C=[];n.set(N,C);for(let N=0;N<t.length;N++)N in t&&(C[N]=internalClone(t[N],n,S));return C}if(F===`Object`||typeof N==`object`){let t={};n.set(N,t);for(let C of Object.keys(N))t[C]=internalClone(N[C],n,S);return t}throwDataCloneError(`${F} cannot be cloned`)}function structuredClone$1(t,n){let S=n?.transfer;if(!S||S.length===0)return internalClone(t,new Map);let C=new Set;for(let t of S)if(classOf(t)===`ArrayBuffer`){let n=t;n.detached===!0&&throwDataCloneError(`ArrayBuffer in transfer list is detached`),C.add(n)}let N=new Map;C.size>0&&snapshotViewsBackedByTransferredBuffers(t,C,N,new Set);let F=new Map;for(let t of C){let n=t;typeof n.transfer!=`function`&&throwDataCloneError(`ArrayBuffer.prototype.transfer() not available — runtime is not SM140+`),F.set(t,n.transfer())}return internalClone(t,new Map,{transferred:F,viewSnapshots:N})}function snapshotViewsBackedByTransferredBuffers(t,n,S,C){if(typeof t!=`object`||!t)return;let N=t;if(C.has(N))return;C.add(N);let F=classOf(N);if(F===`DataView`){let t=N;n.has(t.buffer)&&S.set(N,{byteOffset:t.byteOffset,length:0,byteLength:t.byteLength});return}if(Te.has(F)){let t=N;n.has(t.buffer)&&S.set(N,{byteOffset:t.byteOffset,length:t.length,byteLength:t.byteLength});return}if(Array.isArray(N)){for(let t=0;t<N.length;t++)t in N&&snapshotViewsBackedByTransferredBuffers(N[t],n,S,C);return}if(F===`Map`){for(let[t,F]of N)snapshotViewsBackedByTransferredBuffers(t,n,S,C),snapshotViewsBackedByTransferredBuffers(F,n,S,C);return}if(F===`Set`){for(let t of N)snapshotViewsBackedByTransferredBuffers(t,n,S,C);return}if(F===`Object`)for(let t of Object.keys(N))snapshotViewsBackedByTransferredBuffers(N[t],n,S,C)}var Ce,we,Te,Ee=__esmMin(()=>{({toString:Ce}=Object.prototype),we={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Te=new Set([`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`]),__name$1(structuredClone$1,`structuredClone`)});function hostGlib(){try{return globalThis.imports?.gi?.GLib}catch{return}}function readText(t,n){try{let[S,C]=t.file_get_contents(n);return!S||!C?null:new TextDecoder().decode(C)}catch{return null}}function shellOut(t,n){try{let[S,C]=t.spawn_command_line_sync(n);if(!S||!C)return null;let N=new TextDecoder().decode(C).trim();return N.length>0?N:null}catch{return null}}function hasProcfs(){let t=hostGlib();if(!t)return!1;try{return t.file_test(`/proc/self/status`,16)}catch{return!1}}function hostPid(){if(De!==null)return De>0?De:void 0;let t=hostGlib();if(!t)return;let n=0,S=hasProcfs()?readText(t,`/proc/self/stat`):null;if(S)n=parseInt(S,10);else{let S=shellOut(t,`sh -c 'echo $PPID'`);S&&(n=parseInt(S,10))}return De=Number.isInteger(n)&&n>0?n:0,De>0?De:void 0}function hostPpid(){let t=hostGlib();if(!t)return;let n=hasProcfs()?readText(t,`/proc/self/status`):null;if(n){let t=/PPid:\s+(\d+)/.exec(n);if(t){let n=parseInt(t[1],10);return Number.isInteger(n)?n:void 0}}let S=hostPid();if(S===void 0)return;let C=shellOut(t,`ps -o ppid= -p ${S}`);if(!C)return;let N=parseInt(C,10);return Number.isInteger(N)?N:void 0}function hostExecPath(){let t=hostGlib();if(t){if(hasProcfs())try{let n=t.file_read_link(`/proc/self/exe`);if(n)return n}catch{}try{let n=t.get_prgname();if(n){let S=t.find_program_in_path(n);if(S)return S}}catch{return}}}function readProcessMemory$4(){let t=hostGlib();if(!t)return null;let n=hasProcfs()?readText(t,`/proc/self/status`):null;if(n){let t=new Map;for(let S of n.split(`
10
10
  `)){let n=/^(\w+):\s+(\d+)(\s+kB)?/.exec(S);n&&t.set(n[1],parseInt(n[2],10)*(n[3]?1024:1))}if(t.size>0)return{virtual:t.get(`VmSize`)??0,resident:t.get(`VmRSS`)??0,data:t.get(`VmData`)??0,peak:t.get(`VmPeak`)??0}}let S=shellOut(t,`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!S)return null;let C=/^(\d+)\s+(\d+)$/.exec(S);return C?{virtual:parseInt(C[2],10)*1024,resident:parseInt(C[1],10)*1024,data:0,peak:0}:null}var De,Oe=__esmMin(()=>{De=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib(){let t=globalThis;if(typeof t.process?.versions?.gjs==`string`||t.process===void 0)return t.imports?.gi?.GLib}function arm(t){je||(je=!0,t.runAsync().catch(()=>{}))}function ensureMainLoop(){let t=glib();if(t)return Ae?ke:(ke=new t.MainLoop(null,!1),Ae=!0,t.main_depth()===0&&arm(ke),ke)}function holdMainLoop(){let t=ensureMainLoop();return t&&arm(t),t}function quitMainLoop(){ke&&=(ke.quit(),Ae=!1,je=!1,null)}var ke,Ae,je,Me=__esmMin(()=>{ke=null,Ae=!1,je=!1});function hostGi(){return globalThis.imports?.gi}function directoryOf(t){return/^(.*)[\\/][^\\/]*$/.exec(t)?.[1]}function colocateNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t),N=C?directoryOf(C):void 0;return!S||!N?!1:(S.prepend_library_path(N),!0)}catch{return!1}}function probeNativeLibrary(t,n=hostGi()){try{let S=n?.GIRepository?.Repository?.dup_default?.(),C=S?.get_typelib_path(t);if(!n||!S||!C)return null;let N=firstSymbol(S,t);if(!N||(n.GModule?.module_error(),N.info.get_typelib().symbol(N.name)[0]))return null;let F=directoryOf(C)??`.`,I=C.includes(`\\`)&&!C.includes(`/`)?`\\`:`/`;for(let H of S.get_shared_libraries(t)??[]){let S=`${F}${I}${H}`,W=n.GLib?.file_test(S,n.GLib.FileTest.EXISTS)?S:H,q=loaderError(n,t,C,W,N.name);if(q!==void 0)return{namespace:t,library:W,reason:q,missingDependency:missingLibraryDependency(q,W)}}let H=(S.get_shared_libraries(t)??[]).join(`, `)||`(none named)`;return{namespace:t,library:H,reason:`symbol ${N.name} not found in ${H}, and the loader reported no error`}}catch{return null}}function firstSymbol(t,n){let S=t.get_n_infos(n),C=null;for(let N=0;N<S;N++){let S=t.get_info(n,N),F=S.get_type_init_function_name?.();if(F)return{info:S,name:F};let I=S.get_symbol?.();I&&!C&&(C={info:S,name:I})}return C}function loaderError(t,n,S,C,N){let{GIRepository:F,GLib:I,GModule:H}=t;if(!F?.Repository||!F.Typelib||!I||!H)return;let[,W]=I.file_get_contents(S),q=new TextEncoder().encode(`${C}\0`),Y=new Uint8Array(W.length+q.length);Y.set(W),Y.set(q,W.length);let X=new DataView(Y.buffer);X.setUint32(40,Y.length,!0),X.setUint32(52,W.length,!0);let Z=new F.Repository,te=firstSymbol(Z,Z.load_typelib(F.Typelib.new_from_bytes(new I.Bytes(Y)),0));if(te&&(H.module_error(),!te.info.get_typelib().symbol(N)[0]))return H.module_error()??`${n}: ${C} could not be opened (the loader reported no error)`}function missingLibraryDependency(t,n){let S=/Library not loaded: (\S+)/.exec(t)?.[1]??/Error loading shared library ([^\s:]+): .*\(needed by /.exec(t)?.[1]??/(?:^|\s)([^\s:]+): cannot open shared object file/.exec(t)?.[1];if(!S)return;let C=S.replace(/^.*[\\/]/,``);if(!(n&&C===n.replace(/^.*[\\/]/,``)))return C}function openNativeLibrary(t,n=hostGi()){colocateNativeLibrary(t,n);let S=probeNativeLibrary(t,n);return S?new NativeLibraryLoadError(S):null}function loadOptionalNativeModule(t,n,S=hostGi()){if(!S)return{module:null,error:Error(`${t}: imports.gi is not available (not running on GJS)`)};try{let C=S[t];if(!C)return{module:null,error:Error(`${t}: typelib not found`)};let N=openNativeLibrary(t,S);if(N)return ge.debug(N.message),{module:null,error:N};for(let t of n)C[t];return{module:C,error:null}}catch(t){return{module:null,error:t instanceof Error?t:Error(String(t))}}}var NativeLibraryLoadError,Fe=__esmMin(()=>{_e(),NativeLibraryLoadError=class extends Error{failure;constructor(t,n){let S=t.missingDependency?`It needs ${t.missingDependency}, which the loader could not find: not installed, or not on its search path.`:`The loader could not open it.`;super(`${t.namespace}: the native library ${t.library} could not be loaded. ${S}\nLoader: ${t.reason.trim()}\n`+(n??"`gjsify system-check` lists the system libraries the installed @gjsify packages need, with the install command for this host.")),this.name=`NativeLibraryLoadError`,this.failure=t}}});function drainOnce(t){let n=Math.min(64,Ie.length);for(let S=0;S<n;S++){let n=Ie.shift();try{n()}catch(n){try{t.log_default_handler(`gjsify-nextTick`,t.LogLevelFlags.LEVEL_WARNING,String(n?.stack||n),null)}catch{}}}Ie.length>0?t.timeout_add(t.PRIORITY_DEFAULT,1,()=>(drainOnce(t),!1)):Le=!1}function tryGLibTimeout(t){let n=globalThis.imports?.gi?.GLib;return n?.timeout_add?(Ie.push(t),Le||(Le=!0,n.timeout_add(n.PRIORITY_DEFAULT,0,()=>(drainOnce(n),!1))),!0):!1}var Ie,Le,nextTick,Re=__esmMin(()=>{Ie=[],Le=!1,nextTick=(t,...n)=>{let S=n.length>0?()=>t(...n):t;if(!tryGLibTimeout(S)){if(typeof globalThis.process?.nextTick==`function`){globalThis.process.nextTick(t,...n);return}if(typeof queueMicrotask==`function`){queueMicrotask(S);return}Promise.resolve().then(S)}}}),ze=__esmMin(()=>{ie(),oe(),se(),ce(),ue(),ye(),xe(),Se(),Ee(),Oe(),Me(),Fe(),Re()});re(),ze(),registerGlobal(`Blob`,te),registerGlobal(`File`,ne);function atobPolyfill(t){if(typeof globalThis.atob==`function`)return globalThis.atob(t);let n=t.replace(/[=\s]/g,``),S=``,C=0,N=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S+=String.fromCharCode(C>>N&255));return S}function btoaPolyfill(t){if(typeof globalThis.btoa==`function`)return globalThis.btoa(t);let n=``,S=0;for(;S+2<t.length;S+=3){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8|t.charCodeAt(S+2);n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+Be[C&63]}if(S+1===t.length){let C=t.charCodeAt(S)<<16;n+=Be[C>>18&63]+Be[C>>12&63]+`==`}else if(S+2===t.length){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8;n+=Be[C>>18&63]+Be[C>>12&63]+Be[C>>6&63]+`=`}return n}function base64Decode$2(t){let n=t.replace(/[=\s]/g,``),S=new Uint8Array(n.length*3>>2),C=0,N=0,F=0;for(let t=0;t<n.length;t++)C=C<<6|Ve[n.charCodeAt(t)],N+=6,N>=8&&(N-=8,S[F++]=C>>N&255);return S.subarray(0,F)}function base64Encode$1(t){let n=``,S=t.length;for(let C=0;C<S;C+=3){let N=t[C],F=C+1<S?t[C+1]:0,I=C+2<S?t[C+2]:0;n+=Be[N>>2],n+=Be[(N&3)<<4|F>>4],n+=C+1<S?Be[(F&15)<<2|I>>6]:`=`,n+=C+2<S?Be[I&63]:`=`}return n}var Be,Ve,He=__esmMin(()=>{Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ve=new Uint8Array(256);for(let t=0;t<64;t++)Ve[Be.charCodeAt(t)]=t;__name$1(base64Decode$2,`base64Decode`),__name$1(base64Encode$1,`base64Encode`)});function normalizeEncoding(t){if(!t||t===`utf8`||t===`utf-8`)return`utf8`;switch((``+t).toLowerCase().replace(/-/g,``)){case`utf8`:return`utf8`;case`ascii`:return`ascii`;case`latin1`:case`binary`:return`latin1`;case`base64`:return`base64`;case`base64url`:return`base64url`;case`hex`:return`hex`;case`ucs2`:case`utf16le`:return`utf16le`;default:return`utf8`}}function checkEncoding(t){let n=(``+t).toLowerCase().replace(/-/g,``);if(!Ue.includes(n))throw TypeError(`Unknown encoding: ${t}`)}var Ue,Ge=__esmMin(()=>{Ue=[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`]});function encodeString(t,n){switch(n){case`utf8`:return textEncoder().encode(t);case`ascii`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&127;return n}case`latin1`:{let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return n}case`base64`:return base64Decode$2(t.replace(/-/g,`+`).replace(/_/g,`/`));case`base64url`:return encodeString(t.replace(/-/g,`+`).replace(/_/g,`/`),`base64`);case`hex`:{let n=t.length>>>1,S=new Uint8Array(n);for(let C=0;C<n;C++){let n=parseInt(t[C*2],16),N=parseInt(t[C*2+1],16);if(Number.isNaN(n)||Number.isNaN(N))break;S[C]=n<<4|N}return S}case`utf16le`:{let n=new Uint8Array(t.length*2);for(let S=0;S<t.length;S++){let C=t.charCodeAt(S);n[S*2]=C&255,n[S*2+1]=C>>8&255}return n}default:return textEncoder().encode(t)}}function decodeString(t,n,S,C){let N=S!==void 0||C!==void 0?t.subarray(S??0,C??t.length):t;switch(n){case`utf8`:return textDecoder().decode(N);case`ascii`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]&127);return t}case`latin1`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return t}case`base64`:{let t=``;for(let n=0;n<N.length;n++)t+=String.fromCharCode(N[n]);return btoaPolyfill(t)}case`base64url`:return decodeString(N,`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);case`hex`:{let t=``;for(let n=0;n<N.length;n++)t+=N[n].toString(16).padStart(2,`0`);return t}case`utf16le`:{let t=``;for(let n=0;n+1<N.length;n+=2)t+=String.fromCharCode(N[n]|N[n+1]<<8);return t}default:return textDecoder().decode(N)}}function checkOffset(t,n,S){if(t+n>S)throw RangeError(`Attempt to access memory outside buffer bounds`)}var Ke,qe,textEncoder,textDecoder,Je=__esmMin(()=>{He(),textEncoder=()=>Ke??=new TextEncoder,textDecoder=()=>qe??=new TextDecoder}),Ye,Xe,Ze,Qe,$e,SlowBuffer,et=__esmMin(()=>{Je(),Ge(),Ye=typeof SharedArrayBuffer<`u`,Xe=class Buffer extends Uint8Array{static _isBuffer=!0;static alloc(t,n,S){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);if(t<0)throw RangeError(`The value "${t}" is invalid for option "size"`);let C=new Buffer(t);return n!==void 0&&n!==0&&C.fill(n,0,t,S),C}static allocUnsafe(t){if(typeof t!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof t}`);return new Buffer(t)}static allocUnsafeSlow(t){return Buffer.allocUnsafe(t)}static from(t,n,S){if(typeof t==`string`){let S=normalizeEncoding(n);if(n&&typeof n==`string`){let t=(``+n).toLowerCase().replace(/-/g,``);[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`,``].includes(t)||checkEncoding(n)}let C=encodeString(t,S);return new Buffer(C.buffer,C.byteOffset,C.byteLength)}if(ArrayBuffer.isView(t)){let n=new Buffer(t.buffer,t.byteOffset,t.byteLength),S=new Buffer(n.length);return S.set(n),S}if(t instanceof ArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(t,C,N)}if(Ye&&t instanceof SharedArrayBuffer){let C=n||0,N=S===void 0?t.byteLength-C:S;return new Buffer(new Uint8Array(t,C,N))}if(typeof t==`object`&&t&&typeof t.viewBytes==`function`&&typeof t.byteLength==`number`&&t.constructor?.name===`SharedBuffer`){let C=t,N=n||0,F=S===void 0?C.byteLength-N:S,I=C.viewBytes(N,F);return new Buffer(I.buffer,I.byteOffset,I.byteLength)}if(Array.isArray(t)){let n=new Buffer(t.length);for(let S=0;S<t.length;S++)n[S]=t[S]&255;return n}throw TypeError(`The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array`)}static isBuffer(t){return t instanceof Buffer}static isEncoding(t){if(typeof t!=`string`)return!1;let n=t.toLowerCase().replace(/-/g,``);return[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`].includes(n)}static byteLength(t,n){if(typeof t!=`string`){if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||Ye&&t instanceof SharedArrayBuffer)return t.byteLength;throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer`)}switch(normalizeEncoding(n)){case`utf8`:return new TextEncoder().encode(t).byteLength;case`ascii`:case`latin1`:return t.length;case`base64`:case`base64url`:{let n=t.length;for(;n>0&&(t[n-1]===`=`||t[n-1]===` `);)n--;return n*3>>>2}case`hex`:return t.length>>>1;case`utf16le`:return t.length*2;default:return new TextEncoder().encode(t).byteLength}}static compare(t,n){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))throw TypeError(`Arguments must be Buffers or Uint8Arrays`);let S=Math.min(t.length,n.length);for(let C=0;C<S;C++){if(t[C]<n[C])return-1;if(t[C]>n[C])return 1}return t.length<n.length?-1:+(t.length>n.length)}static concat(t,n){if(t.length===0)return Buffer.alloc(0);if(n===void 0){n=0;for(let S=0;S<t.length;S++)n+=t[S].length}let S=Buffer.alloc(n),C=0;for(let N=0;N<t.length;N++){let F=t[N],I=Math.min(F.length,n-C);I<=0||(S.set(F.subarray(0,I),C),C+=I)}return S}static poolSize=65536;toString(t,n,S){let C=normalizeEncoding(t);return decodeString(this,C,n,S)}toJSON(){return{type:`Buffer`,data:Array.from(this)}}equals(t){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);if(this.length!==t.length)return!1;for(let n=0;n<this.length;n++)if(this[n]!==t[n])return!1;return!0}compare(t,n,S,C,N){if(!(t instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);let F=C!==void 0||N!==void 0?this.subarray(C??0,N??this.length):this,I=n!==void 0||S!==void 0?t.subarray(n??0,S??t.length):t;return Buffer.compare(F,I)}copy(t,n=0,S=0,C){let N=C??this.length,F=Math.min(N-S,t.length-n);return F<=0?0:(t.set(this.subarray(S,S+F),n),F)}slice(t,n){let S=t??0,C=n??this.length,N=super.subarray(S,C);return new Buffer(N.buffer,N.byteOffset,N.byteLength)}subarray(t,n){let S=super.subarray(t,n);return new Buffer(S.buffer,S.byteOffset,S.byteLength)}write(t,n,S,C){n??=0;let N=encodeString(t,normalizeEncoding(C||(typeof S==`string`?S:void 0))),F=S!==void 0&&typeof S==`number`?Math.min(S,this.length-n):this.length-n,I=Math.min(N.length,F);return this.set(N.subarray(0,I),n),I}fill(t,n,S,C){let N=n??0,F=S??this.length;if(typeof t==`number`)super.fill(t&255,N,F);else if(typeof t==`string`){let n=encodeString(t,normalizeEncoding(C));if(n.length===0)super.fill(0,N,F);else if(n.length===1)super.fill(n[0],N,F);else for(let t=N;t<F;t++)this[t]=n[(t-N)%n.length]}else if(t instanceof Uint8Array)if(t.length===0)super.fill(0,N,F);else for(let n=N;n<F;n++)this[n]=t[(n-N)%t.length];return this}indexOf(t,n,S){if(typeof t==`number`)return super.indexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n??0;outer:for(let t=N;t<=this.length-C.length;t++){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}lastIndexOf(t,n,S){if(typeof t==`number`)return n===void 0?super.lastIndexOf(t&255):super.lastIndexOf(t&255,n);let C=typeof t==`string`?encodeString(t,normalizeEncoding(S)):t,N=n===void 0?this.length-C.length:Math.min(n,this.length-C.length);outer:for(let t=N;t>=0;t--){for(let n=0;n<C.length;n++)if(this[t+n]!==C[n])continue outer;return t}return-1}includes(t,n,S){return this.indexOf(t,n,S)!==-1}readUInt8(t=0){return checkOffset(t,1,this.length),this[t]}readUInt16BE(t=0){return checkOffset(t,2,this.length),this[t]<<8|this[t+1]}readUInt16LE(t=0){return checkOffset(t,2,this.length),this[t]|this[t+1]<<8}readUInt32BE(t=0){return checkOffset(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])}readUInt32LE(t=0){return checkOffset(t,4,this.length),this[t+3]*16777216+(this[t+2]<<16|this[t+1]<<8|this[t])>>>0}readInt8(t=0){return checkOffset(t,1,this.length),this[t]|(this[t]&128?4294967040:0)}readInt16BE(t=0){checkOffset(t,2,this.length);let n=this[t]<<8|this[t+1];return n&32768?n|4294901760:n}readInt16LE(t=0){checkOffset(t,2,this.length);let n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n}readInt32BE(t=0){return checkOffset(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]}readInt32LE(t=0){return checkOffset(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24}readFloatBE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!1)}readFloatLE(t=0){return checkOffset(t,4,this.length),new DataView(this.buffer,this.byteOffset+t,4).getFloat32(0,!0)}readDoubleBE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!1)}readDoubleLE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getFloat64(0,!0)}readBigInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!1)}readBigInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigInt64(0,!0)}readBigUInt64BE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!1)}readBigUInt64LE(t=0){return checkOffset(t,8,this.length),new DataView(this.buffer,this.byteOffset+t,8).getBigUint64(0,!0)}readUIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S}readUIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S}readIntBE(t,n){checkOffset(t,n,this.length);let S=0;for(let C=0;C<n;C++)S=S*256+this[t+C];return S>=2**(8*n-1)&&(S-=2**(8*n)),S}readIntLE(t,n){checkOffset(t,n,this.length);let S=0,C=1;for(let N=0;N<n;N++)S+=this[t+N]*C,C*=256;return S>=2**(8*n-1)&&(S-=2**(8*n)),S}writeUInt8(t,n=0){return checkOffset(n,1,this.length),this[n]=t&255,n+1}writeUInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeUInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeUInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeUInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeInt8(t,n=0){return checkOffset(n,1,this.length),t<0&&(t=255+t+1),this[n]=t&255,n+1}writeInt16BE(t,n=0){return checkOffset(n,2,this.length),this[n]=t>>>8&255,this[n+1]=t&255,n+2}writeInt16LE(t,n=0){return checkOffset(n,2,this.length),this[n]=t&255,this[n+1]=t>>>8&255,n+2}writeInt32BE(t,n=0){return checkOffset(n,4,this.length),this[n]=t>>>24&255,this[n+1]=t>>>16&255,this[n+2]=t>>>8&255,this[n+3]=t&255,n+4}writeInt32LE(t,n=0){return checkOffset(n,4,this.length),this[n]=t&255,this[n+1]=t>>>8&255,this[n+2]=t>>>16&255,this[n+3]=t>>>24&255,n+4}writeFloatBE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!1),n+4}writeFloatLE(t,n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).setFloat32(0,t,!0),n+4}writeDoubleBE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!1),n+8}writeDoubleLE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setFloat64(0,t,!0),n+8}writeBigInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!1),n+8}writeBigInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigInt64(0,t,!0),n+8}writeBigUInt64BE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!1),n+8}writeBigUInt64LE(t,n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).setBigUint64(0,t,!0),n+8}readUint8(t=0){return this.readUInt8(t)}readUint16BE(t=0){return this.readUInt16BE(t)}readUint16LE(t=0){return this.readUInt16LE(t)}readUint32BE(t=0){return this.readUInt32BE(t)}readUint32LE(t=0){return this.readUInt32LE(t)}readUintBE(t,n){return this.readUIntBE(t,n)}readUintLE(t,n){return this.readUIntLE(t,n)}readBigUint64BE(t=0){return this.readBigUInt64BE(t)}readBigUint64LE(t=0){return this.readBigUInt64LE(t)}writeUint8(t,n=0){return this.writeUInt8(t,n)}writeUint16BE(t,n=0){return this.writeUInt16BE(t,n)}writeUint16LE(t,n=0){return this.writeUInt16LE(t,n)}writeUint32BE(t,n=0){return this.writeUInt32BE(t,n)}writeUint32LE(t,n=0){return this.writeUInt32LE(t,n)}writeBigUint64BE(t,n=0){return this.writeBigUInt64BE(t,n)}writeBigUint64LE(t,n=0){return this.writeBigUInt64LE(t,n)}swap16(){let t=this.length;if(t%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let n=0;n<t;n+=2){let t=this[n];this[n]=this[n+1],this[n+1]=t}return this}swap32(){let t=this.length;if(t%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let n=0;n<t;n+=4){let t=this[n],S=this[n+1];this[n]=this[n+3],this[n+1]=this[n+2],this[n+2]=S,this[n+3]=t}return this}swap64(){let t=this.length;if(t%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let n=0;n<t;n+=8){let t=this[n],S=this[n+1],C=this[n+2],N=this[n+3];this[n]=this[n+7],this[n+1]=this[n+6],this[n+2]=this[n+5],this[n+3]=this[n+4],this[n+4]=N,this[n+5]=C,this[n+6]=S,this[n+7]=t}return this}},Ze=2**31-1,Qe=2**28-16,$e={MAX_LENGTH:Ze,MAX_STRING_LENGTH:Qe},SlowBuffer=class extends Xe{constructor(t){super(t)}}}),tt=__exportAll$5({Blob:()=>te,Buffer:()=>Xe,File:()=>ne,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>nt,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>rt,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>$e,default:()=>it,kMaxLength:()=>Ze,kStringMaxLength:()=>Qe,normalizeEncoding:()=>normalizeEncoding}),nt,rt,it,ot=__esmMin(()=>{He(),re(),Ge(),et(),nt=globalThis.atob,rt=globalThis.btoa,it={Buffer:Xe,SlowBuffer,Blob:te,File:ne,atob:nt,btoa:rt,kMaxLength:Ze,kStringMaxLength:Qe,constants:$e,INSPECT_MAX_BYTES:50}});ot(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:Xe,enumerable:!1,writable:!0,configurable:!0});var st,ct=__esmMin(()=>{st=t}),lt,ut=__esmMin(()=>{ct(),lt=st});ut(),typeof globalThis.btoa!=`function`&&Object.defineProperty(globalThis,"btoa",{value:function btoa(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S)&255;return lt.base64_encode(n)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(t){let n=lt.base64_decode(t),S=``;for(let t=0;t<n.length;t++)S+=String.fromCharCode(n[t]);return S},enumerable:!0,writable:!0,configurable:!0}),ze(),typeof queueMicrotask!=`function`&&Object.defineProperty(globalThis,"queueMicrotask",{value:ve,enumerable:!0,writable:!0,configurable:!0});function getGjsGlobal(){return globalThis}function getGioNamespace(){let t=getGjsGlobal().imports?.gi;if(!t)return null;let n=null;try{n=t.GioUnix??null}catch{}if(!n)try{n=t.Gio??null}catch{}return n}var dt=__esmMin(()=>{});function getMonotonicTime(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_monotonic_time)return BigInt(t.get_monotonic_time())*1000n}catch{}return typeof performance?.now==`function`?BigInt(Math.round(performance.now()*1e6)):BigInt(Date.now())*1000000n}function hrtime(t){let n=getMonotonicTime()-ft,S=Number(n/1000000000n),C=Number(n%1000000000n);if(t){let n=S-t[0],N=C-t[1];return N<0&&(n--,N+=1e9),[n,N]}return[S,C]}function hrtimeBigint(){return getMonotonicTime()-ft}var ft,pt=__esmMin(()=>{dt(),ft=getMonotonicTime()});function probeUname(){if(mt!==void 0)return mt;mt=null;try{let t=getGjsGlobal().imports?.gi?.GLib;if(!t)return mt;let n=t.spawn_sync,S=t.SpawnFlags?.SEARCH_PATH;if(!n||S===void 0)return mt;let[C,N]=n(null,[`uname`,`-sm`],null,S,null);if(!C||!N)return mt;let F=new TextDecoder().decode(N).trim().split(/\s+/);if(F.length<2)return mt;let I=mapSysname(F[0]),H=mapMachine(F[F.length-1]);if(!I||!H)return mt;mt={platform:I,arch:H}}catch{}return mt}var mt,ht=__esmMin(()=>{dt(),ze()});function detectGjsVersion(){try{let t=getGjsGlobal().imports?.system;if(t?.version!==void 0){let n=Number(t.version);return`${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100}`}}catch{}}function detectNodeVersion(){if(typeof globalThis.process?.versions?.node==`string`)return globalThis.process.versions.node}function detectVersionInfo(){if(detectNodeVersion())return{version:globalThis.process.version,versions:{...globalThis.process.versions},title:globalThis.process?.title||`node`};let t=detectGjsVersion(),n={node:`20.0.0`};return t&&(n.gjs=t),{version:`v20.0.0`,versions:n,title:`gjs`}}function detectPpid(){let t=runtimeProcess();return t&&typeof t.ppid==`number`?t.ppid:hostPpid()??0}function runtimeProcess(){let t=globalThis.process;return typeof t?.release?.name==`string`?t:void 0}function onGjs(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function detectPlatform$1(){let t=runtimeProcess();if(t)return t.platform;if(onGjs()){let t=probeUname();if(t)return t.platform}return`linux`}function detectArch(){let t=runtimeProcess();if(t)return t.arch;if(onGjs()){let t=probeUname();if(t)return t.arch}return`x64`}function getPid$1(){let t=runtimeProcess();return t&&typeof t.pid==`number`?t.pid:hostPid()??0}var gt=__esmMin(()=>{dt(),ht(),ze(),__name$1(detectPlatform$1,`detectPlatform`),__name$1(getPid$1,`getPid`)});function getEnvProxy(){if(typeof globalThis.process?.env==`object`)return globalThis.process.env;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return new Proxy({},{get(n,S){if(typeof S==`string`)return t.getenv(S)??void 0},set(n,S,C){return typeof S==`string`?(t.setenv(S,String(C),!0),!0):!1},deleteProperty(n,S){return typeof S==`string`?(t.unsetenv(S),!0):!1},has(n,S){return typeof S==`string`?t.getenv(S)!==null:!1},ownKeys(n){return t.listenv()},getOwnPropertyDescriptor(n,S){if(typeof S!=`string`)return;let C=t.getenv(S);if(C!==null)return{configurable:!0,enumerable:!0,writable:!0,value:C}}})}catch{}return{}}function getArgv(){if(globalThis.process?.argv!==void 0)return globalThis.process.argv;try{let t=getGjsGlobal().imports?.system;if(t?.programArgs)return[`gjs`,t.programInvocationName||``,...t.programArgs]}catch{}return[`gjs`]}function getExecPath(){let t=globalThis.process;return!isGjsHost()&&typeof t?.execPath==`string`?t.execPath:hostExecPath()??`/usr/bin/gjs`}function isGjsHost(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function getCwd(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function chdir(t){let n=getGjsGlobal().imports?.gi?.GLib;try{if(n?.chdir){if(!n.file_test(t,16)){let n=Error(`ENOENT: no such file or directory, chdir '${t}'`);throw n.code=`ENOENT`,n.syscall=`chdir`,n.path=t,n}n.chdir(t);return}}catch(t){if(t&&typeof t==`object`&&t.code===`ENOENT`)throw t}if(!n){let n=globalThis.process;if(n&&typeof n.chdir==`function`){n.chdir(t);return}}throw Error(`process.chdir() is not supported in this environment`)}var _t=__esmMin(()=>{dt(),ze()});function exitProcess(t){let n=getGjsGlobal().imports,S=n?.gi?.GLib,C=n?.system,N=S?.idle_add,F=S?.SOURCE_REMOVE,I=S?.PRIORITY_DEFAULT,H=S?.MainContext;if(C?.exit&&N&&typeof I==`number`&&typeof F==`boolean`&&typeof H?.default==`function`){N(I,()=>(C.exit(t),F));let n=H.default();for(;;)n.iteration(!0)}try{C?.exit&&C.exit(t)}catch{}let W=globalThis.process;throw W&&typeof W.exit==`function`&&W.exit(t),Error(`process.exit(${t})`)}var vt=__esmMin(()=>{dt()});function isGjs$1(){return getGjsGlobal().imports?.gi?.GLib!==void 0}function classifyKillFailure(t){if(/No such process/i.test(t))return`ESRCH`;if(/Operation not permitted/i.test(t))return`EPERM`}function killPid(t,n){let S=getGjsGlobal().imports?.gi?.GLib;if(S){let C=typeof n==`number`?String(n):n||`SIGTERM`,N=[`kill`,C.startsWith(`SIG`)?`-${C.slice(3)}`:`-${C}`,`--`,String(t)],F=S.environ_setenv(S.get_environ(),`LC_ALL`,`C`,!0),[,,I,H]=S.spawn_sync(null,N,F,4,null),W=!1;try{W=S.spawn_check_wait_status(H)}catch{W=!1}if(W)return!0;let q=I?new TextDecoder().decode(I).trim():``,Y=classifyKillFailure(q),X=Error(Y?`kill ${Y}`:`kill failed${q?`: ${q}`:``}`);throw Y&&(X.code=Y,X.errno=Y===`ESRCH`?-3:-1,X.syscall=`kill`),X}let C=globalThis.process;if(C&&typeof C.kill==`function`)return C.kill(t,n);throw Error(`process.kill() is not supported in this environment`)}function memoryUsage(){let t=readProcessMemory$4();if(t)return{rss:t.resident,heapTotal:t.resident,heapUsed:t.resident,external:0,arrayBuffers:0};if(!isGjs$1()){let t=globalThis.process;if(t&&typeof t.memoryUsage==`function`)return t.memoryUsage()}return{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}function cpuUsage(t){if(!isGjs$1()){let n=globalThis.process;if(n&&typeof n.cpuUsage==`function`)return n.cpuUsage(t)}return{user:0,system:0}}function readUmask(){try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let[n,S]=t.file_get_contents(`/proc/self/status`);if(n){let t=/^Umask:\s*([0-7]+)/m.exec(new TextDecoder().decode(S));if(t)return parseInt(t[1],8)}}}catch{}return 18}var yt=__esmMin(()=>{dt(),ze(),__name$1(isGjs$1,`isGjs`)});function resolveSignalAdd(){let t=getGjsGlobal().imports?.gi;if(!t)return null;for(let[n,S]of[[`GLibUnix`,`signal_add`],[`GLib`,`unix_signal_add`]])try{let C=t[n]?.[S];if(typeof C==`function`)return C}catch{}return null}function isDeliverableSignal(t){return typeof t==`string`&&t in bt}function armSignal(t,n){if(xt.has(t))return;let S=bt[t],C=resolveSignalAdd(),N=getGjsGlobal().imports?.gi?.GLib;if(S===void 0||C===null||!N)return;let F=N.PRIORITY_DEFAULT,I=C(F,S,()=>(n(t),!0));xt.set(t,I)}function disarmSignal(t){let n=xt.get(t);if(n===void 0)return;xt.delete(t);let S=getGjsGlobal().imports?.gi?.GLib;S&&typeof S.source_remove==`function`&&S.source_remove(n)}var bt,xt,St=__esmMin(()=>{dt(),bt={SIGHUP:1,SIGINT:2,SIGTERM:15},xt=new Map});function claimRawMode(t,n){Tt.set(t,n)}function releaseRawMode(t){Tt.delete(t)}function noteRawMode(t,n,S){let C=S(n);return n?C&&claimRawMode(t,()=>{S(!1)}):releaseRawMode(t),C}function restoreClaimedRawModes(){let t=[...Tt.entries()];Tt.clear();let n=0,S;for(let[,C]of t)try{C(),n+=1}catch(t){S??=t}if(S!==void 0)throw S;return n}var Ct,wt,Tt,Et=__esmMin(()=>{Ct=Symbol.for(`@gjsify/terminal-native:raw-mode-claims`),wt=globalThis,Tt=wt[Ct]??=new Map});function callableModule(){if(!Ot)return null;try{return Ot.Terminal.is_tty(2),Ot}catch{return null}}function nativeIsTty(t){try{return callableModule()?.Terminal.is_tty(t)??null}catch{return null}}function nativeTerminalSize(t){try{let[n,S,C]=callableModule()?.Terminal.get_size(t)??[!1,0,0];return!n||C<=0?null:{rows:S,columns:C}}catch{return null}}function nativeSetRawMode(t,n){try{return callableModule()?.Terminal.set_raw_mode(t,n)??null}catch{return null}}var Dt,Ot,kt,At=__esmMin(()=>{Et(),ze(),Dt=loadOptionalNativeModule(`GjsifyTerminal`,[`Terminal`,`ResizeWatcher`]),Ot=Dt.module,kt=Ot});function onceWrapper(){let{target:t,type:n,listener:S}=this;return this.wrapperFn&&t.removeListener(n,this.wrapperFn),S.apply(t,Array.from(arguments))}function _onceWrap(t,n,S){let C={target:t,type:n,listener:S,wrapperFn:void 0},N=onceWrapper.bind(C);return C.wrapperFn=N,N.listener=S,N}function arrayClone(t){switch(t.length){case 0:return[];case 1:return[t[0]];case 2:return[t[0],t[1]];case 3:return[t[0],t[1],t[2]];default:return t.slice()}}function checkListener(t){if(typeof t!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof t)}function validateNumber(t,n){if(typeof t!=`number`||t!==t)throw TypeError(`The "${n}" argument must be of type number. Received type ${typeof t}`)}function spliceOne(t,n){for(;n+1<t.length;n++)t[n]=t[n+1];t.pop()}function unwrapListeners(t){let n=Array.from({length:t.length});for(let S=0;S<n.length;++S)n[S]=t[S].listener??t[S];return n}function createAbortError$2(t){let n=Error(`The operation was aborted`);return n.name=`AbortError`,n.code=`ABORT_ERR`,t?.reason&&(n.cause=t.reason),n}var jt,Mt,Nt,Pt=__esmMin(()=>{_e(),jt=Symbol(`kCapture`),Mt=Symbol.for(`nodejs.rejection`),Nt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=Mt;static _captureRejections=!1;static get captureRejections(){return EventEmitter._captureRejections}static set captureRejections(t){if(typeof t!=`boolean`)throw TypeError(`The "captureRejections" argument must be of type boolean.`);EventEmitter._captureRejections=t}_events;_eventsCount;_maxListeners;[jt];constructor(t){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[jt]=t?.captureRejections??EventEmitter._captureRejections}setMaxListeners(t){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+t);return this._maxListeners=t,this}getMaxListeners(){return this._maxListeners??EventEmitter.defaultMaxListeners}emit(t,...n){let S=this._events,C=t===`error`;if(S!==void 0)C&&S[EventEmitter.errorMonitor]!==void 0&&this.emit(EventEmitter.errorMonitor,...n),C&&=S.error===void 0;else if(!C)return!1;if(C){let t;if(t=n.length>0?n[0]:Error(`Unhandled error.`),t instanceof Error)throw t;let S=Error(`Unhandled error. (`+t+`)`);throw S.context=t,S}let N=S[t];if(N===void 0)return!1;if(typeof N==`function`){let S=N.apply(this,n);S!=null&&this[jt]&&this._addCatch(S,t,n)}else{let S=arrayClone(N),C=S.length;for(let N=0;N<C;++N){let C=S[N].apply(this,n);C!=null&&this[jt]&&this._addCatch(C,t,n)}}return!0}_addCatch(t,n,S){typeof t?.then==`function`&&t.then(void 0,t=>{let C=this[Mt];if(typeof C==`function`)C.call(this,t,n,...S);else{let n=this[jt];try{this[jt]=!1,this.emit(`error`,t)}finally{this[jt]=n}}})}addListener(t,n){return this._addListener(t,n,!1)}on(t,n){return this._addListener(t,n,!1)}prependListener(t,n){return this._addListener(t,n,!0)}_addListener(t,n,S){checkListener(n);let C=this._events;C===void 0?(C=this._events=Object.create(null),this._eventsCount=0):C.newListener!==void 0&&(this.emit(`newListener`,t,n.listener??n),C=this._events);let N=C[t];N===void 0?(C[t]=n,++this._eventsCount):typeof N==`function`?C[t]=S?[n,N]:[N,n]:S?N.unshift(n):N.push(n);let F=this.getMaxListeners();if(F>0){let n=typeof C[t]==`function`?1:C[t].length;if(n>F&&!C[t].warned){typeof C[t]!=`function`&&(C[t].warned=!0);let S=Error(`Possible EventEmitter memory leak detected. ${n} ${String(t)} listeners added to [${this.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);S.name=`MaxListenersExceededWarning`,ge.warn(S.message)}}return this}once(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this}prependOnceListener(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this}removeListener(t,n){checkListener(n);let S=this._events;if(S===void 0)return this;let C=S[t];if(C===void 0)return this;if(C===n||C.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete S[t],S.removeListener&&this.emit(`removeListener`,t,C.listener??n));else if(typeof C!=`function`){let N=-1;for(let t=C.length-1;t>=0;t--)if(C[t]===n||C[t].listener===n){N=t;break}if(N<0)return this;N===0?C.shift():spliceOne(C,N),C.length===1&&(S[t]=C[0]),S.removeListener!==void 0&&this.emit(`removeListener`,t,n.listener??n)}return this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=this._events;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){let t=Object.keys(n);for(let n=0;n<t.length;++n){let S=t[n];S!==`removeListener`&&this.removeAllListeners(S)}return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}let S=n[t];if(typeof S==`function`)this.removeListener(t,S);else if(S!==void 0)for(let n=S.length-1;n>=0;n--)this.removeListener(t,S[n]);return this}listeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S.listener??S]:unwrapListeners(S)}rawListeners(t){let n=this._events;if(n===void 0)return[];let S=n[t];return S===void 0?[]:typeof S==`function`?[S]:arrayClone(S)}listenerCount(t){let n=this._events;if(n===void 0)return 0;let S=n[t];return S===void 0?0:typeof S==`function`?1:S.length}eventNames(){return(this._eventsCount??0)>0?Reflect.ownKeys(this._events):[]}static once(t,n,S){return new Promise((C,N)=>{let F=S?.signal;if(F?.aborted){N(createAbortError$2(F));return}if(typeof t.addEventListener==`function`){let S=t,handler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),C(t)},errorHandler=t=>{F&&F.removeEventListener(`abort`,abortHandler),S.removeEventListener(`error`,errorHandler),N(t)},abortHandler=()=>{S.removeEventListener(n,handler),S.removeEventListener(`error`,errorHandler),N(createAbortError$2(F))};S.addEventListener(n,handler,{once:!0}),n!==`error`&&S.addEventListener(`error`,errorHandler,{once:!0}),F&&F.addEventListener(`abort`,abortHandler,{once:!0});return}let I=t,eventHandler=(...t)=>{F&&F.removeEventListener(`abort`,abortHandler),errorHandler!==void 0&&I.removeListener(`error`,errorHandler),C(t)},errorHandler;n!==`error`&&(errorHandler=t=>{I.removeListener(n,eventHandler),F&&F.removeEventListener(`abort`,abortHandler),N(t)},I.once(`error`,errorHandler)),I.once(n,eventHandler);let abortHandler=()=>{I.removeListener(n,eventHandler),errorHandler&&I.removeListener(`error`,errorHandler),N(createAbortError$2(F))};F&&F.addEventListener(`abort`,abortHandler,{once:!0})})}static on(t,n,S){let C=S?.signal;if(C?.aborted)throw createAbortError$2(C);let N=S?.highWaterMark??2**53-1,F=S?.lowWaterMark??1;validateNumber(N,`highWaterMark`),validateNumber(F,`lowWaterMark`);let I=[],H=[],W=null,q=!1,Y=!1,eventHandler=(...n)=>{if(H.length>0){let{resolve:t}=H.shift();t({value:n,done:!1})}else I.push(n),I.length>=N&&!Y&&(Y=!0,typeof t.pause==`function`&&t.pause())},errorHandler=t=>{if(W=t,H.length>0){let{reject:n}=H.shift();n(t)}X.return()},abortHandler=()=>{errorHandler(createAbortError$2(C))};t.on(n,eventHandler),n!==`error`&&t.on(`error`,errorHandler),C&&C.addEventListener(`abort`,abortHandler,{once:!0});let cleanup=()=>{t.removeListener(n,eventHandler),t.removeListener(`error`,errorHandler),C&&C.removeEventListener(`abort`,abortHandler),q=!0;for(let{resolve:t}of H)t({value:void 0,done:!0});H.length=0,I.length=0},X={next(){if(I.length>0){let n=I.shift();return Y&&I.length<F&&(Y=!1,typeof t.resume==`function`&&t.resume()),Promise.resolve({value:n,done:!1})}if(W){let t=Promise.reject(W);return W=null,t}return q?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{H.push({resolve:t,reject:n})})},return(){return cleanup(),Promise.resolve({value:void 0,done:!0})},throw(t){return q||(W=t,cleanup()),Promise.reject(t)},[Symbol.asyncIterator](){return this}};return X}static listenerCount(t,n){return t.listenerCount(n)}static getEventListeners(t,n){return typeof t.listeners==`function`?t.listeners(n):[]}static setMaxListeners(t,...n){if(validateNumber(t,`n`),t<0)throw RangeError(`The value of "n" is out of range.`);if(n.length===0)EventEmitter.defaultMaxListeners=t;else for(let S of n)typeof S.setMaxListeners==`function`&&S.setMaxListeners(t)}static getMaxListeners(t){return typeof t.getMaxListeners==`function`?t.getMaxListeners():EventEmitter.defaultMaxListeners}static addAbortListener(t,n){t.aborted&&Promise.resolve().then(()=>n());let handler=()=>n();return t.addEventListener(`abort`,handler,{once:!0}),{[Symbol.dispose](){t.removeEventListener(`abort`,handler)}}}},Nt.EventEmitter=Nt;for(let t of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let n=Nt.prototype[t];typeof n==`function`&&Object.defineProperty(Nt.prototype,t,{enumerable:!0,configurable:!0,writable:!0,value:n})}Object.defineProperty(Nt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Nt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Nt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),Ft=__exportAll$5({EventEmitter:()=>It,addAbortListener:()=>Kt,captureRejectionSymbol:()=>Lt,default:()=>It,defaultMaxListeners:()=>zt,errorMonitor:()=>Rt,getEventListeners:()=>Wt,getMaxListeners:()=>Vt,listenerCount:()=>Gt,"module.exports":()=>It,on:()=>Ut,once:()=>Ht,setMaxListeners:()=>Bt}),It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt=__esmMin(()=>{Pt(),ze(),It=makeCallable(Nt),It.EventEmitter=It,Lt=It.captureRejectionSymbol,Rt=It.errorMonitor,zt=It.defaultMaxListeners,Bt=It.setMaxListeners,Vt=It.getMaxListeners,Ht=It.once,Ut=It.on,Wt=It.getEventListeners,Gt=It.listenerCount,Kt=It.addAbortListener});function normalizeAndValidateEncoding(t){return t&&checkEncoding(t),normalizeEncoding(t)}function utf8DecodeMaximalSubpart(t,n,S){let C=``,N=n;for(;N<S;){let n=t[N];if(n<=127){C+=String.fromCharCode(n),N++;continue}if(n>=194&&n<=223){N+1<S&&t[N+1]>=128&&t[N+1]<=191?(C+=String.fromCharCode((n&31)<<6|t[N+1]&63),N+=2):(C+=`�`,N++);continue}if(n>=224&&n<=239){let F,I;if(n===224?(F=160,I=191):n===237?(F=128,I=159):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}let q=(n&15)<<12|(H&63)<<6|W&63;C+=String.fromCharCode(q),N+=3;continue}if(n>=240&&n<=244){let F,I;if(n===240?(F=144,I=191):n===244?(F=128,I=143):(F=128,I=191),N+1>=S){C+=`�`,N++;continue}let H=t[N+1];if(H<F||H>I){C+=`�`,N++;continue}if(N+2>=S){C+=`�`,N+=2;continue}let W=t[N+2];if(W<128||W>191){C+=`�`,N+=2;continue}if(N+3>=S){C+=`�`,N+=3;continue}let q=t[N+3];if(q<128||q>191){C+=`�`,N+=3;continue}let Y=(n&7)<<18|(H&63)<<12|(W&63)<<6|q&63;C+=String.fromCharCode(55296+(Y-65536>>10),56320+(Y-65536&1023)),N+=4;continue}C+=`�`,N++}return C}function utf8CharLength(t){return t&128?t>=194&&t<=223?2:t>=224&&t<=239?3:t>=240&&t<=244?4:0:1}function isValidContinuation(t,n,S,C){if(S===1){if(n===3)return t===224?C>=160&&C<=191:t===237?C>=128&&C<=159:C>=128&&C<=191;if(n===4)return t===240?C>=144&&C<=191:t===244?C>=128&&C<=143:C>=128&&C<=191}return C>=128&&C<=191}function writeUtf8(t,n){let S=0,C=``;if(t._lastNeed>0){for(;S<n.length&&t._lastNeed>0;){let N=n[S],F=t._lastTotal-t._lastNeed;if(isValidContinuation(t._lastLeadByte,t._lastTotal,F,N))t._lastChar[F]=N,t._lastNeed--,S++;else{C+=`�`,t._lastNeed=0,t._lastTotal=0,t._lastLeadByte=0;break}}if(t._lastNeed===0&&t._lastTotal>0&&(C+=utf8DecodeMaximalSubpart(t._lastChar,0,t._lastTotal),t._lastTotal=0,t._lastLeadByte=0),t._lastNeed>0)return C}let N=n.length;for(let C=0;C<Math.min(4,n.length-S);C++){let F=n.length-1-C;if(F<S)break;let I=n[F];if((I&192)!=128){let S=utf8CharLength(I);if(S>0&&I>=128){let C=n.length-F;if(C<S){let H=!0;for(let t=1;t<C;t++)if(!isValidContinuation(I,S,t,n[F+t])){H=!1;break}if(H){N=F;for(let S=0;S<C;S++)t._lastChar[S]=n[F+S];t._lastNeed=S-C,t._lastTotal=S,t._lastLeadByte=I}}}break}}return N>S&&(C+=utf8DecodeMaximalSubpart(n,S,N)),C}function writeUtf16le(t,n){let S=``,C=0;if(t._lastNeed>0){let N=t._lastTotal-t._lastNeed,F=Math.min(t._lastNeed,n.length);for(let S=0;S<F;S++)t._lastChar[N+S]=n[S];if(t._lastNeed-=F,C=F,t._lastNeed>0)return``;let I=t._lastTotal,H=0;for(;H+1<I;){let N=t._lastChar[H]|t._lastChar[H+1]<<8;if(H+=2,N>=55296&&N<=56319){if(H+1<I){let n=t._lastChar[H]|t._lastChar[H+1]<<8;if(n>=56320&&n<=57343){S+=String.fromCharCode(N,n),H+=2;continue}}if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C>=n.length)return t._lastChar[0]=t._lastChar[H-2],t._lastChar[1]=t._lastChar[H-1],t._lastNeed=2,t._lastTotal=4,S}S+=String.fromCharCode(N)}t._lastTotal=0}for(;C+1<n.length;){let N=n[C]|n[C+1]<<8;if(C+=2,N>=55296&&N<=56319)if(C+1<n.length){let t=n[C]|n[C+1]<<8;if(t>=56320&&t<=57343){S+=String.fromCharCode(N,t),C+=2;continue}}else if(C<n.length)return S+=String.fromCharCode(N),t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2,S;else return t._lastChar[0]=n[C-2],t._lastChar[1]=n[C-1],t._lastNeed=2,t._lastTotal=4,S;S+=String.fromCharCode(N)}return C<n.length&&(t._lastChar[0]=n[C],t._lastNeed=1,t._lastTotal=2),S}function writeBase64(t,n){let S=0;if(t._lastNeed>0){let C=Math.min(t._lastNeed,n.length);for(let S=0;S<C;S++)t._lastChar[t._lastTotal-t._lastNeed+S]=n[S],t._lastNeed--;if(S=C,t._lastNeed>0)return``}let C=n.length-S,N=C-C%3,F=``;t._lastTotal>0&&t._lastNeed===0&&(F+=base64Encode$1(t._lastChar.subarray(0,t._lastTotal)),t._lastTotal=0),N>0&&(F+=base64Encode$1(n.subarray(S,S+N)));let I=C-N;if(I>0){for(let C=0;C<I;C++)t._lastChar[C]=n[S+N+C];t._lastNeed=3-I,t._lastTotal=3}return F}function decodeAscii(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]&127);return n}function decodeLatin1(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return n}function decodeHex(t){let n=``;for(let S=0;S<t.length;S++)n+=t[S].toString(16).padStart(2,`0`);return n}var Jt,Yt=__esmMin(()=>{ot(),Jt=function StringDecoder(t){this.encoding=normalizeAndValidateEncoding(t),this._lastNeed=0,this._lastTotal=0,this._lastLeadByte=0,this.encoding===`utf8`||this.encoding===`utf16le`?this._lastChar=new Uint8Array(4):this.encoding===`base64`?this._lastChar=new Uint8Array(3):this._lastChar=new Uint8Array},Jt.prototype.write=function write(t){if(t.length===0)return``;switch(this.encoding){case`utf8`:return writeUtf8(this,t);case`utf16le`:return writeUtf16le(this,t);case`base64`:return writeBase64(this,t);case`ascii`:return decodeAscii(t);case`latin1`:return decodeLatin1(t);case`hex`:return decodeHex(t);default:return decodeAscii(t)}},Jt.prototype.end=function end(t){let n=``;if(t&&t.length>0&&(n=this.write(t)),this.encoding===`utf8`&&this._lastNeed>0)n+=`�`,this._lastNeed=0,this._lastTotal=0;else if(this.encoding===`utf16le`&&this._lastNeed>0){let t=this._lastTotal-this._lastNeed;for(let S=0;S+1<t;S+=2)n+=String.fromCharCode(this._lastChar[S]|this._lastChar[S+1]<<8);this._lastNeed=0,this._lastTotal=0}else if(this.encoding===`base64`&&this._lastNeed>0){let t=this._lastChar.subarray(0,this._lastTotal-this._lastNeed);n+=base64Encode$1(t),this._lastNeed=0,this._lastTotal=0}return n}}),Xt,ProcessWriteStream,ProcessReadStream,Zt=__esmMin(()=>{_e(),dt(),At(),qt(),ze(),Yt(),Xt=new TextEncoder,ProcessWriteStream=class extends It{fd;writable=!0;_outGio=null;constructor(t){super(),this.fd=t;let n=getGioNamespace();if(n){let t=n.UnixOutputStream??n.OutputStream;if(t)try{this._outGio=t.new(this.fd,!1)}catch{}}}write(t){if(this._outGio)try{let n=typeof t==`string`?Xt.encode(t):t;return this._outGio.write_all(n,null),!0}catch{}return this.fd===2?ge.error(t):ge.log(t),!0}get isTTY(){let t=nativeIsTty(this.fd);if(t!==null)return t;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t)return!!t.log_writer_supports_color(this.fd)}catch{}return!1}get columns(){let t=nativeTerminalSize(this.fd);if(t)return t.columns;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`COLUMNS`)??`0`,10);if(n>0)return n}}catch{}return 80}end(){}destroy(){}get rows(){let t=nativeTerminalSize(this.fd);if(t)return t.rows;try{let t=getGjsGlobal().imports?.gi?.GLib;if(t){let n=parseInt(t.getenv(`LINES`)??`0`,10);if(n>0)return n}}catch{}return 24}},ProcessReadStream=class extends It{fd;isRaw=!1;_gio=null;_stdinGio=null;_reading=!1;_flowing=!1;_mainLoopHeld=!1;_pendingRead=!1;_decoder=null;constructor(t){super(),this.fd=t,this._gio=getGioNamespace()}get isTTY(){return nativeIsTty(this.fd)??!1}setRawMode(t){return noteRawMode(this.fd,t,t=>nativeSetRawMode(this.fd,t)===!0)?(this.isRaw=t,this):(noteRawMode(this.fd,t,t=>this._setRawModeViaStty(t)),this.isRaw=t,this)}_setRawModeViaStty(t){try{let n=globalThis.imports?.gi,S=n?.Gio??n?.Gio;if(!S)return!1;let C=S.SubprocessFlags?.STDIN_INHERIT??2,N=t?[`stty`,`-icanon`,`-echo`,`-icrnl`,`-isig`,`min`,`1`,`time`,`0`]:[`stty`,`icanon`,`echo`,`icrnl`,`isig`],F=new S.SubprocessLauncher({flags:C}).spawnv(N);return F.wait(null),F.get_successful()}catch{return!1}}setEncoding(t){return this._decoder=new Jt(t),this}_pushData(t){if(this._decoder){let n=this._decoder.write(t);n.length>0&&this.emit(`data`,n)}else this.emit(`data`,t)}on(t,n){let S=t===`data`&&this.listenerCount(`data`)===0;return super.on(t,n),S&&t===`data`&&this.resume(),this}addListener(t,n){return this.on(t,n)}once(t,n){return super.once(t,n),this}removeListener(t,n){return super.removeListener(t,n),t===`data`&&this.listenerCount(`data`)===0&&this.pause(),this}off(t,n){return this.removeListener(t,n)}removeAllListeners(t){let n=t===void 0||t===`data`?this.listenerCount(`data`)>0:!1;return super.removeAllListeners(t),n&&this.listenerCount(`data`)===0&&this.pause(),this}resume(){return this._flowing=!0,this._gio&&this.fd===0&&!this._reading&&this._startReading(),this}pause(){if(this._flowing=!1,this._reading=!1,this._mainLoopHeld){this._mainLoopHeld=!1;let t=globalThis.imports?.gi,n=t?.GLib??t?.GLib;n?.idle_add?n.idle_add(300,()=>(this._mainLoopHeld||quitMainLoop(),!1)):quitMainLoop()}return this}read(){return null}_startReading(){if(!this._gio||this._reading)return;if(this._pendingRead){this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop());return}if(this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop()),!this._stdinGio){let t=this._gio.UnixInputStream??this._gio.InputStream;if(!t){this._reading=!1;return}try{this._stdinGio=t.new(this.fd,!1)}catch{this._reading=!1;return}}let loop=()=>{if(!this._reading){this._pendingRead=!1;return}this._pendingRead=!0,this._stdinGio.read_bytes_async(4096,0,null,(t,n)=>{this._pendingRead=!1;try{let S=t.read_bytes_finish(n)?.get_data?.()??null;if(S&&S.byteLength>0)this._pushData(Buffer.from(S));else if(S!==null&&S.byteLength===0){if(this._reading=!1,this._decoder){let t=this._decoder.end();t.length>0&&this.emit(`data`,t)}this.emit(`end`);return}}catch{this._reading=!1;return}this._reading&&loop()})};loop()}}});function defineLazy(t,n,S){Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let C=S();return Object.defineProperty(t,n,{value:C,configurable:!0,enumerable:!0,writable:!1}),C}})}var Qt,Process,$t=__esmMin(()=>{_e(),gt(),_t(),vt(),pt(),yt(),St(),Zt(),At(),qt(),Qt=Date.now(),Process=class extends It{platform;arch;env;argv;argv0;execPath;pid;ppid;version;versions;title;execArgv;config;exitCode;constructor(){super(),this.on(`exit`,()=>{try{restoreClaimedRawModes()}catch(t){ge.error(`@gjsify/process: raw mode could not be restored:`,t)}}),defineLazy(this,`platform`,detectPlatform$1),defineLazy(this,`arch`,detectArch),this.env=getEnvProxy(),this.argv=getArgv(),this.argv0=this.argv[0]||`gjs`,this.execPath=getExecPath(),this.execArgv=globalThis.process?.execArgv??[],this.config=globalThis.process?.config??{target_defaults:{},variables:{}},this.pid=getPid$1(),this.ppid=detectPpid();let t=detectVersionInfo();this.version=t.version,this.versions=t.versions,this.title=t.title,this.on(`newListener`,t=>{isDeliverableSignal(t)&&armSignal(t,t=>this.emit(t,t))}),this.on(`removeListener`,t=>{isDeliverableSignal(t)&&this.listenerCount(t)===0&&disarmSignal(t)})}cwd(){return getCwd()}chdir(t){chdir(t)}kill(t,n){return killPid(t,n)}exit(t){return this.exitCode=t??this.exitCode??0,this.emit(`exit`,this.exitCode),exitProcess(this.exitCode)}nextTick(t,...n){typeof queueMicrotask==`function`?queueMicrotask(()=>t(...n)):Promise.resolve().then(()=>t(...n))}hrtime(t){return hrtime(t)}uptime(){return(Date.now()-Qt)/1e3}memoryUsage(){return memoryUsage()}cpuUsage(t){return cpuUsage(t)}stdout=new ProcessWriteStream(1);stderr=new ProcessWriteStream(2);stdin=new ProcessReadStream(0);abort(){this.exit(1)}umask(t){let n=readUmask();return t!==void 0&&!this._umaskWarned&&(this._umaskWarned=!0,this.emitWarning(`process.umask(0${t.toString(8)}) cannot change the file-creation mask under GJS — there is no umask(2) binding, so the mask is UNCHANGED. Pass an explicit \`mode\` to open/mkdir/writeFile instead; the kernel applies it atomically at creation.`,`UnsupportedWarning`)),n}_umaskWarned=!1;emitWarning(t,n){ge.warn(typeof t==`string`?`(${n||`Warning`}): ${t}`:t.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}}),en,tn,nn,rn=__esmMin(()=>{if(pt(),$t(),At(),en=new Process,kt)try{let t=new kt.ResizeWatcher;t.connect(`resized`,(t,n,S)=>{en.stdout.emit(`resize`),en.stderr.emit(`resize`)}),t.start()}catch{}en.platform,en.arch,en.env,en.argv,en.argv0,en.execPath,en.pid,en.ppid,en.version,en.versions,en.cwd.bind(en),en.chdir.bind(en),en.exit.bind(en),en.nextTick.bind(en),Object.assign(en.hrtime.bind(en),{bigint:hrtimeBigint}),en.uptime.bind(en),en.memoryUsage.bind(en),en.cpuUsage.bind(en),en.kill.bind(en),en.abort.bind(en),en.umask.bind(en),en.emitWarning.bind(en),en.execArgv,en.config,tn=en.stdout,en.stderr,nn=en.stdin});ze(),rn(),typeof Promise.withResolvers!=`function`&&(Promise.withResolvers=function(){let t,n;return{promise:new Promise((S,C)=>{t=S,n=C}),resolve:t,reject:n}}),initErrorV8Methods(Error),`global`in globalThis||Object.defineProperty(globalThis,"global",{value:globalThis,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(globalThis,"process",{value:en,enumerable:!1,writable:!0,configurable:!0}),ze(),typeof globalThis.structuredClone!=`function`&&Object.defineProperty(globalThis,"structuredClone",{value:structuredClone$1,enumerable:!0,writable:!0,configurable:!0});function getGLib(){return globalThis.imports?.gi?.GLib}const an=getGLib()!==void 0;function reportTimerThrow(t,n){try{t.log_default_handler(`gjsify-timers`,t.LogLevelFlags.LEVEL_WARNING,`Uncaught exception in a timer callback: ${String(n)}\n${n?.stack??``}`,null)}catch{}}var GjsifyTimeout=class{_id=null;_refed=!0;_callback;_delay;_args;_repeat;constructor(t,n,S,C){this._callback=t,this._delay=n,this._args=S,this._repeat=C,this._schedule()}_schedule(){let t=getGLib();if(!t)return;let n=t.timeout_add.bind(t);this._id=n(t.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){reportTimerThrow(t,n)}return this._repeat?t.SOURCE_CONTINUE:(this._id=null,t.SOURCE_REMOVE)})}unref(){return this._refed=!1,this}ref(){return this._refed=!0,this}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null)}close(){return this._cancel(),this}[Symbol.toPrimitive](){return this._id}[Symbol.dispose](){this._cancel()}};function removeById(t){t instanceof GjsifyTimeout||typeof t==`object`&&t&&`_cancel`in t?t._cancel():typeof t==`object`&&t&&typeof t.close==`function`?t.close():typeof t==`number`&&getGLib()?.Source.remove(t)}if(an){let setT=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!1),setI=(t,n=0,...S)=>new GjsifyTimeout(t,Math.max(0,n|0),S,!0),t=globalThis;t.setTimeout=setT,t.clearTimeout=removeById,t.setInterval=setI,t.clearInterval=removeById}function setImmediate$1(t,...n){return setTimeout(t,0,...n)}__name$1(setImmediate$1,`setImmediate`);function clearImmediate(t){clearTimeout(t)}`setImmediate`in globalThis||Object.defineProperty(globalThis,"setImmediate",{value:setImmediate$1,enumerable:!0,writable:!0,configurable:!0}),`clearImmediate`in globalThis||Object.defineProperty(globalThis,"clearImmediate",{value:clearImmediate,enumerable:!0,writable:!0,configurable:!0});var on,sn,cn=__esmMin(()=>{on=Object.defineProperty,sn=__name$1((t,n)=>{let S={};for(var C in t)on(S,C,{get:t[C],enumerable:!0});return n||on(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function assertPath(t){if(typeof t!=`string`)throw TypeError(`The "path" argument must be of type string. Received type `+typeof t)}function isPosixPathSeparator(t){return t===47}function isPathSeparator(t){return t===47||t===92}function isWindowsDeviceRoot(t){return t>=65&&t<=90||t>=97&&t<=122}function normalizeString$1(t,n,S,C){let N=``,F=0,I=-1,H=0,W;for(let q=0;q<=t.length;++q){if(q<t.length)W=t.charCodeAt(q);else if(C(W))break;else W=47;if(C(W)){if(!(I===q-1||H===1))if(I!==q-1&&H===2){if(N.length<2||F!==2||N.charCodeAt(N.length-1)!==46||N.charCodeAt(N.length-2)!==46){if(N.length>2){let t=N.lastIndexOf(S);t===-1?(N=``,F=0):(N=N.slice(0,t),F=N.length-1-N.lastIndexOf(S)),I=q,H=0;continue}else if(N.length===2||N.length===1){N=``,F=0,I=q,H=0;continue}}n&&(N.length>0?N+=`${S}..`:N=`..`,F=2)}else N.length>0?N+=S+t.slice(I+1,q):N=t.slice(I+1,q),F=q-I-1;I=q,H=0}else W===46&&H!==-1?++H:H=-1}return N}function _format(t,n){if(typeof n!=`object`||!n)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof n);let S=n,C=S.dir||S.root,N=S.base||(S.name||``)+formatExt(S.ext);return C?C===S.root?C+N:C+t+N:N}function formatExt(t){return t?`${t[0]===`.`?``:`.`}${t}`:``}var ln=__esmMin(()=>{__name$1(normalizeString$1,`normalizeString`)});function posixCwd(){if(typeof globalThis.process?.cwd==`function`)return globalThis.process.cwd();try{let t=globalThis.imports?.gi?.GLib;if(t?.get_current_dir)return t.get_current_dir()}catch{}return`/`}function resolve$4(...t){let n=``,S=!1;for(let C=t.length-1;C>=-1&&!S;C--){let N;if(C>=0){if(N=t[C],assertPath(N),N.length===0)continue}else N=posixCwd();n=`${N}/${n}`,S=N.charCodeAt(0)===47}return n=normalizeString$1(n,!S,`/`,isPosixPathSeparator),S?n.length>0?`/${n}`:`/`:n.length>0?n:`.`}function normalize$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=t.charCodeAt(t.length-1)===47,C=normalizeString$1(t,!n,`/`,isPosixPathSeparator);return C.length===0&&!n&&(C=`.`),C.length>0&&S&&(C+=`/`),n?`/${C}`:C}function isAbsolute$2(t){return assertPath(t),t.length>0&&t.charCodeAt(0)===47}function join$3(...t){if(t.length===0)return`.`;let n;for(let S=0;S<t.length;++S){let C=t[S];assertPath(C),C.length>0&&(n===void 0?n=C:n+=`/${C}`)}return n===void 0?`.`:normalize$2(n)}function relative$1(t,n){if(assertPath(t),assertPath(n),t===n||(t=resolve$4(t),n=resolve$4(n),t===n))return``;let S=t.length,C=S-1,N=1,F=n.length-N,I=C<F?C:F,H=-1,W=0;for(;W<=I;++W){if(W===I){if(F>I){if(n.charCodeAt(N+W)===47)return n.slice(N+W+1);if(W===0)return n.slice(N+W)}else C>I&&(t.charCodeAt(1+W)===47?H=W:W===0&&(H=0));break}let S=t.charCodeAt(1+W);if(S!==n.charCodeAt(N+W))break;S===47&&(H=W)}let q=``;for(W=1+H+1;W<=S;++W)(W===S||t.charCodeAt(W)===47)&&(q.length===0?q+=`..`:q+=`/..`);return q.length>0?q+n.slice(N+H):(N+=H,n.charCodeAt(N)===47&&++N,n.slice(N))}function toNamespacedPath$1(t){return t}function dirname$2(t){if(assertPath(t),t.length===0)return`.`;let n=t.charCodeAt(0)===47,S=-1,C=!0;for(let n=t.length-1;n>=1;--n)if(t.charCodeAt(n)===47){if(!C){S=n;break}}else C=!1;return S===-1?n?`/`:`.`:n&&S===1?`//`:t.slice(0,S)}function basename$2(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=0;--H){let W=t.charCodeAt(H);if(W===47){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=0;--n)if(t.charCodeAt(n)===47){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$2(t){assertPath(t);let n=-1,S=0,C=-1,N=!0,F=0;for(let I=t.length-1;I>=0;--I){let H=t.charCodeAt(I);if(H===47){if(!N){S=I+1;break}continue}C===-1&&(N=!1,C=I+1),H===46?n===-1?n=I:F!==1&&(F=1):n!==-1&&(F=-1)}return n===-1||C===-1||F===0||F===1&&n===C-1&&n===S+1?``:t.slice(n,C)}function format$3(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`/`,t)}function parse$5(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.charCodeAt(0)===47,C;S?(n.root=`/`,C=1):C=0;let N=-1,F=0,I=-1,H=!0,W=t.length-1,q=0;for(;W>=C;--W){let n=t.charCodeAt(W);if(n===47){if(!H){F=W+1;break}continue}I===-1&&(H=!1,I=W+1),n===46?N===-1?N=W:q!==1&&(q=1):N!==-1&&(q=-1)}return N===-1||I===-1||q===0||q===1&&N===I-1&&N===F+1?I!==-1&&(F===0&&S?n.base=n.name=t.slice(1,I):n.base=n.name=t.slice(F,I)):(F===0&&S?(n.name=t.slice(1,N),n.base=t.slice(1,I)):(n.name=t.slice(F,N),n.base=t.slice(F,I)),n.ext=t.slice(N,I)),F>0?n.dir=t.slice(0,F-1):S&&(n.dir=`/`),n}var un,dn=__esmMin(()=>{cn(),ln(),un=sn({basename:()=>basename$2,delimiter:()=>`:`,dirname:()=>dirname$2,extname:()=>extname$2,format:()=>format$3,isAbsolute:()=>isAbsolute$2,join:()=>join$3,normalize:()=>normalize$2,parse:()=>parse$5,relative:()=>relative$1,resolve:()=>resolve$4,sep:()=>`/`,toNamespacedPath:()=>toNamespacedPath$1}),__name$1(resolve$4,`resolve`),__name$1(normalize$2,`normalize`),__name$1(isAbsolute$2,`isAbsolute`),__name$1(join$3,`join`),__name$1(relative$1,`relative`),__name$1(toNamespacedPath$1,`toNamespacedPath`),__name$1(dirname$2,`dirname`),__name$1(basename$2,`basename`),__name$1(extname$2,`extname`),__name$1(format$3,`format`),__name$1(parse$5,`parse`)});function cwd$1(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():`/`}function resolve$3(...t){let n=``,S=``,C=!1;for(let N=t.length-1;N>=-1;N--){let F;if(N>=0){if(F=t[N],assertPath(F),F.length===0)continue}else n.length===0?F=cwd$1():(F=globalThis.process?.env?.[`=${n}`]||cwd$1(),F.slice(0,2).toLowerCase()!==n.toLowerCase()&&F.charCodeAt(2)===92&&(F=`${n}\\`));let I=F.length,H=0,W=``,q=!1,Y=F.charCodeAt(0);if(I===1)isPathSeparator(Y)&&(H=1,q=!0);else if(isPathSeparator(Y))if(q=!0,isPathSeparator(F.charCodeAt(1))){let t=matchUncRoot(F);t&&(W=t.device,H=t.rootEnd)}else H=1;else isWindowsDeviceRoot(Y)&&F.charCodeAt(1)===58&&(W=F.slice(0,2),H=2,I>2&&isPathSeparator(F.charCodeAt(2))&&(q=!0,H=3));if(W.length>0)if(n.length>0){if(W.toLowerCase()!==n.toLowerCase())continue}else n=W;if(C){if(n.length>0)break}else if(S=`${F.slice(H)}\\${S}`,C=q,q&&n.length>0)break}return S=normalizeString$1(S,!C,`\\`,isPathSeparator),C?`${n}\\${S}`:`${n}${S}`||`.`}function matchUncRoot(t){let n=t.length,S=2,C=S;for(;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;if(S>=n||S===C)return;let N=t.slice(C,S);for(C=S;S<n&&isPathSeparator(t.charCodeAt(S));)S++;if(!(S>=n||S===C)){for(C=S;S<n&&!isPathSeparator(t.charCodeAt(S));)S++;return N===`.`||N===`?`?{device:`\\\\${N}`,rootEnd:4,shareOnly:!1}:{device:`\\\\${N}\\${t.slice(C,S)}`,rootEnd:S,shareOnly:S===n}}}function normalize$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=t.charCodeAt(0);if(n===1)return isPosixPathSeparator(S)?`\\`:t;let C=0,N,F=!1;if(isPathSeparator(S))if(F=!0,isPathSeparator(t.charCodeAt(1))){let n=matchUncRoot(t);if(n?.shareOnly)return`${n.device}\\`;if(n&&(N=n.device,C=n.rootEnd,N.length===3)){let n=t.slice(4,t.indexOf(`:`)+1);isWindowsReservedName(n,n.length-1)&&(N=`\\\\?\\${n}`,C=4+n.length)}}else C=1;else{let I=t.indexOf(`:`);I>0&&(isWindowsDeviceRoot(S)&&I===1?(N=t.slice(0,2),C=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(F=!0,C=3)):isWindowsReservedName(t,I)&&(N=t.slice(0,I+1),C=I+1))}let I=C<n?normalizeString$1(t.slice(C),!F,`\\`,isPathSeparator):``;if(I.length===0&&!F&&(I=`.`),I.length>0&&isPathSeparator(t.charCodeAt(n-1))&&(I+=`\\`),!F&&N===void 0&&t.includes(`:`)){if(I.length>=2&&isWindowsDeviceRoot(I.charCodeAt(0))&&I.charCodeAt(1)===58)return`.\\${I}`;let S=t.indexOf(`:`);do if(S===n-1||isPathSeparator(t.charCodeAt(S+1)))return`.\\${I}`;while((S=t.indexOf(`:`,S+1))!==-1)}return isWindowsReservedName(t,t.indexOf(`:`))?`.\\${N??``}${I}`:N===void 0?F?`\\${I}`:I:F?`${N}\\${I}`:`${N}${I}`}function isWindowsReservedName(t,n){return pn.has(t.slice(0,n).toUpperCase())}function isAbsolute$1(t){assertPath(t);let n=t.length;if(n===0)return!1;let S=t.charCodeAt(0);return!!(isPathSeparator(S)||isWindowsDeviceRoot(S)&&n>2&&t.charCodeAt(1)===58&&isPathSeparator(t.charCodeAt(2)))}function join$2(...t){if(t.length===0)return`.`;let n,S;for(let C=0;C<t.length;++C){let N=t[C];assertPath(N),N.length>0&&(n===void 0?n=S=N:n+=`\\${N}`)}if(n===void 0)return`.`;let C=!0,N=0;if(isPathSeparator(S.charCodeAt(0))){++N;let t=S.length;t>1&&isPathSeparator(S.charCodeAt(1))&&(++N,t>2&&(isPathSeparator(S.charCodeAt(2))?++N:C=!1))}if(C){for(;N<n.length&&isPathSeparator(n.charCodeAt(N));++N);N>=2&&(n=`\\${n.slice(N)}`)}return n.split(/\\+/).some(t=>{let n=t.indexOf(`:`);return n!==-1&&isWindowsReservedName(t,n)})?n.replace(/\//g,`\\`):normalize$1(n)}function relative(t,n){if(assertPath(t),assertPath(n),t===n)return``;let S=resolve$3(t),C=resolve$3(n);if(S===C||(t=S.toLowerCase(),n=C.toLowerCase(),t===n))return``;let N=0;for(;N<t.length&&t.charCodeAt(N)===92;++N);let F=t.length;for(;F-1>N&&t.charCodeAt(F-1)===92;--F);let I=F-N,H=0;for(;H<n.length&&n.charCodeAt(H)===92;++H);let W=n.length;for(;W-1>H&&n.charCodeAt(W-1)===92;--W);let q=W-H,Y=I<q?I:q,X=-1,Z=0;for(;Z<=Y;++Z){if(Z===Y){if(q>Y){if(n.charCodeAt(H+Z)===92)return C.slice(H+Z+1);if(Z===2)return C.slice(H+Z)}I>Y&&(t.charCodeAt(N+Z)===92?X=Z:Z===2&&(X=3));break}let S=t.charCodeAt(N+Z);if(S!==n.charCodeAt(H+Z))break;S===92&&(X=Z)}if(Z!==Y&&X===-1)return C;let te=``;for(X===-1&&(X=0),Z=N+X+1;Z<=F;++Z)(Z===F||t.charCodeAt(Z)===92)&&(te.length===0?te+=`..`:te+=`\\..`);return te.length>0?te+C.slice(H+X,W):(H+=X,C.charCodeAt(H)===92&&++H,C.slice(H,W))}function toNamespacedPath(t){if(typeof t!=`string`||t.length===0)return t;let n=resolve$3(t);if(n.length<=2)return t;if(n.charCodeAt(0)===92){if(n.charCodeAt(1)===92){let t=n.charCodeAt(2);if(t!==63&&t!==46)return`\\\\?\\UNC\\${n.slice(2)}`}}else if(isWindowsDeviceRoot(n.charCodeAt(0))&&n.charCodeAt(1)===58&&n.charCodeAt(2)===92)return`\\\\?\\${n}`;return n}function dirname$1(t){assertPath(t);let n=t.length;if(n===0)return`.`;let S=-1,C=-1,N=!0,F=0,I=t.charCodeAt(0);if(n>1)if(isPathSeparator(I)){if(S=F=1,isPathSeparator(t.charCodeAt(1))){let C=2,N=C;for(;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&isPathSeparator(t.charCodeAt(C));++C);if(C<n&&C!==N){for(N=C;C<n&&!isPathSeparator(t.charCodeAt(C));++C);if(C===n)return t;C!==N&&(S=F=C+1)}}}}else isWindowsDeviceRoot(I)&&t.charCodeAt(1)===58&&(S=F=2,n>2&&isPathSeparator(t.charCodeAt(2))&&(S=F=3));else if(isPathSeparator(I))return t;for(let S=n-1;S>=F;--S)if(isPathSeparator(t.charCodeAt(S))){if(!N){C=S;break}}else N=!1;if(C===-1){if(S===-1)return`.`;C=S}return t.slice(0,C)}function basename$1(t,n){n!==void 0&&assertPath(n),assertPath(t);let S=0,C=-1,N=!0;if(t.length>=2&&isWindowsDeviceRoot(t.charCodeAt(0))&&t.charCodeAt(1)===58&&(S=2),n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return``;let F=n.length-1,I=-1;for(let H=t.length-1;H>=S;--H){let W=t.charCodeAt(H);if(isPathSeparator(W)){if(!N){S=H+1;break}}else I===-1&&(N=!1,I=H+1),F>=0&&(W===n.charCodeAt(F)?--F===-1&&(C=H):(F=-1,C=I))}return S===C?C=I:C===-1&&(C=t.length),t.slice(S,C)}else{for(let n=t.length-1;n>=S;--n)if(isPathSeparator(t.charCodeAt(n))){if(!N){S=n+1;break}}else C===-1&&(N=!1,C=n+1);return C===-1?``:t.slice(S,C)}}function extname$1(t){assertPath(t);let n=0,S=-1,C=0,N=-1,F=!0,I=0;t.length>=2&&t.charCodeAt(1)===58&&isWindowsDeviceRoot(t.charCodeAt(0))&&(n=C=2);for(let H=t.length-1;H>=n;--H){let n=t.charCodeAt(H);if(isPathSeparator(n)){if(!F){C=H+1;break}continue}N===-1&&(F=!1,N=H+1),n===46?S===-1?S=H:I!==1&&(I=1):S!==-1&&(I=-1)}return S===-1||N===-1||I===0||I===1&&S===N-1&&S===C+1?``:t.slice(S,N)}function format$2(t){if(typeof t!=`object`||!t)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof t);return _format(`\\`,t)}function parse$4(t){assertPath(t);let n={root:``,dir:``,base:``,ext:``,name:``};if(t.length===0)return n;let S=t.length,C=0,N=t.charCodeAt(0);if(S>1)if(isPathSeparator(N)){if(C=1,isPathSeparator(t.charCodeAt(1))){let n=2,N=n;for(;n<S&&!isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&isPathSeparator(t.charCodeAt(n));++n);if(n<S&&n!==N){for(N=n;n<S&&!isPathSeparator(t.charCodeAt(n));++n);n===S?C=n:n!==N&&(C=n+1)}}}}else isWindowsDeviceRoot(N)&&t.charCodeAt(1)===58&&(C=2,S>2&&isPathSeparator(t.charCodeAt(2))&&(C=3));else if(isPathSeparator(N))return n.root=n.dir=t,n;C>0&&(n.root=t.slice(0,C));let F=-1,I=C,H=-1,W=!0,q=t.length-1,Y=0;for(;q>=C;--q){if(N=t.charCodeAt(q),isPathSeparator(N)){if(!W){I=q+1;break}continue}H===-1&&(W=!1,H=q+1),N===46?F===-1?F=q:Y!==1&&(Y=1):F!==-1&&(Y=-1)}return F===-1||H===-1||Y===0||Y===1&&F===H-1&&F===I+1?H!==-1&&(n.base=n.name=t.slice(I,H)):(n.name=t.slice(I,F),n.base=t.slice(I,H),n.ext=t.slice(F,H)),I>0&&I!==C?n.dir=t.slice(0,I-1):n.dir=n.root,n}var fn,pn,mn=__esmMin(()=>{cn(),ln(),fn=sn({basename:()=>basename$1,delimiter:()=>`;`,dirname:()=>dirname$1,extname:()=>extname$1,format:()=>format$2,isAbsolute:()=>isAbsolute$1,join:()=>join$2,normalize:()=>normalize$1,parse:()=>parse$4,relative:()=>relative,resolve:()=>resolve$3,sep:()=>`\\`,toNamespacedPath:()=>toNamespacedPath}),__name$1(cwd$1,`cwd`),__name$1(resolve$3,`resolve`),__name$1(normalize$1,`normalize`),pn=new Set([`CON`,`PRN`,`AUX`,`NUL`,...[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`¹`,`²`,`³`].flatMap(t=>[`COM${t}`,`LPT${t}`])]),__name$1(isAbsolute$1,`isAbsolute`),__name$1(join$2,`join`),__name$1(dirname$1,`dirname`),__name$1(basename$1,`basename`),__name$1(extname$1,`extname`),__name$1(format$2,`format`),__name$1(parse$4,`parse`)});function selectFlavour(t){return t===`win32`?fn:un}var hn=__esmMin(()=>{dn(),mn()}),gn=__exportAll$5({basename:()=>Tn,default:()=>An,delimiter:()=>kn,dirname:()=>wn,extname:()=>$,format:()=>En,isAbsolute:()=>bn,join:()=>xn,normalize:()=>yn,parse:()=>Dn,posix:()=>un,relative:()=>Sn,resolve:()=>vn,sep:()=>On,toNamespacedPath:()=>Cn,win32:()=>fn}),_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,$,En,Dn,On,kn,An,jn=__esmMin(()=>{dn(),mn(),hn(),ze(),_n=selectFlavour(hostOs()),{resolve:vn,normalize:yn,isAbsolute:bn,join:xn,relative:Sn,toNamespacedPath:Cn,dirname:wn,basename:Tn,extname:$,format:En,parse:Dn,sep:On,delimiter:kn}=_n,An={resolve:_n.resolve,normalize:_n.normalize,isAbsolute:_n.isAbsolute,join:_n.join,relative:_n.relative,toNamespacedPath:_n.toNamespacedPath,dirname:_n.dirname,basename:_n.basename,extname:_n.extname,format:_n.format,parse:_n.parse,sep:_n.sep,delimiter:_n.delimiter,posix:un,win32:fn}}),Mn=__exportAll$5({URL:()=>Bn,URLSearchParams:()=>Fn,default:()=>Vn,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$1,parse:()=>parse$3,pathToFileURL:()=>pathToFileURL,resolve:()=>resolve$2});function platformOrShapeIsWindows(t){return hostOs()===void 0?isWindowsPath(t):isWin32()}function parseFormUrlencoded(t){let n=[];if(!t)return n;for(let S of t.split(`&`)){if(S===``)continue;let t=S.indexOf(`=`);t===-1?n.push([decodeComponent(S),``]):n.push([decodeComponent(S.slice(0,t)),decodeComponent(S.slice(t+1))])}return n}function decodeComponent(t){try{return decodeURIComponent(t.replace(/\+/g,` `))}catch{return t}}function percentEncodeUtf8(t){let n=``;for(let S of new TextEncoder().encode(t))n+=`%${S.toString(16).toUpperCase().padStart(2,`0`)}`;return n}function encodeComponent(t){let n=``;for(let S of t)S===` `?n+=`+`:/^[A-Za-z0-9*\-._]$/.test(S)?n+=S:n+=percentEncodeUtf8(S);return n}function isSpecialScheme(t){return In.has(t)}function defaultPort(t){return In.get(t)??null}function percentEncode(t,n){let S=``;for(let C of t){let t=C.codePointAt(0);S+=t<=32||t>126||n.includes(C)?percentEncodeUtf8(C):C}return S}function encodeQuery(t,n){return percentEncode(t,n?`"#<>'`:`"#<>`)}function isSchemeChar(t){return t>=`a`&&t<=`z`||t>=`A`&&t<=`Z`||t>=`0`&&t<=`9`||t===`+`||t===`-`||t===`.`}function isAsciiDigit(t){return t!==void 0&&t>=`0`&&t<=`9`}function isHexDigit$1(t){return t!==void 0&&/^[0-9A-Fa-f]$/.test(t)}function digitPrefix(t){let n=``;for(let S of t){if(!isAsciiDigit(S))break;n+=S}return n}function hasForbiddenDomainCodePoint(t){for(let n of t){let t=n.codePointAt(0);if(t<=31||t===127||n===`%`||zn.has(n))return!0}return!1}function parseIPv6(t){let n=[0,0,0,0,0,0,0,0],S=0,C=null,N=0,at=()=>t[N];if(at()===`:`){if(t[N+1]!==`:`)return;N+=2,S++,C=S}for(;N<t.length;){if(S===8)return;if(at()===`:`){if(C!==null)return;N++,S++,C=S;continue}let F=0,I=0;for(;I<4&&isHexDigit$1(at());)F=F*16+Number.parseInt(at(),16),N++,I++;if(at()===`.`){if(I===0||(N-=I,S>6))return;let C=0;for(;N<t.length;){let t=null;if(C>0)if(at()===`.`&&C<4)N++;else return;if(!isAsciiDigit(at()))return;for(;isAsciiDigit(at());){let n=Number(at());if(t===null)t=n;else if(t===0)return;else t=t*10+n;if(t>255)return;N++}n[S]=n[S]*256+t,C++,(C===2||C===4)&&S++}if(C!==4)return;break}if(at()===`:`){if(N++,N>=t.length)return}else if(N<t.length)return;n[S]=F,S++}if(C!==null){let t=S-C;for(S=7;S!==0&&t>0;){let N=n[C+t-1];n[C+t-1]=n[S],n[S]=N,S--,t--}}else if(S!==8)return;return serializeIPv6(n)}function serializeIPv6(t){let n=null,S=1,C=-1,N=0;for(let F=0;F<8;F++){if(t[F]!==0){C=-1,N=0;continue}C===-1&&(C=F),N++,N>S&&(S=N,n=C)}let F=``,I=!1;for(let S=0;S<8;S++)if(!(I&&t[S]===0)){if(I=!1,n===S){F+=S===0?`::`:`:`,I=!0;continue}F+=t[S].toString(16),S!==7&&(F+=`:`)}return F}function parseHost(t,n){if(t.startsWith(`[`)){if(!t.endsWith(`]`))return;let n=parseIPv6(t.slice(1,-1));return n===void 0?void 0:`[${n}]`}if(n){for(let n of t)if(zn.has(n))return;return percentEncode(t,``)}if(!hasForbiddenDomainCodePoint(t))return t.toLowerCase()}function parseHostSetterValue(t,n,S,C,N){let F=t.replace(Rn,``),I=isSpecialScheme(n);if(n===`file`){let t=F.length;for(let n=0;n<F.length;n++){let S=F[n];if(S===`/`||S===`\\`||S===`?`||S===`#`){t=n;break}}let n=F.slice(0,t);if(n===``)return{host:``};let S=parseHost(n,!1);return S===void 0?void 0:{host:S===`localhost`?``:S}}let H=!1,W=``;for(let t=0;t<F.length;t++){let S=F[t];if(S===`:`&&!H){if(W===``||N)return;let S=parseHost(W,!I);if(S===void 0)return;let C=digitPrefix(F.slice(t+1));if(C===``)return{host:S};let H=Number(C);return H>65535?{host:S}:{host:S,port:H===defaultPort(n)?null:H}}if(S===`/`||S===`?`||S===`#`||I&&S===`\\`)break;S===`[`?H=!0:S===`]`&&(H=!1),W+=S}if(W===``&&(I||S||C))return;let q=parseHost(W,!I);return q===void 0?void 0:{host:q}}function isDoubleDotSegment(t){let n=t.toLowerCase();return n===`..`||n===`.%2e`||n===`%2e.`||n===`%2e%2e`}function isSingleDotSegment(t){let n=t.toLowerCase();return n===`.`||n===`%2e`}function parsePathSetterValue(t,n,S){let C=t.replace(Rn,``);if(n&&(C=C.replace(/\\/g,`/`)),C===``)return n||S?`/`:``;let N=[],F=(C.startsWith(`/`)?C.slice(1):C).split(`/`);for(let t=0;t<F.length;t++){let n=F[t],S=t===F.length-1;isDoubleDotSegment(n)?(N.pop(),S&&N.push(``)):isSingleDotSegment(n)?S&&N.push(``):N.push(percentEncode(n,'"#<>?^`{}'))}return`/`+N.join(`/`)}function bracketIPv6Host(t){return t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t}function parse$3(t,n,S){if(typeof t!=`string`)throw TypeError(`The "url" argument must be of type string. Received type `+typeof t);let C={protocol:null,slashes:null,auth:null,host:null,port:null,hostname:null,hash:null,search:null,query:null,pathname:null,path:null,href:t},N=t.trim(),F=N.indexOf(`#`);F!==-1&&(C.hash=N.slice(F),N=N.slice(0,F));let I=N.indexOf(`?`);I!==-1&&(C.search=N.slice(I),C.query=n?Object.fromEntries(new Fn(N.slice(I+1))):N.slice(I+1),N=N.slice(0,I));let H=/^([a-z][a-z0-9.+-]*:)/i.exec(N);if(H&&(C.protocol=H[1].toLowerCase(),N=N.slice(C.protocol.length)),(S||C.protocol)&&N.startsWith(`//`)&&(C.slashes=!0,N=N.slice(2)),C.slashes||C.protocol&&![`javascript:`,`data:`,`mailto:`].includes(C.protocol)){let t=-1;for(let n=0;n<N.length;n++){let S=N[n];if(S===`/`||S===`\\`){t=n;break}}let n=t===-1?N:N.slice(0,t);N=t===-1?``:N.slice(t);let S=n.lastIndexOf(`@`);S===-1?parseHostPort(n,C):(C.auth=decodeURIComponent(n.slice(0,S)),parseHostPort(n.slice(S+1),C))}return C.pathname=N||(C.slashes?`/`:null),(C.pathname!==null||C.search!==null)&&(C.path=(C.pathname||``)+(C.search||``)),C.href=format$1(C),C}function parseHostPort(t,n){if(!t)return;let S=t.indexOf(`[`);if(S!==-1){let C=t.indexOf(`]`,S);if(C!==-1){let N=t.slice(C+1);N.startsWith(`:`)&&(n.port=N.slice(1)),n.hostname=t.slice(S,C+1),n.host=n.hostname+(n.port?`:`+n.port:``);return}}let C=t.lastIndexOf(`:`);if(C!==-1){let S=t.slice(C+1);/^\d*$/.test(S)?(n.port=S||null,n.hostname=t.slice(0,C).toLowerCase()):n.hostname=t.toLowerCase()}else n.hostname=t.toLowerCase();n.host=n.hostname+(n.port?`:`+n.port:``)}function format$1(t){if(typeof t==`string`)return t;if(t instanceof Bn)return t.href;let n=t,S=``;if(n.protocol&&(S+=n.protocol),(n.slashes||n.protocol&&![`javascript:`,`data:`,`mailto:`].includes(n.protocol||``))&&(S+=`//`),n.auth&&(S+=encodeURIComponent(n.auth)+`@`),n.host?S+=n.host:(n.hostname&&(S+=n.hostname),n.port&&(S+=`:`+n.port)),n.pathname&&(S+=n.pathname),n.search)S+=n.search;else if(n.query&&typeof n.query==`object`){let t=new Fn(n.query).toString();t&&(S+=`?`+t)}return n.hash&&(S+=n.hash),S}function resolve$2(t,n){return new Bn(n,new Bn(t,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(t,n){if(typeof t==`string`&&(t=new Bn(t)),!(t instanceof Bn))throw TypeError(`The "url" argument must be of type string or URL. Received type `+typeof t);if(t.protocol!==`file:`)throw TypeError(`The URL must be of scheme file`);let S=t.pathname,C=n?.windows??platformOrShapeIsWindows(S.slice(1));for(let t=0;t<S.length;t++){if(S[t]!==`%`)continue;let n=S.codePointAt(t+2)|32,N=S[t+1]===`2`&&n===102,F=S[t+1]===`5`&&n===99;if(C&&(N||F))throw TypeError(`File URL path must not include encoded \\ or / characters`);if(N)throw TypeError(`File URL path must not include encoded / characters`)}if(t.hostname!==``&&t.hostname!==`localhost`){if(!C)throw TypeError(`File URL host must be "localhost" or empty on ${hostOs()??`this platform`}`);return`\\\\${t.hostname}${decodeURIComponent(S).replace(/\//g,`\\`)}`}if(C){let t=decodeURIComponent(S);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t.replace(/\//g,`\\`)}return decodeURIComponent(S)}function pathToFileURL(t,n){let S=n?.windows??platformOrShapeIsWindows(t),C=S&&t.startsWith(`\\\\`)?t:(S?fn:un).resolve(currentDir(),t);if(S&&C.startsWith(`\\\\`))return uncPathToFileURL(C);let N=t.charCodeAt(t.length-1);return(N===47||S&&N===92)&&C[C.length-1]!==On&&(C+=`/`),new Bn(pathToFileUrlHref(C,{windows:S}))}function currentDir(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():lt.get_current_dir()}function uncPathToFileURL(t){let n=t.startsWith(`\\\\?\\UNC\\`)?8:2,S=t.indexOf(`\\`,n);if(S===-1)throw invalidPathValue(t,`Missing UNC resource path`);if(S===2)throw invalidPathValue(t,`Empty UNC servername`);let C=t.slice(n,S);return new Bn(`file://${C===`?`?``:C}${encodePathForFileUrl(t.slice(S).replace(/\\/g,`/`))}`)}function invalidPathValue(t,n){let S=TypeError(`The argument 'path' ${n}. Received '${t}'`);return S.code=`ERR_INVALID_ARG_VALUE`,S}function domainToASCII(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}function domainToUnicode(t){try{return new Bn(`http://${t}`).hostname}catch{return``}}var Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn=__esmMin(()=>{ut(),ze(),jn(),Nn=lt.UriFlags.HAS_PASSWORD|lt.UriFlags.ENCODED|lt.UriFlags.SCHEME_NORMALIZE,Pn=new WeakMap,Fn=class URLSearchParams{_entries=[];constructor(t){if(t)if(typeof t==`string`)this._entries=parseFormUrlencoded(t.startsWith(`?`)?t.slice(1):t);else if(Array.isArray(t))for(let[n,S]of t)this._entries.push([String(n),String(S)]);else if(t instanceof URLSearchParams)this._entries=t._entries.map(([t,n])=>[t,n]);else for(let n of Object.keys(t))this._entries.push([n,String(t[n])])}get(t){for(let[n,S]of this._entries)if(n===t)return S;return null}getAll(t){return this._entries.filter(([n])=>n===t).map(([,t])=>t)}set(t,n){let S=!1;if(this._entries=this._entries.filter(([n])=>n===t?S?!1:(S=!0,!0):!0),S){for(let S=0;S<this._entries.length;S++)if(this._entries[S][0]===t){this._entries[S][1]=n;break}}else this._entries.push([t,n]);Pn.get(this)?.()}has(t,n){return n===void 0?this._entries.some(([n])=>n===t):this._entries.some(([S,C])=>S===t&&C===n)}delete(t,n){this._entries=n===void 0?this._entries.filter(([n])=>n!==t):this._entries.filter(([S,C])=>!(S===t&&C===n)),Pn.get(this)?.()}append(t,n){this._entries.push([t,n]),Pn.get(this)?.()}sort(){this._entries.sort((t,n)=>t[0]<n[0]?-1:+(t[0]>n[0])),Pn.get(this)?.()}toString(){return this._entries.map(([t,n])=>encodeComponent(t)+`=`+encodeComponent(n)).join(`&`)}forEach(t){for(let[n,S]of this._entries)t(S,n,this)}*entries(){yield*this._entries}*keys(){for(let[t]of this._entries)yield t}*values(){for(let[,t]of this._entries)yield t}[Symbol.iterator](){return this.entries()}get size(){return this._entries.length}},In=new Map([[`ftp`,21],[`file`,null],[`http`,80],[`https`,443],[`ws`,80],[`wss`,443]]),Ln='"#/:;<=>?@[\\]^`{|}',Rn=/[\t\n\r]/g,__name$1(isHexDigit$1,`isHexDigit`),zn=new Set([`\0`,` `,`
11
- `,`\r`,` `,`#`,`/`,`:`,`<`,`>`,`?`,`@`,`[`,`\\`,`]`,`^`,`|`]),Bn=class URL{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(t,n){let S=t instanceof URL?t.href:String(t),C;try{if(n!==void 0){let t=n instanceof URL?n.href:String(n);C=lt.Uri.parse(t,Nn).parse_relative(S,Nn)}else C=lt.Uri.parse(S,Nn)}catch{throw TypeError(`Invalid URL: ${S}`)}if(!C)throw TypeError(`Invalid URL: ${S}`);this.#e=C.get_scheme();let N=isSpecialScheme(this.#e);this.#t=C.get_user()??``,this.#n=C.get_password()??``;let F=C.get_host(),I=F===null?null:bracketIPv6Host(F.toLowerCase());this.#r=I===null?N?``:null:this.#e===`file`&&I===`localhost`?``:I;let H=C.get_port();this.#i=H===-1||H===defaultPort(this.#e)?null:H,this.#a=C.get_path()??``,N&&this.#a===``&&(this.#a=`/`),this.#o=this.#r===null&&!this.#a.startsWith(`/`),this.#r===null&&!this.#o&&this.#a.startsWith(`/.//`)&&(this.#a=this.#a.slice(2)),this.#s=C.get_fragment()??null,this.#l=C.get_query()??null,this.#c=new Fn,this.#c._entries=parseFormUrlencoded(this.#l??``),Pn.set(this.#c,()=>{let t=this.#c.toString();this.#l=t===``?null:t})}get protocol(){return this.#e+`:`}set protocol(t){let n=String(t).replace(Rn,``)+`:`;if(!/^[A-Za-z]/.test(n))return;let S=``;for(let t of n){if(t===`:`)break;if(!isSchemeChar(t))return;S+=t.toLowerCase()}isSpecialScheme(this.#e)===isSpecialScheme(S)&&(S===`file`&&(this.#t!==``||this.#n!==``||this.#i!==null)||this.#e===`file`&&(this.#r===null||this.#r===``)||(this.#e=S,this.#i!==null&&this.#i===defaultPort(S)&&(this.#i=null)))}get hostname(){return this.#r??``}set hostname(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!0);n!==void 0&&(this.#r=n.host)}get port(){return this.#i===null?``:String(this.#i)}set port(t){if(this.#u())return;let n=String(t);if(n===``){this.#i=null;return}let S=digitPrefix(n.replace(Rn,``));if(S===``)return;let C=Number(S);C>65535||(this.#i=C===defaultPort(this.#e)?null:C)}get host(){let t=this.hostname,n=this.port;return n?`${t}:${n}`:t}set host(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!1);n!==void 0&&(this.#r=n.host,n.port!==void 0&&(this.#i=n.port))}get pathname(){return this.#a}set pathname(t){this.#o||(this.#a=parsePathSetterValue(String(t),isSpecialScheme(this.#e),this.#r===null))}get search(){return this.#l?`?`+this.#l:``}set search(t){let n=String(t);if(n===``){this.#l=null,this.#c._entries=[];return}let S=(n.startsWith(`?`)?n.slice(1):n).replace(Rn,``);this.#l=encodeQuery(S,isSpecialScheme(this.#e)),this.#c._entries=parseFormUrlencoded(S)}get hash(){return this.#s?`#`+this.#s:``}set hash(t){let n=String(t);if(n===``){this.#s=null;return}let S=(n.startsWith(`#`)?n.slice(1):n).replace(Rn,``);this.#s=percentEncode(S,'"<>`')}get origin(){return isSpecialScheme(this.#e)&&this.#e!==`file`?`${this.protocol}//${this.host}`:`null`}get username(){return this.#t}set username(t){this.#u()||(this.#t=percentEncode(String(t),Ln))}get password(){return this.#n}set password(t){this.#u()||(this.#n=percentEncode(String(t),Ln))}#u(){return this.#r===null||this.#r===``||this.#e===`file`}get href(){let t=this.#e+`:`;return this.#r===null?!this.#o&&this.#a.startsWith(`//`)&&(t+=`/.`):(t+=`//`,(this.#t!==``||this.#n!==``)&&(t+=this.#t,this.#n!==``&&(t+=`:`+this.#n),t+=`@`),t+=this.#r,this.#i!==null&&(t+=`:`+this.#i)),t+=this.#a,t+=this.#l===null?``:`?${this.#l}`,t+=this.#s===null?``:`#${this.#s}`,t}set href(t){let n=new URL(String(t));this.#e=n.#e,this.#t=n.#t,this.#n=n.#n,this.#r=n.#r,this.#i=n.#i,this.#a=n.#a,this.#o=n.#o,this.#l=n.#l,this.#s=n.#s,this.#c._entries=parseFormUrlencoded(this.#l??``)}get searchParams(){return this.#c}toString(){return this.href}toJSON(){return this.href}static _objectURLPaths=new Map;static _objectURLCounter=0;static createObjectURL(t){let n=t?._tmpPath;if(typeof n==`string`&&n.length>0){let t=`file://${n}`;return URL._objectURLPaths.set(t,n),t}return`file:///dev/null`}static revokeObjectURL(t){let n=URL._objectURLPaths.get(t);n&&(lt.unlink(n),URL._objectURLPaths.delete(t))}},__name$1(parse$3,`parse`),__name$1(format$1,`format`),__name$1(resolve$2,`resolve`),Vn={URL:Bn,URLSearchParams:Fn,parse:parse$3,format:format$1,resolve:resolve$2,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});Hn(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:Bn,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:Fn,enumerable:!1,writable:!0,configurable:!0});var Un=__exportAll$5({PerformanceEntry:()=>qn,PerformanceMark:()=>Yn,PerformanceMeasure:()=>Xn,PerformanceObserver:()=>Kn,PerformanceObserverEntryList:()=>Jn,default:()=>Zn,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>Wn,timerify:()=>timerify});function eventLoopUtilization(t,n){return{idle:0,active:0,utilization:0}}function timerify(t){let wrapped=function(...n){let S=Wn.now(),C=t.apply(this,n);return Wn.now()-S,C};return Object.defineProperty(wrapped,"name",{value:t.name}),wrapped}function monitorEventLoopDelay(t){let n=new Map;return{enable(){},disable(){},reset(){},percentile(t){return 0},get min(){return 0},get max(){return 0},get mean(){return 0},get stddev(){return 0},get percentiles(){return n}}}var Wn,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn=__esmMin(()=>{if(globalThis.performance)Wn=globalThis.performance;else{let t,_now;try{let n=globalThis.imports?.gi?.GLib;if(!n)throw Error(`GJS imports.gi.GLib not available`);t=n.get_monotonic_time(),_now=()=>(n.get_monotonic_time()-t)/1e3}catch{let n=Date.now();t=0,_now=()=>Date.now()-n}let n=[],S=Date.now()-_now();Wn={timeOrigin:S,now:_now,mark(t){let S={name:t,entryType:`mark`,startTime:_now(),duration:0};return n.push(S),S},measure(t,S,C){let N=0,F=_now();if(S){let t=n.find(t=>t.entryType===`mark`&&t.name===S);t&&(N=t.startTime)}if(C){let t=n.find(t=>t.entryType===`mark`&&t.name===C);t&&(F=t.startTime)}let I={name:t,entryType:`measure`,startTime:N,duration:F-N};return n.push(I),I},getEntries(){return[...n]},getEntriesByName(t){return n.filter(n=>n.name===t)},getEntriesByType(t){return n.filter(n=>n.entryType===t)},clearMarks(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`mark`&&(!t||n[S].name===t)&&n.splice(S,1)},clearMeasures(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`measure`&&(!t||n[S].name===t)&&n.splice(S,1)},clearResourceTimings(){},setResourceTimingBufferSize(){},toJSON(){return{timeOrigin:S}}}}PerformanceObserverStub=class{_callback;constructor(t){this._callback=t}observe(t){}disconnect(){}takeRecords(){return[]}},PerformanceEntryStub=class{name=``;entryType=``;startTime=0;duration=0;toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration}}},PerformanceObserverEntryListStub=class{getEntries(){return[]}getEntriesByName(t){return[]}getEntriesByType(t){return[]}},Gn=globalThis,Kn=Gn.PerformanceObserver||PerformanceObserverStub,qn=Gn.PerformanceEntry||PerformanceEntryStub,Jn=Gn.PerformanceObserverEntryList||PerformanceObserverEntryListStub,Yn=Gn.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},Xn=Gn.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Zn={performance:Wn,PerformanceObserver:Kn,PerformanceEntry:qn,PerformanceObserverEntryList:Jn,PerformanceMark:Yn,PerformanceMeasure:Xn,eventLoopUtilization,timerify,monitorEventLoopDelay}});Qn();const $n=globalThis;globalThis.performance===void 0&&($n.performance=Wn),typeof $n.PerformanceObserver!=`function`&&($n.PerformanceObserver=Kn);const er={IndexSizeError:1,HierarchyRequestError:3,WrongDocumentError:4,InvalidCharacterError:5,NoModificationAllowedError:7,NotFoundError:8,NotSupportedError:9,InUseAttributeError:10,InvalidStateError:11,SyntaxError:12,InvalidModificationError:13,NamespaceError:14,InvalidAccessError:15,TypeMismatchError:17,SecurityError:18,NetworkError:19,AbortError:20,URLMismatchError:21,QuotaExceededError:22,TimeoutError:23,InvalidNodeTypeError:24,DataCloneError:25};var _DOMExceptionPolyfill=class extends Error{code;constructor(t,n){super(t),this.name=n||`Error`,this.code=Object.hasOwn(er,this.name)?er[this.name]:0}};const tr=globalThis.DOMException===void 0?_DOMExceptionPolyfill:globalThis.DOMException;_e();const nr=Symbol(`type`),rr=Symbol(`bubbles`),ir=Symbol(`cancelable`),ar=Symbol(`composed`),sr=Symbol(`target`),cr=Symbol(`currentTarget`),lr=Symbol(`eventPhase`),ur=Symbol(`defaultPrevented`),dr=Symbol(`isTrusted`),fr=Symbol(`timeStamp`),pr=Symbol(`stop`),mr=Symbol(`immediateStop`),hr=Symbol(`dispatching`),gr=Symbol(`inPassiveListener`);var Event=class{[nr];[rr];[ir];[ar];[sr]=null;[cr]=null;[lr]=0;[ur]=!1;[dr]=!1;[fr];[pr]=!1;[mr]=!1;[hr]=!1;[gr]=!1;get type(){return this[nr]}get bubbles(){return this[rr]}get cancelable(){return this[ir]}get composed(){return this[ar]}get target(){return this[sr]}get currentTarget(){return this[cr]}get eventPhase(){return this[lr]}get defaultPrevented(){return this[ur]}get timeStamp(){return this[fr]}get cancelBubble(){return this[pr]}set cancelBubble(t){t&&this.stopPropagation()}get returnValue(){return!this[ur]}set returnValue(t){t||this.preventDefault()}get srcElement(){return this[sr]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(t,n){this[nr]=t,this[rr]=n?.bubbles??!1,this[ir]=n?.cancelable??!1,this[ar]=n?.composed??!1,this[fr]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[dr],enumerable:!0,configurable:!1})}composedPath(){return this[cr]?[this[cr]]:[]}preventDefault(){this[ir]&&!this[gr]&&(this[ur]=!0)}stopPropagation(){this[pr]=!0}stopImmediatePropagation(){this[pr]=!0,this[mr]=!0}},EventTarget=class{#e=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=typeof S==`object`?S?.once??!1:!1,F=typeof S==`object`?S?.passive??!1:!1,I=this.#e.get(t);I||(I=[],this.#e.set(t,I));for(let t of I)if(t.listener===n&&t.capture===C)return;let H={listener:n,capture:C,once:N,passive:F,removed:!1};I.push(H),typeof S==`object`&&S?.signal&&S.signal.addEventListener(`abort`,()=>{this.removeEventListener(t,n,{capture:C})},{once:!0})}removeEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=this.#e.get(t);if(!N)return;let F=N.findIndex(t=>t.listener===n&&t.capture===C);F!==-1&&(N[F].removed=!0,N.splice(F,1),N.length===0&&this.#e.delete(t))}dispatchEvent(t){let n=t;if(n[hr])throw new tr(`The event is already being dispatched.`,`InvalidStateError`);n[hr]=!0,n[sr]=this,n[cr]=this,n[lr]=Event.AT_TARGET;try{let S=this.#e.get(t.type);if(S){let C=[...S];for(let S of C)if(!S.removed){if(n[mr]||n[pr])break;S.once&&this.removeEventListener(t.type,S.listener,{capture:S.capture});try{S.passive&&(n[gr]=!0),typeof S.listener==`function`?S.listener.call(this,t):typeof S.listener.handleEvent==`function`&&S.listener.handleEvent.call(S.listener,t)}catch(t){reportListenerException(t)}finally{n[gr]=!1}}}}finally{n[lr]=Event.NONE,n[cr]=null,n[hr]=!1}return!t.defaultPrevented}};function reportListenerException(t){try{let n=globalThis;if(typeof n.reportError==`function`)n.reportError(t);else if(t instanceof Error){let n=`${t.name}: ${t.message}`;ge.error(t.stack?`${n}\n${t.stack}`:n)}else ge.error(String(t))}catch{}}for(let[t,n]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,t,{value:n,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,t,{value:n,writable:!1,enumerable:!0,configurable:!1});const _r=Symbol(`abort`),vr=Symbol(`internal`);var yr=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(t){if(super(),t!==vr)throw TypeError(`Illegal constructor.`)}get aborted(){if(!(this instanceof AbortSignal))throw TypeError(`'get aborted' called on an object that is not a valid instance of AbortSignal.`);return this.#e}get reason(){return this.#t}get[Symbol.toStringTag](){return`AbortSignal`}throwIfAborted(){if(this.#e)throw this.#t}[_r](t){if(this.#e)return;this.#e=!0,this.#t=t??new tr(`The operation was aborted.`,`AbortError`);let n=new Event(`abort`);typeof this.onabort==`function`&&this.onabort.call(this,n),this.dispatchEvent(n)}static abort(t){let n=new AbortSignal(vr);return n[_r](t),n}static timeout(t){let n=new AbortSignal(vr);return setTimeout(()=>{n[_r](new tr(`The operation timed out.`,`TimeoutError`))},t),n}static any(t){let n=new AbortSignal(vr);for(let S of t)if(S.aborted)return n[_r](S.reason),n;let onAbort=()=>{if(!n.aborted){let S=t.find(t=>t.aborted);n[_r](S?.reason)}};for(let n of t)n.addEventListener(`abort`,onAbort,{once:!0});return n}},br=class AbortController{signal;constructor(){this.signal=new yr(vr)}get[Symbol.toStringTag](){return`AbortController`}abort(t){if(!(this instanceof AbortController))throw TypeError(`'abort' called on an object that is not a valid instance of AbortController.`);this.signal[_r](t)}};const Sr=globalThis;globalThis.AbortController===void 0&&(Sr.AbortController=br),globalThis.AbortSignal===void 0&&(Sr.AbortSignal=yr);const Cr=Symbol(`kState`),wr=Symbol(`kType`);function isBrandCheck(t){return n=>typeof n==`object`&&!!n&&n[Cr]!==void 0&&n[wr]===t}function dequeueValue(t){let n=t[Cr].queue.shift();if(n===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:S,size:C}=n;return t[Cr].queueTotalSize=Math.max(0,t[Cr].queueTotalSize-C),S}function resetQueue(t){t[Cr].queue=[],t[Cr].queueTotalSize=0}function peekQueueValue(t){return t[Cr].queue[0].value}function enqueueValueWithSize(t,n,S){if(S=+S,typeof S!=`number`||S<0||Number.isNaN(S)||S===1/0)throw RangeError(`Invalid size: ${S}`);t[Cr].queue.push({value:n,size:S}),t[Cr].queueTotalSize+=S}function extractHighWaterMark(t,n){if(t===void 0)return n;if(t=+t,typeof t!=`number`||Number.isNaN(t)||t<0)throw RangeError(`Invalid highWaterMark: ${t}`);return t}function extractSizeAlgorithm(t){if(t===void 0)return()=>1;if(typeof t!=`function`)throw TypeError(`strategy.size must be a function`);return t}function transferArrayBuffer(t){return typeof ArrayBuffer.prototype.transfer==`function`?t.transfer():t.slice(0)}function isDetachedBuffer(t){if(typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||t.byteLength!==0)return!1;try{return t.slice(0,0),!1}catch{return!0}}function typedArrayConstructorByTag(t){switch(t){case`Int8Array`:return Int8Array;case`Uint8Array`:return Uint8Array;case`Uint8ClampedArray`:return Uint8ClampedArray;case`Int16Array`:return Int16Array;case`Uint16Array`:return Uint16Array;case`Int32Array`:return Int32Array;case`Uint32Array`:return Uint32Array;case`Float32Array`:return Float32Array;case`Float64Array`:return Float64Array;case`BigInt64Array`:return typeof BigInt64Array<`u`?BigInt64Array:void 0;case`BigUint64Array`:return typeof BigUint64Array<`u`?BigUint64Array:void 0;default:return}}function elementSizeByTag(t){switch(t){case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:return 1;case`Int16Array`:case`Uint16Array`:return 2;case`Int32Array`:case`Uint32Array`:case`Float32Array`:return 4;case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:return 8;default:return 1}}function setPromiseHandled(t){t.then(()=>{},()=>{})}function createPromiseCallback(t,n,S){if(typeof n!=`function`)throw TypeError(`${t} must be a function`);return async(...t)=>n.call(S,...t)}async function nonOpFlush(){}function nonOpStart(){}async function nonOpPull(){}async function nonOpCancel(){}async function nonOpWrite(){}const Tr={__proto__:Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),next:void 0,return:void 0};function createAsyncFromSyncIterator(t){let n={[Symbol.iterator]:()=>t.iterator},S=(async function*(){return yield*n})();return{iterator:S,nextMethod:S.next,done:!1}}function getIterator(t,n=`sync`,S){if(S===void 0)if(n===`async`){if(S=t[Symbol.asyncIterator],S==null){let n=t[Symbol.iterator];if(n===void 0)throw TypeError(`Object is not iterable`);return createAsyncFromSyncIterator(getIterator(t,`sync`,n))}}else S=t[Symbol.iterator];if(S===void 0)throw TypeError(`Object is not iterable`);let C=S.call(t);if(typeof C!=`object`||!C)throw TypeError(`The iterator method must return an object`);return{iterator:C,nextMethod:C.next,done:!1}}function iteratorNext(t,n){let S;if(S=n===void 0?t.nextMethod.call(t.iterator):t.nextMethod.call(t.iterator,n),typeof S!=`object`||!S)throw TypeError(`The iterator.next() method must return an object`);return S}const Er=typeof globalThis.AbortController==`function`?globalThis.AbortController:class AbortControllerShim{signal={aborted:!1,reason:void 0,addEventListener(){},removeEventListener(){}};abort(t){this.signal.aborted=!0,this.signal.reason=t}},Dr=Symbol(`kAbort`),Or=Symbol(`kCloseSentinel`),kr=Symbol(`kError`),Ar=Symbol(`kSkipThrow`);var WritableStream=class{[wr]=`WritableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`sink must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);let S=t?.type;if(S!==void 0)throw RangeError(`Invalid type: ${S}`);this[Cr]=createWritableStreamState();let C=extractSizeAlgorithm(n?.size),N=extractHighWaterMark(n?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,t,N,C)}get locked(){if(!jr(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(t){return jr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){return jr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamCloseQueuedOrInFlight(this)?Promise.reject(TypeError(`Failure closing WritableStream`)):writableStreamClose(this):Promise.reject(TypeError(`Invalid this`))}getWriter(){if(!jr(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[wr]=`WritableStreamDefaultWriter`;[Cr];constructor(t){if(!jr(t))throw TypeError(`Expected a WritableStream`);this[Cr]={stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0},ready:{promise:void 0,resolve:void 0,reject:void 0}},setupWritableStreamDefaultWriter(this,t)}get closed(){return Mr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!Mr(this))throw TypeError(`Invalid this`);if(this[Cr].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return Mr(this)?this[Cr].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){if(!Mr(this))return Promise.reject(TypeError(`Invalid this`));let{stream:t}=this[Cr];return t===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamCloseQueuedOrInFlight(t)?Promise.reject(TypeError(`Failure to close WritableStream`)):writableStreamDefaultWriterClose(this)}releaseLock(){if(!Mr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr];t!==void 0&&writableStreamDefaultWriterRelease(this)}write(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterWrite(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`WritableStreamDefaultWriter`}},WritableStreamDefaultController=class{[wr]=`WritableStreamDefaultController`;[Cr];constructor(t){if(t!==Ar)throw TypeError(`Illegal constructor`)}[Dr](t){let n=this[Cr].abortAlgorithm(t);return writableStreamDefaultControllerClearAlgorithms(this),n}[kr](){resetQueue(this)}get signal(){if(!Nr(this))throw TypeError(`Invalid this`);return this[Cr].abortController.signal}error(t){if(!Nr(this))throw TypeError(`Invalid this`);this[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(this,t)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const jr=isBrandCheck(`WritableStream`),Mr=isBrandCheck(`WritableStreamDefaultWriter`),Nr=isBrandCheck(`WritableStreamDefaultController`);function createEmptyPromiseRecord(){return{promise:void 0,resolve:void 0,reject:void 0}}function createWritableStreamState(){return{close:Promise.withResolvers(),closeRequest:createEmptyPromiseRecord(),inFlightWriteRequest:createEmptyPromiseRecord(),inFlightCloseRequest:createEmptyPromiseRecord(),pendingAbortRequest:{abort:createEmptyPromiseRecord(),reason:void 0,wasAlreadyErroring:!1},backpressure:!1,controller:void 0,state:`writable`,storedError:void 0,writeRequests:[],writer:void 0}}function isWritableStreamLocked(t){return t[Cr].writer!==void 0}function setupWritableStreamDefaultWriter(t,n){if(isWritableStreamLocked(n))throw TypeError(`WritableStream is locked`);switch(t[Cr].stream=n,n[Cr].writer=t,n[Cr].state){case`writable`:!writableStreamCloseQueuedOrInFlight(n)&&n[Cr].backpressure?t[Cr].ready=Promise.withResolvers():t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close=Promise.withResolvers();break;case`erroring`:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),setPromiseHandled(t[Cr].close.promise)}}function writableStreamAbort(t,n){let{state:S,controller:C}=t[Cr];if(S===`closed`||S===`errored`)return Promise.resolve();if(C[Cr].abortController.abort(n),t[Cr].pendingAbortRequest.abort.promise!==void 0)return t[Cr].pendingAbortRequest.abort.promise;let N=!1;S===`erroring`&&(N=!0,n=void 0);let F=Promise.withResolvers();return t[Cr].pendingAbortRequest={abort:F,reason:n,wasAlreadyErroring:N},N||writableStreamStartErroring(t,n),F.promise}function writableStreamClose(t){let{state:n,writer:S,backpressure:C,controller:N}=t[Cr];if(n===`closed`||n===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));t[Cr].closeRequest=Promise.withResolvers();let{promise:F}=t[Cr].closeRequest;return S!==void 0&&C&&n===`writable`&&S[Cr].ready.resolve?.(),writableStreamDefaultControllerClose(N),F}function writableStreamUpdateBackpressure(t,n){let{writer:S}=t[Cr];S!==void 0&&t[Cr].backpressure!==n&&(n?S[Cr].ready=Promise.withResolvers():S[Cr].ready.resolve?.()),t[Cr].backpressure=n}function writableStreamStartErroring(t,n){let{controller:S,writer:C}=t[Cr];t[Cr].state=`erroring`,t[Cr].storedError=n,C!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(C,n),!writableStreamHasOperationMarkedInFlight(t)&&S[Cr].started&&writableStreamFinishErroring(t)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(t){t[Cr].closeRequest.promise!==void 0&&(t[Cr].closeRequest.reject?.(t[Cr].storedError),t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(t[Cr].close.promise),t[Cr].close.reject?.(t[Cr].storedError);let{writer:n}=t[Cr];n!==void 0&&(setPromiseHandled(n[Cr].close.promise),n[Cr].close.reject?.(t[Cr].storedError))}function writableStreamMarkFirstWriteRequestInFlight(t){let n=t[Cr].writeRequests.shift();t[Cr].inFlightWriteRequest=n}function writableStreamMarkCloseRequestInFlight(t){t[Cr].inFlightCloseRequest=t[Cr].closeRequest,t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(t){return t[Cr].inFlightWriteRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(t,n){t[Cr].inFlightWriteRequest.reject?.(n),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightWrite(t){t[Cr].inFlightWriteRequest.resolve?.(),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(t,n){t[Cr].inFlightCloseRequest.reject?.(n),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.reject?.(n),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightClose(t){t[Cr].inFlightCloseRequest.resolve?.(),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].state===`erroring`&&(t[Cr].storedError=void 0,t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.resolve?.(),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),t[Cr].state=`closed`,t[Cr].writer!==void 0&&t[Cr].writer[Cr].close.resolve?.(),t[Cr].close.resolve?.()}function writableStreamFinishErroring(t){t[Cr].state=`errored`,t[Cr].controller[kr]();let n=t[Cr].storedError;for(let S of t[Cr].writeRequests)S.reject?.(n);if(t[Cr].writeRequests=[],t[Cr].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}let S=t[Cr].pendingAbortRequest;if(t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1},S.wasAlreadyErroring){S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}t[Cr].controller[Dr](S.reason).then(()=>{S.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)},n=>{S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)})}function writableStreamDealWithRejection(t,n){if(t[Cr].state===`writable`){writableStreamStartErroring(t,n);return}writableStreamFinishErroring(t)}function writableStreamCloseQueuedOrInFlight(t){return t[Cr].closeRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(t){let{promise:n,resolve:S,reject:C}=Promise.withResolvers();return t[Cr].writeRequests.push({promise:n,resolve:S,reject:C}),n}function writableStreamDefaultWriterWrite(t,n){let{stream:S}=t[Cr],{controller:C}=S[Cr],N=writableStreamDefaultControllerGetChunkSize(C,n);if(S!==t[Cr].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:F}=S[Cr];if(F===`errored`)return Promise.reject(S[Cr].storedError);if(writableStreamCloseQueuedOrInFlight(S)||F===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(F===`erroring`)return Promise.reject(S[Cr].storedError);let I=writableStreamAddWriteRequest(S);return writableStreamDefaultControllerWrite(C,n,N),I}function writableStreamDefaultWriterRelease(t){let{stream:n}=t[Cr],S=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(t,S),writableStreamDefaultWriterEnsureClosedPromiseRejected(t,S),n[Cr].writer=void 0,t[Cr].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(t){let{stream:n}=t[Cr];switch(n[Cr].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(n[Cr].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(t,n){t[Cr].ready.reject?(t[Cr].ready.reject(n),t[Cr].ready.resolve=void 0,t[Cr].ready.reject=void 0):t[Cr].ready={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(t,n){t[Cr].close.reject?(t[Cr].close.reject(n),t[Cr].close.resolve=void 0,t[Cr].close.reject=void 0):t[Cr].close={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(t){let{stream:n}=t[Cr],{state:S}=n[Cr];return writableStreamCloseQueuedOrInFlight(n)||S===`closed`?Promise.resolve():S===`errored`?Promise.reject(n[Cr].storedError):writableStreamDefaultWriterClose(t)}function writableStreamDefaultWriterClose(t){return writableStreamClose(t[Cr].stream)}function writableStreamDefaultWriterAbort(t,n){return writableStreamAbort(t[Cr].stream,n)}function writableStreamDefaultControllerWrite(t,n,S){try{enqueueValueWithSize(t,n,S)}catch(n){writableStreamDefaultControllerErrorIfNeeded(t,n);return}let{stream:C}=t[Cr];!writableStreamCloseQueuedOrInFlight(C)&&C[Cr].state===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerProcessWrite(t,n){let{stream:S,writeAlgorithm:C}=t[Cr];writableStreamMarkFirstWriteRequestInFlight(S),C(n,t).then(()=>{writableStreamFinishInFlightWrite(S);let{state:n}=S[Cr];dequeueValue(t),!writableStreamCloseQueuedOrInFlight(S)&&n===`writable`&&writableStreamUpdateBackpressure(S,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)},n=>{S[Cr].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(t),writableStreamFinishInFlightWriteWithError(S,n)})}function writableStreamDefaultControllerProcessClose(t){let{closeAlgorithm:n,stream:S}=t[Cr];writableStreamMarkCloseRequestInFlight(S),dequeueValue(t);let C=n();writableStreamDefaultControllerClearAlgorithms(t),C.then(()=>writableStreamFinishInFlightClose(S),t=>writableStreamFinishInFlightCloseWithError(S,t))}function writableStreamDefaultControllerGetDesiredSize(t){return t[Cr].highWaterMark-t[Cr].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(t,n){let{sizeAlgorithm:S}=t[Cr];if(S===void 0)return 1;try{return S(n)}catch(n){return writableStreamDefaultControllerErrorIfNeeded(t,n),1}}function writableStreamDefaultControllerErrorIfNeeded(t,n){t[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(t,n)}function writableStreamDefaultControllerError(t,n){writableStreamDefaultControllerClearAlgorithms(t),writableStreamStartErroring(t[Cr].stream,n)}function writableStreamDefaultControllerClose(t){enqueueValueWithSize(t,Or,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerClearAlgorithms(t){t[Cr].writeAlgorithm=void 0,t[Cr].closeAlgorithm=void 0,t[Cr].abortAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(t){return writableStreamDefaultControllerGetDesiredSize(t)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(t){let{queue:n,started:S,stream:C}=t[Cr];if(!S||C[Cr].inFlightWriteRequest.promise!==void 0)return;if(C[Cr].state===`erroring`){writableStreamFinishErroring(C);return}if(!n.length)return;let N=peekQueueValue(t);N===Or?writableStreamDefaultControllerProcessClose(t):writableStreamDefaultControllerProcessWrite(t,N)}function setupWritableStreamDefaultControllerFromSink(t,n,S,C){let N=new WritableStreamDefaultController(Ar),F=n?.start,I=n?.write,H=n?.close,W=n?.abort;setupWritableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`sink.write`,I,n):nonOpWrite,H?createPromiseCallback(`sink.close`,H,n):nonOpCancel,W?createPromiseCallback(`sink.abort`,W,n):nonOpCancel,S,C)}function setupWritableStreamDefaultController(t,n,S,C,N,F,I,H){n[Cr]={abortAlgorithm:F,closeAlgorithm:N,highWaterMark:I,queue:[],queueTotalSize:0,abortController:new Er,sizeAlgorithm:H,started:!1,stream:t,writeAlgorithm:C},t[Cr].controller=n,writableStreamUpdateBackpressure(t,writableStreamDefaultControllerGetBackpressure(n));let W=S();new Promise(t=>t(W)).then(()=>{n[Cr].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{n[Cr].started=!0,writableStreamDealWithRejection(t,S)})}function createWritableStream(t,n,S,C,N=1,F=()=>1){let I=Object.create(WritableStream.prototype);return I[wr]=`WritableStream`,I[Cr]=createWritableStreamState(),setupWritableStreamDefaultController(I,new WritableStreamDefaultController(Ar),t,n,S,C,N,F),I}ze();const Pr=Symbol(`kCancel`),Fr=Symbol(`kClose`),Ir=Symbol(`kChunk`),Lr=Symbol(`kError`),Rr=Symbol(`kPull`),zr=Symbol(`kRelease`),Br=Symbol(`kSkipThrow`);let Vr,Hr;function lazyReadableReleasedError(){return Vr||(Vr=TypeError(`Reader released`),Vr)}function lazyReadableReleasingError(){return Hr||(Hr=TypeError(`Releasing reader`),Hr)}function createAbortError$1(){if(typeof globalThis.DOMException==`function`)return new DOMException(`The operation was aborted`,`AbortError`);let t=Error(`The operation was aborted`);return t.name=`AbortError`,t}__name$1(createAbortError$1,`createAbortError`);function createReadableStreamState(){return{disturbed:!1,reader:void 0,state:`readable`,storedError:void 0,controller:void 0,closedPromise:Promise.withResolvers()}}var ReadableStream$1=class{static{__name$1(this,`ReadableStream`)}[wr]=`ReadableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`source must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);this[Cr]=createReadableStreamState();let S=n?.size,C=n?.highWaterMark,N=t?.type;if(N!==void 0){if(`${N}`==`bytes`){if(S!==void 0)throw RangeError(`strategy.size must not be set for a byte stream`);setupReadableByteStreamControllerFromSource(this,t,extractHighWaterMark(C,0));return}throw RangeError(`Invalid type: ${N}`)}setupReadableStreamDefaultControllerFromSource(this,t,extractHighWaterMark(C,1),extractSizeAlgorithm(S))}get locked(){if(!Ur(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(t){return readableStreamFromIterable(t)}cancel(t=void 0){return Ur(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,t):Promise.reject(TypeError(`Invalid this`))}getReader(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=t?.mode;if(n===void 0)return new ReadableStreamDefaultReader(this);if(`${n}`==`byob`)return new ReadableStreamBYOBReader(this);throw RangeError(`Invalid mode: ${n}`)}pipeThrough(t,n={}){if(!Ur(this))throw TypeError(`Invalid this`);let S=t?.readable;if(!Ur(S))throw TypeError(`transform.readable must be a ReadableStream`);let C=t?.writable;if(!jr(C))throw TypeError(`transform.writable must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let N=n?.preventAbort,F=n?.preventCancel,I=n?.preventClose,H=n?.signal;if(H!==void 0&&!(H instanceof Object&&`aborted`in H))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(C))throw TypeError(`The WritableStream is locked`);return setPromiseHandled(readableStreamPipeTo(this,C,!!I,!!N,!!F,H)),S}pipeTo(t,n={}){try{if(!Ur(this))throw TypeError(`Invalid this`);if(!jr(t))throw TypeError(`destination must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=n?.preventAbort,C=n?.preventCancel,N=n?.preventClose,F=n?.signal;if(F!==void 0&&!(F instanceof Object&&`aborted`in F))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(t))throw TypeError(`The WritableStream is locked`);return readableStreamPipeTo(this,t,!!N,!!S,!!C,F)}catch(t){return Promise.reject(t)}}tee(){if(!Ur(this))throw TypeError(`Invalid this`);let t=this[Cr].controller;return Kr(t)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=!!t?.preventCancel,S=new ReadableStreamDefaultReader(this),C={done:!1,current:void 0},N=!1;function nextSteps(){if(C.done)return Promise.resolve({done:!0,value:void 0});if(S[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not bound to a ReadableStream`));let{promise:t,resolve:n,reject:N}=Promise.withResolvers();return readableStreamDefaultReaderRead(S,{[Ir](t){C.current=void 0,n({value:t,done:!1})},[Fr](){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),n({done:!0,value:void 0})},[Lr](t){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),N(t)}}),t}async function returnSteps(t){if(C.done)return{done:!0,value:t};if(C.done=!0,S[Cr].stream===void 0)throw TypeError(`The reader is not bound to a ReadableStream`);if(!n){let n=readableStreamReaderGenericCancel(S,t);return readableStreamReaderGenericRelease(S),await n,{done:!0,value:t}}return readableStreamReaderGenericRelease(S),{done:!0,value:t}}return Object.setPrototypeOf({next(){return N||=(C.current=Promise.resolve(),!0),C.current=C.current===void 0?nextSteps():C.current.then(nextSteps,nextSteps),C.current},return(t){return N=!0,C.current=C.current===void 0?returnSteps(t):C.current.then(()=>returnSteps(t),()=>returnSteps(t)),C.current},[Symbol.asyncIterator](){return this}},Tr)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](){this[Cr].resolve?.({value:void 0,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamDefaultReader=class{[wr]=`ReadableStreamDefaultReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,t)}read(){if(!Gr(this))return Promise.reject(TypeError(`Invalid this`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let t=this[Cr].stream,n=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(n)&&n[Cr].queue.length>0){t[Cr].disturbed=!0;let S=dequeueValue(n);return n[Cr].closeRequested&&!n[Cr].queue.length?(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(t)):readableStreamDefaultControllerCallPullIfNeeded(n),Promise.resolve({value:S,done:!1})}let S=new DefaultReadRequest;return readableStreamDefaultReaderRead(this,S),S.promise}releaseLock(){if(!Gr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return Gr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return Gr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`The reader is not attached to a stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamDefaultReader`}},ReadableStreamDefaultController=class{[wr]=`ReadableStreamDefaultController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get desiredSize(){return readableStreamDefaultControllerGetDesiredSize(this)}close(){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerClose(this)}enqueue(t=void 0){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerEnqueue(this,t)}error(t=void 0){readableStreamDefaultControllerError(this,t)}[Pr](t){return readableStreamDefaultControllerCancelSteps(this,t)}[Rr](t){readableStreamDefaultControllerPullSteps(this,t)}[zr](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const Ur=isBrandCheck(`ReadableStream`),Wr=isBrandCheck(`ReadableStreamDefaultController`),Gr=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(t){return t[Cr].reader!==void 0}function readableStreamCancel(t,n){switch(t[Cr].disturbed=!0,t[Cr].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(t[Cr].storedError)}readableStreamClose(t);let S=t[Cr].reader;if(S!==void 0&&readableStreamHasBYOBReader(t)){let t=S[Cr].readIntoRequests;S[Cr].readIntoRequests=[];for(let n=0;n<t.length;n++)t[n][Fr](void 0)}return t[Cr].controller[Pr](n).then(()=>{})}function readableStreamClose(t){t[Cr].state=`closed`,t[Cr].closedPromise.resolve();let{reader:n}=t[Cr];if(n!==void 0&&(n[Cr].close.resolve?.(),readableStreamHasDefaultReader(t))){for(let t=0;t<n[Cr].readRequests.length;t++)n[Cr].readRequests[t][Fr]();n[Cr].readRequests=[]}}function readableStreamError(t,n){t[Cr].state=`errored`,t[Cr].storedError=n,setPromiseHandled(t[Cr].closedPromise.promise),t[Cr].closedPromise.reject(n);let{reader:S}=t[Cr];if(S!==void 0){if(setPromiseHandled(S[Cr].close.promise),S[Cr].close.reject?.(n),readableStreamHasDefaultReader(t)){for(let t=0;t<S[Cr].readRequests.length;t++)S[Cr].readRequests[t][Lr](n);S[Cr].readRequests=[]}else if(readableStreamHasBYOBReader(t)){for(let t=0;t<S[Cr].readIntoRequests.length;t++)S[Cr].readIntoRequests[t][Lr](n);S[Cr].readIntoRequests=[]}}}function readableStreamHasDefaultReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(t){return t[Cr].reader[Cr].readRequests.length}function readableStreamFulfillReadRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readRequests.shift();S?N[Fr]():N[Ir](n)}function readableStreamAddReadRequest(t,n){t[Cr].reader[Cr].readRequests.push(n)}function readableStreamReaderGenericCancel(t,n){let{stream:S}=t[Cr];return readableStreamCancel(S,n)}function readableStreamReaderGenericInitialize(t,n){switch(t[Cr].stream=n,n[Cr].reader=t,n[Cr].state){case`readable`:t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise);break}}function readableStreamReaderGenericRelease(t){let{stream:n}=t[Cr],S=lazyReadableReleasedError();n[Cr].state===`readable`?t[Cr].close.reject?.(S):t[Cr].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise),n[Cr].controller[zr](),n[Cr].reader=void 0,t[Cr].stream=void 0}function readableStreamDefaultReaderRelease(t){readableStreamReaderGenericRelease(t),readableStreamDefaultReaderErrorReadRequests(t,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(t,n){for(let S=0;S<t[Cr].readRequests.length;++S)t[Cr].readRequests[S][Lr](n);t[Cr].readRequests=[]}function readableStreamDefaultReaderRead(t,n){let{stream:S}=t[Cr];switch(S[Cr].disturbed=!0,S[Cr].state){case`closed`:n[Fr]();break;case`errored`:n[Lr](S[Cr].storedError);break;case`readable`:S[Cr].controller[Rr](n);break}}function setupReadableStreamDefaultReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(t,n),t[Cr].readRequests=[]}function readableStreamDefaultControllerClose(t){readableStreamDefaultControllerCanCloseOrEnqueue(t)&&(t[Cr].closeRequested=!0,t[Cr].queue.length||(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)))}function readableStreamDefaultControllerEnqueue(t,n){if(!readableStreamDefaultControllerCanCloseOrEnqueue(t))return;let{stream:S}=t[Cr];if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))readableStreamFulfillReadRequest(S,n,!1);else try{enqueueValueWithSize(t,n,t[Cr].sizeAlgorithm(n))}catch(n){throw readableStreamDefaultControllerError(t,n),n}readableStreamDefaultControllerCallPullIfNeeded(t)}function readableStreamDefaultControllerCanCloseOrEnqueue(t){let{stream:n}=t[Cr];return!t[Cr].closeRequested&&n[Cr].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(t){let{stream:n,highWaterMark:S,queueTotalSize:C}=t[Cr];switch(n[Cr].state){case`errored`:return null;case`closed`:return 0;default:return S-C}}function readableStreamDefaultControllerHasBackpressure(t){return!readableStreamDefaultControllerShouldCallPull(t)}function readableStreamDefaultControllerShouldCallPull(t){let{stream:n}=t[Cr];if(!readableStreamDefaultControllerCanCloseOrEnqueue(t)||!t[Cr].started)return!1;if(isReadableStreamLocked(n)&&readableStreamGetNumReadRequests(n))return!0;let S=readableStreamDefaultControllerGetDesiredSize(t);return S!==null&&S>0}function readableStreamDefaultControllerCallPullIfNeeded(t){if(readableStreamDefaultControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(t))},n=>readableStreamDefaultControllerError(t,n))}}function readableStreamDefaultControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(resetQueue(t),readableStreamDefaultControllerClearAlgorithms(t),readableStreamError(S,n))}function readableStreamDefaultControllerCancelSteps(t,n){resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(t),S}function readableStreamDefaultControllerPullSteps(t,n){let{stream:S,queue:C}=t[Cr];if(C.length){let N=dequeueValue(t);t[Cr].closeRequested&&!C.length?(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(S)):readableStreamDefaultControllerCallPullIfNeeded(t),n[Ir](N);return}readableStreamAddReadRequest(S,n),readableStreamDefaultControllerCallPullIfNeeded(t)}function setupReadableStreamDefaultController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:I,stream:t},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableStreamDefaultControllerCallPullIfNeeded(n)},t=>readableStreamDefaultControllerError(n,t))}function setupReadableStreamDefaultControllerFromSource(t,n,S,C){let N=new ReadableStreamDefaultController(Br),F=n?.start,I=n?.pull,H=n?.cancel;setupReadableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`source.pull`,I,n):nonOpPull,H?createPromiseCallback(`source.cancel`,H,n):nonOpCancel,S,C)}function createReadableStream(t,n,S,C=1,N=()=>1){let F=Object.create(ReadableStream$1.prototype);return F[wr]=`ReadableStream`,F[Cr]=createReadableStreamState(),setupReadableStreamDefaultController(F,new ReadableStreamDefaultController(Br),t,n,S,C,N),F}function readableStreamFromIterable(t){let n,S=getIterator(t,`async`),C=nonOpStart;async function pullAlgorithm(){let t=iteratorNext(S);return Promise.resolve(t).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.next() method must fulfill with an object`);t.done?readableStreamDefaultControllerClose(n[Cr].controller):readableStreamDefaultControllerEnqueue(n[Cr].controller,t.value)})}async function cancelAlgorithm(t){let n=S.iterator,C=n.return;if(C===void 0)return Promise.resolve();let N=C.call(n,t);return Promise.resolve(N).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.return() method must fulfill with an object`)})}return n=createReadableStream(C,pullAlgorithm,cancelAlgorithm,0),n}function readableStreamPipeTo(t,n,S,C,N,F){let I,H;try{I=new ReadableStreamDefaultReader(t),H=new WritableStreamDefaultWriter(n)}catch(t){return Promise.reject(t)}t[Cr].disturbed=!0;let W=!1,{promise:q,resolve:Y,reject:X}=Promise.withResolvers(),Z={currentWrite:Promise.resolve()},te;function finalize(t,n){writableStreamDefaultWriterRelease(H),readableStreamReaderGenericRelease(I),F!==void 0&&te&&(F.removeEventListener(`abort`,te),te=void 0),t?X(n):Y()}async function waitForCurrentWrite(){let t=Z.currentWrite;await t,t!==Z.currentWrite&&await waitForCurrentWrite()}function shutdownWithAnAction(t,S,C){if(W)return;if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(complete,t=>finalize(!0,t));return}complete();function complete(){t().then(()=>finalize(!!S,C),t=>finalize(!0,t))}}function shutdown(t,S){if(!W){if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(()=>finalize(!!t,S),t=>finalize(!0,t));return}finalize(!!t,S)}}function abortAlgorithm(){let S;S=F.reason&&F.reason.name===`AbortError`?createAbortError$1():F.reason;let I=[];C||I.push(()=>n[Cr].state===`writable`?writableStreamAbort(n,S):Promise.resolve()),N||I.push(()=>t[Cr].state===`readable`?readableStreamCancel(t,S):Promise.resolve()),shutdownWithAnAction(()=>Promise.all(I.map(t=>t())).then(()=>void 0),!0,S)}function watchErrored(t,n,S){t[Cr].state===`errored`?S(t[Cr].storedError):n.then(void 0,S)}function watchClosed(t,n,S){t[Cr].state===`closed`?S():n.then(S,()=>{})}class PipeToReadRequest{[Ir](t){ve(()=>{Z.currentWrite=writableStreamDefaultWriterWrite(H,t),setPromiseHandled(Z.currentWrite),ne.resolve(!1)})}[Fr](){ne.resolve(!0)}[Lr](t){ne.reject(t)}}let ne={resolve:null,reject:null};async function step(){if(W||n[Cr].backpressure&&(await H[Cr].ready.promise,W))return!0;let S=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(S)&&S[Cr].queue.length>0){for(;S[Cr].queue.length>0;){if(W)return!0;let C=dequeueValue(S);if(S[Cr].closeRequested&&!S[Cr].queue.length&&(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(t)),Z.currentWrite=writableStreamDefaultWriterWrite(H,C),setPromiseHandled(Z.currentWrite),n[Cr].backpressure||n[Cr].state!==`writable`||writableStreamCloseQueuedOrInFlight(n))break}return readableStreamDefaultControllerCallPullIfNeeded(S),t[Cr].state===`closed`}let{promise:C,resolve:N,reject:F}=Promise.withResolvers();return ne={resolve:N,reject:F},readableStreamDefaultReaderRead(I,new PipeToReadRequest),C}async function run(){for(;!await step(););}if(F!==void 0){if(F.aborted)return abortAlgorithm(),q;te=abortAlgorithm,F.addEventListener(`abort`,te,{once:!0})}if(setPromiseHandled(run()),watchErrored(t,I[Cr].close.promise,t=>{if(!C)return shutdownWithAnAction(()=>writableStreamAbort(n,t),!0,t);shutdown(!0,t)}),watchErrored(n,H[Cr].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n);shutdown(!0,n)}),watchClosed(t,I[Cr].close.promise,()=>{if(!S)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(H));shutdown()}),writableStreamCloseQueuedOrInFlight(n)||n[Cr].state===`closed`){let n=TypeError(`Destination WritableStream is closed`);N?shutdown(!0,n):shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n)}return q}function readableStreamDefaultTee(t,n){let S=new ReadableStreamDefaultReader(t),C=!1,N=!1,F=!1,I,H,W,q,Y=Promise.withResolvers();async function pullAlgorithm(){C||(C=!0,readableStreamDefaultReaderRead(S,{[Ir](t){ve(()=>{C=!1;let S=t,I=t;if(!F&&n)try{I=structuredClone(I)}catch{}N||readableStreamDefaultControllerEnqueue(W[Cr].controller,S),F||readableStreamDefaultControllerEnqueue(q[Cr].controller,I)})},[Fr](){ve(()=>{C=!1,N||readableStreamDefaultControllerClose(W[Cr].controller),F||readableStreamDefaultControllerClose(q[Cr].controller),(!N||!F)&&Y.resolve(void 0)})},[Lr](){C=!1}}))}function cancel1Algorithm(n){if(N=!0,I=n,F){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}function cancel2Algorithm(n){if(F=!0,H=n,N){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}return W=createReadableStream(nonOpStart,pullAlgorithm,cancel1Algorithm),q=createReadableStream(nonOpStart,pullAlgorithm,cancel2Algorithm),S[Cr].close.promise.then(void 0,t=>{readableStreamDefaultControllerError(W[Cr].controller,t),readableStreamDefaultControllerError(q[Cr].controller,t),(!N||!F)&&Y.resolve(void 0)}),[W,q]}var BYOBReadIntoRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](t){this[Cr].resolve?.({value:t,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamBYOBReader=class{[wr]=`ReadableStreamBYOBReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,t)}read(t,n={}){if(!qr(this))return Promise.reject(TypeError(`Invalid this`));if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))return Promise.reject(TypeError(`view must be an ArrayBufferView`));let S=t.buffer,C=t.byteLength;if(C===0)return Promise.reject(TypeError(`view must have non-zero byteLength`));if(S.byteLength===0)return isDetachedBuffer(S)?Promise.reject(TypeError(`view's buffer has been detached`)):Promise.reject(TypeError(`view's buffer must have non-zero byteLength`));let N=n?.min??1;if(typeof N!=`number`||N<1||!Number.isInteger(N)||Number.isNaN(N))return Promise.reject(TypeError(`options.min must be a positive integer`));let F=t[Symbol.toStringTag];if(F!==void 0&&F!==`DataView`){if(N>t.length)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`))}else if(N>C)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`Reader has no associated stream`));let I=new BYOBReadIntoRequest;return readableStreamBYOBReaderRead(this,t,N,I),I.promise}releaseLock(){if(!qr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return qr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return qr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Reader has no associated stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamBYOBReader`}},ReadableStreamBYOBRequest=class{[wr]=`ReadableStreamBYOBRequest`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get view(){if(!Jr(this))throw TypeError(`Invalid this`);return this[Cr].view}respond(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(t=+t,!Number.isInteger(t)||t<0||!Number.isFinite(t))throw RangeError(`bytesWritten must be a non-negative integer`);let n=this[Cr].view;if(isDetachedBuffer(n.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Cr].controller,t)}respondWithNewView(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`view must be an ArrayBufferView`);if(isDetachedBuffer(t.buffer))throw TypeError(`The given view's buffer has been detached`);readableByteStreamControllerRespondWithNewView(this[Cr].controller,t)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[wr]=`ReadableByteStreamController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!Kr(this))throw TypeError(`Invalid this`);if(this[Cr].closeRequested)throw TypeError(`Close already requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(t){if(!Kr(this))throw TypeError(`Invalid this`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`chunk must be an ArrayBufferView`);if(t.byteLength===0)throw TypeError(`chunk length must be non-zero`);if(t.buffer.byteLength===0)throw TypeError(`chunk's buffer length must be non-zero`);if(this[Cr].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,t)}error(t=void 0){if(!Kr(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,t)}[Pr](t){return readableByteStreamControllerCancelSteps(this,t)}[Rr](t){readableByteStreamControllerPullSteps(this,t)}[zr](){if(this[Cr].pendingPullIntos.length>0){let t=this[Cr].pendingPullIntos[0];t.readerType=`none`,this[Cr].pendingPullIntos=[t]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const Kr=isBrandCheck(`ReadableByteStreamController`),qr=isBrandCheck(`ReadableStreamBYOBReader`),Jr=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(t){return t[Cr].reader[Cr].readIntoRequests.length}function readableStreamAddReadIntoRequest(t,n){t[Cr].reader[Cr].readIntoRequests.push(n)}function readableStreamFulfillReadIntoRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readIntoRequests.shift();S?N[Fr](n):N[Ir](n)}function setupReadableStreamBYOBReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);if(!Kr(n[Cr].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(t,n),t[Cr].readIntoRequests=[]}function readableStreamBYOBReaderRead(t,n,S,C){let{stream:N}=t[Cr];N[Cr].disturbed=!0,N[Cr].state===`errored`?C[Lr](N[Cr].storedError):readableByteStreamControllerPullInto(N[Cr].controller,n,S,C)}function readableStreamBYOBReaderRelease(t){readableStreamReaderGenericRelease(t);let n=TypeError(`Reader was released`);for(let S=0;S<t[Cr].readIntoRequests.length;S++)t[Cr].readIntoRequests[S][Lr](n);t[Cr].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(t){readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(t){let n=t[Cr].byobRequest;n!=null&&(n[Cr].controller=void 0,n[Cr].view=null,t[Cr].byobRequest=null)}function readableByteStreamControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t),readableByteStreamControllerClearAlgorithms(t),readableStreamError(S,n))}function readableByteStreamControllerGetDesiredSize(t){let n=t[Cr].stream[Cr].state;return n===`errored`?null:n===`closed`?0:t[Cr].highWaterMark-t[Cr].queueTotalSize}function readableByteStreamControllerShouldCallPull(t){let{stream:n}=t[Cr];if(n[Cr].state!==`readable`||t[Cr].closeRequested||!t[Cr].started)return!1;if(readableStreamHasDefaultReader(n)&&readableStreamGetNumReadRequests(n)>0||readableStreamHasBYOBReader(n)&&readableStreamGetNumReadIntoRequests(n)>0)return!0;let S=readableByteStreamControllerGetDesiredSize(t);return S!==null&&S>0}function readableByteStreamControllerCallPullIfNeeded(t){if(readableByteStreamControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(t))},n=>readableByteStreamControllerError(t,n))}}function readableByteStreamControllerHandleQueueDrain(t){t[Cr].queueTotalSize===0&&t[Cr].closeRequested?(readableByteStreamControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)):readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerEnqueueChunkToQueue(t,n,S,C){t[Cr].queue.push({buffer:n,byteOffset:S,byteLength:C}),t[Cr].queueTotalSize+=C}function readableByteStreamControllerEnqueueClonedChunkToQueue(t,n,S,C){let N;try{N=n.slice(S,S+C)}catch(n){readableByteStreamControllerError(t,n);return}readableByteStreamControllerEnqueueChunkToQueue(t,N,0,C)}function readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n){n.bytesFilled>0&&readableByteStreamControllerEnqueueClonedChunkToQueue(t,n.buffer,n.byteOffset,n.bytesFilled),readableByteStreamControllerShiftPendingPullInto(t)}function readableByteStreamControllerShiftPendingPullInto(t){return t[Cr].pendingPullIntos.shift()}function readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S){S.bytesFilled+=n}function readableByteStreamControllerConvertPullIntoDescriptor(t){let n=t.bytesFilled,S=t.elementSize,C=transferArrayBuffer(t.buffer);return t.buffer=C,new t.viewConstructor(C,t.byteOffset,n/S)}function readableByteStreamControllerCommitPullIntoDescriptor(t,n){let S=!1;t[Cr].state===`closed`&&(S=!0);let C=readableByteStreamControllerConvertPullIntoDescriptor(n);n.readerType==="default"?readableStreamFulfillReadRequest(t,C,S):readableStreamFulfillReadIntoRequest(t,C,S)}function readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n){let S=Math.min(t[Cr].queueTotalSize,n.byteLength-n.bytesFilled),C=n.bytesFilled+S,N=S,F=!1,I=C-C%n.elementSize;I>=n.minimumFill&&(N=I-n.bytesFilled,F=!0);let H=t[Cr].queue;for(;N>0;){let S=H[0],C=Math.min(N,S.byteLength),F=n.byteOffset+n.bytesFilled,I=new Uint8Array(n.buffer,F,C),W=new Uint8Array(S.buffer,S.byteOffset,C);I.set(W),S.byteLength===C?H.shift():(S.byteOffset+=C,S.byteLength-=C),t[Cr].queueTotalSize-=C,readableByteStreamControllerFillHeadPullIntoDescriptor(t,C,n),N-=C}return F}function readableByteStreamControllerFillReadRequestFromQueue(t,n){let S=t[Cr].queue.shift();t[Cr].queueTotalSize-=S.byteLength,readableByteStreamControllerHandleQueueDrain(t);let C=new Uint8Array(S.buffer,S.byteOffset,S.byteLength);n[Ir](C)}function readableByteStreamControllerProcessReadRequestsUsingQueue(t){let n=t[Cr].stream[Cr].reader;for(;n[Cr].readRequests.length!==0;){if(t[Cr].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(t,n[Cr].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t){for(;t[Cr].pendingPullIntos.length!==0;){if(t[Cr].queueTotalSize===0)return;let n=t[Cr].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n)&&(readableByteStreamControllerShiftPendingPullInto(t),readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,n))}}function readableByteStreamControllerGetBYOBRequest(t){if(t[Cr].byobRequest===null&&t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0],S=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),C=new ReadableStreamBYOBRequest(Br);C[Cr]={controller:t,view:S},t[Cr].byobRequest=C}return t[Cr].byobRequest}function readableByteStreamControllerEnqueue(t,n){let{stream:S}=t[Cr];if(t[Cr].closeRequested||S[Cr].state!==`readable`)return;let C=n.buffer,N=n.byteLength,F=n.byteOffset;if(isDetachedBuffer(C))throw TypeError(`chunk's buffer is detached`);let I=transferArrayBuffer(C);if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(isDetachedBuffer(n.buffer))throw TypeError(`BYOB request's buffer has been detached`);readableByteStreamControllerInvalidateBYOBRequest(t),n.buffer=transferArrayBuffer(n.buffer),n.readerType===`none`&&readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n)}readableStreamHasDefaultReader(S)?(readableByteStreamControllerProcessReadRequestsUsingQueue(t),readableStreamGetNumReadRequests(S)===0?readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N):(t[Cr].pendingPullIntos.length!==0&&readableByteStreamControllerShiftPendingPullInto(t),readableStreamFulfillReadRequest(S,new Uint8Array(I,F,N),!1))):readableStreamHasBYOBReader(S)?(readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)):readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerClose(t){let{stream:n}=t[Cr];if(!(t[Cr].closeRequested||n[Cr].state!==`readable`)){if(t[Cr].queueTotalSize>0){t[Cr].closeRequested=!0;return}if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(n.bytesFilled%n.elementSize!==0){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);throw readableByteStreamControllerError(t,n),n}}readableByteStreamControllerClearAlgorithms(t),readableStreamClose(n)}}function readableByteStreamControllerPullInto(t,n,S,C){let N=t[Cr].stream,F=n[Symbol.toStringTag],I,H;if(F===void 0||F===`DataView`)I=DataView,H=1;else{let t=typedArrayConstructorByTag(F);if(!t){C[Lr](TypeError(`Unsupported typed array: ${F}`));return}I=t,H=elementSizeByTag(F)}let W=n.buffer,q=n.byteLength,Y=n.byteOffset,X=S*H,Z;try{Z=transferArrayBuffer(W)}catch(t){C[Lr](t);return}let te={buffer:Z,bufferByteLength:Z.byteLength,byteOffset:Y,byteLength:q,bytesFilled:0,minimumFill:X,elementSize:H,viewConstructor:I,readerType:`byob`};if(t[Cr].pendingPullIntos.length!==0){t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C);return}if(N[Cr].state===`closed`){let t=new I(te.buffer,te.byteOffset,0);C[Fr](t);return}if(t[Cr].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,te)){let n=readableByteStreamControllerConvertPullIntoDescriptor(te);readableByteStreamControllerHandleQueueDrain(t),C[Ir](n);return}if(t[Cr].closeRequested){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(t,n),C[Lr](n);return}}t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespond(t,n){let S=t[Cr].pendingPullIntos[0];if(t[Cr].stream[Cr].state===`closed`){if(n!==0)throw TypeError(`bytesWritten must be 0 when calling respond() on a closed stream`)}else{if(n===0)throw TypeError(`bytesWritten must be greater than 0 when calling respond() on a readable stream`);if(S.bytesFilled+n>S.byteLength)throw RangeError(`bytesWritten out of range`)}S.buffer=transferArrayBuffer(S.buffer),readableByteStreamControllerRespondInternal(t,n)}function readableByteStreamControllerRespondWithNewView(t,n){let S=t[Cr].pendingPullIntos[0],C=t[Cr].stream[Cr].state,N=n.byteLength,F=n.byteOffset,I=n.buffer;if(C===`closed`){if(N!==0)throw TypeError(`view's length must be 0 when calling respondWithNewView() on a closed stream`)}else if(N===0)throw TypeError(`view's length must be greater than 0 when calling respondWithNewView() on a readable stream`);if(S.byteOffset+S.bytesFilled!==F)throw RangeError(`The region specified by view does not match byobRequest`);if(S.bufferByteLength!==I.byteLength)throw RangeError(`The buffer of view has different capacity than byobRequest`);if(S.bytesFilled+N>S.byteLength)throw RangeError(`The region specified by view is larger than byobRequest`);S.buffer=transferArrayBuffer(I),readableByteStreamControllerRespondInternal(t,N)}function readableByteStreamControllerRespondInternal(t,n){let S=t[Cr].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].stream[Cr].state===`closed`?readableByteStreamControllerRespondInClosedState(t,S):readableByteStreamControllerRespondInReadableState(t,n,S),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespondInClosedState(t,n){n.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(t);let S=t[Cr].stream;if(readableStreamHasBYOBReader(S))for(;readableStreamGetNumReadIntoRequests(S)>0;)readableByteStreamControllerCommitPullIntoDescriptor(S,readableByteStreamControllerShiftPendingPullInto(t))}function readableByteStreamControllerRespondInReadableState(t,n,S){if(readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S),S.readerType===`none`){readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t);return}if(S.bytesFilled<S.minimumFill)return;readableByteStreamControllerShiftPendingPullInto(t);let C=S.bytesFilled%S.elementSize;if(C>0){let n=S.byteOffset+S.bytesFilled;readableByteStreamControllerEnqueueClonedChunkToQueue(t,S.buffer,n-C,C)}S.bytesFilled-=C,readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)}function readableByteStreamControllerCancelSteps(t,n){readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(t),S}function readableByteStreamControllerPullSteps(t,n){let S=t[Cr].stream;if(t[Cr].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(t,n);return}let C=t[Cr].autoAllocateChunkSize;if(C!==void 0){let S;try{S=new ArrayBuffer(C)}catch(t){n[Lr](t);return}let N={buffer:S,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};t[Cr].pendingPullIntos.push(N)}readableStreamAddReadRequest(S,n),readableByteStreamControllerCallPullIfNeeded(t)}function setupReadableByteStreamController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,stream:t,byobRequest:null,pendingPullIntos:[],autoAllocateChunkSize:I},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableByteStreamControllerCallPullIfNeeded(n)},t=>readableByteStreamControllerError(n,t))}function setupReadableByteStreamControllerFromSource(t,n,S){let C=new ReadableByteStreamController(Br),N=n?.start,F=n?.pull,I=n?.cancel,H=n?.autoAllocateChunkSize;if(H!==void 0&&(H===0||!Number.isInteger(H)||H<0))throw TypeError(`autoAllocateChunkSize must be a positive integer`);setupReadableByteStreamController(t,C,N?N.bind(n,C):nonOpStart,F?createPromiseCallback(`source.pull`,F,n):nonOpPull,I?createPromiseCallback(`source.cancel`,I,n):nonOpCancel,S,H)}function readableByteStreamTee(t){let n=new ReadableStreamDefaultReader(t),S=!1,C=!1,N=!1,F,I,H=Promise.withResolvers(),W,q,Y,X;function pullAlgorithm(){return S?Promise.resolve():(S=!0,n.read().then(t=>{if(S=!1,t.done){C||Y.close(),N||X.close();return}let n=t.value,F=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));C||Y.enqueue(F),N||X.enqueue(new Uint8Array(F))},()=>{}),Promise.resolve())}return W=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(C=!0,F=n,N){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),q=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(N=!0,I=n,C){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),Y=W[Cr].controller,X=q[Cr].controller,n.closed.catch(t=>{Y.error(t),X.error(t),(!C||!N)&&H.resolve()}),[W,q]}const Yr=Symbol(`kSkipThrow`);var TransformStream=class{[wr]=`TransformStream`;[Cr];constructor(t={},n={},S={}){if(t!=null&&typeof t!=`object`)throw TypeError(`transformer must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`writableStrategy must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`readableStrategy must be an object`);let C=t?.readableType,N=t?.writableType,F=t?.start;if(C!==void 0)throw RangeError(`Invalid readableType: ${C}`);if(N!==void 0)throw RangeError(`Invalid writableType: ${N}`);let I=extractHighWaterMark(S?.highWaterMark,0),H=extractSizeAlgorithm(S?.size),W=extractHighWaterMark(n?.highWaterMark,1),q=extractSizeAlgorithm(n?.size),Y=Promise.withResolvers();initializeTransformStream(this,Y,W,q,I,H),setupTransformStreamDefaultControllerFromTransformer(this,t),F===void 0?Y.resolve():Y.resolve(F.call(t,this[Cr].controller))}get readable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].readable}get writable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[wr]=`TransformStreamDefaultController`;[Cr];constructor(t){if(t!==Yr)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!Zr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr],{readable:n}=t[Cr],S=n[Cr].controller;return readableStreamDefaultControllerGetDesiredSize(S)}enqueue(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,t)}error(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,t)}terminate(){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Xr=isBrandCheck(`TransformStream`),Zr=isBrandCheck(`TransformStreamDefaultController`);async function defaultTransformAlgorithm(t,n){transformStreamDefaultControllerEnqueue(n,t)}function initializeTransformStream(t,n,S,C,N,F){let startAlgorithm=()=>n.promise,I=createWritableStream(startAlgorithm,n=>transformStreamDefaultSinkWriteAlgorithm(t,n),()=>transformStreamDefaultSinkCloseAlgorithm(t),n=>transformStreamDefaultSinkAbortAlgorithm(t,n),S,C);t[Cr]={readable:createReadableStream(startAlgorithm,()=>transformStreamDefaultSourcePullAlgorithm(t),n=>transformStreamDefaultSourceCancelAlgorithm(t,n),N,F),writable:I,controller:void 0,backpressure:void 0,backpressureChange:{promise:void 0,resolve:void 0,reject:void 0}},transformStreamSetBackpressure(t,!0)}function transformStreamError(t,n){let{readable:S}=t[Cr];readableStreamDefaultControllerError(S[Cr].controller,n),transformStreamErrorWritableAndUnblockWrite(t,n)}function transformStreamErrorWritableAndUnblockWrite(t,n){let{controller:S,writable:C}=t[Cr];transformStreamDefaultControllerClearAlgorithms(S),writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t)}function transformStreamUnblockWrite(t){t[Cr].backpressure&&transformStreamSetBackpressure(t,!1)}function transformStreamSetBackpressure(t,n){t[Cr].backpressureChange.promise!==void 0&&t[Cr].backpressureChange.resolve?.(),t[Cr].backpressureChange=Promise.withResolvers(),t[Cr].backpressure=n}function setupTransformStreamDefaultController(t,n,S,C,N){n[Cr]={stream:t,transformAlgorithm:S,flushAlgorithm:C,cancelAlgorithm:N,finishPromise:void 0},t[Cr].controller=n}function setupTransformStreamDefaultControllerFromTransformer(t,n){let S=new TransformStreamDefaultController(Yr),C=n?.transform,N=n?.flush,F=n?.cancel;setupTransformStreamDefaultController(t,S,C?createPromiseCallback(`transformer.transform`,C,n):defaultTransformAlgorithm,N?createPromiseCallback(`transformer.flush`,N,n):nonOpFlush,F?createPromiseCallback(`transformer.cancel`,F,n):nonOpCancel)}function transformStreamDefaultControllerClearAlgorithms(t){t[Cr].transformAlgorithm=void 0,t[Cr].flushAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(t,n){let{stream:S}=t[Cr],{readable:C}=S[Cr],N=C[Cr].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(N))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(N,n)}catch(t){throw transformStreamErrorWritableAndUnblockWrite(S,t),C[Cr].storedError}readableStreamDefaultControllerHasBackpressure(N)!==S[Cr].backpressure&&transformStreamSetBackpressure(S,!0)}function transformStreamDefaultControllerError(t,n){transformStreamError(t[Cr].stream,n)}async function transformStreamDefaultControllerPerformTransform(t,n){try{let S=t[Cr].transformAlgorithm;if(S===void 0)return;await S(n,t)}catch(n){throw transformStreamError(t[Cr].stream,n),n}}function transformStreamDefaultControllerTerminate(t){let{stream:n}=t[Cr],{readable:S}=n[Cr];readableStreamDefaultControllerClose(S[Cr].controller),transformStreamErrorWritableAndUnblockWrite(n,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(t,n){let{controller:S}=t[Cr];return t[Cr].backpressure?t[Cr].backpressureChange.promise.then(()=>{let{writable:C}=t[Cr];if(C[Cr].state===`erroring`)throw C[Cr].storedError;return transformStreamDefaultControllerPerformTransform(S,n)}):transformStreamDefaultControllerPerformTransform(S,n)}async function transformStreamDefaultSinkAbortAlgorithm(t,n){let{controller:S,readable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(readableStreamDefaultControllerError(C[Cr].controller,n),F())},t=>{readableStreamDefaultControllerError(C[Cr].controller,t),I(t)}),S[Cr].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(t){let{readable:n,controller:S}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:C,resolve:N,reject:F}=Promise.withResolvers();S[Cr].finishPromise=C;let I=S[Cr].flushAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(S),I.then(()=>{n[Cr].state===`errored`?F(n[Cr].storedError):(readableStreamDefaultControllerClose(n[Cr].controller),N())},t=>{readableStreamDefaultControllerError(n[Cr].controller,t),F(t)}),S[Cr].finishPromise}function transformStreamDefaultSourcePullAlgorithm(t){return transformStreamSetBackpressure(t,!1),t[Cr].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(t,n){let{controller:S,writable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),F())},n=>{writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),I(n)}),S[Cr].finishPromise}const Qr=Object.defineProperty(t=>t.byteLength,"name",{value:`size`}),$r=Object.defineProperty(()=>1,"name",{value:`size`});var ByteLengthQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return Qr}get[Symbol.toStringTag](){return`ByteLengthQueuingStrategy`}},CountQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return $r}get[Symbol.toStringTag](){return`CountQueuingStrategy`}},TextEncoderStream=class{#e=null;#t=new TextEncoder;#n;constructor(){this.#n=new TransformStream({transform:(t,n)=>{if(t=String(t),t===``)return;this.#e!==null&&(t=this.#e+t);let S=t.charCodeAt(t.length-1);55296<=S&&S<=56319?(this.#e=t.slice(-1),t=t.slice(0,-1)):this.#e=null,t&&n.enqueue(this.#t.encode(t))},flush:t=>{this.#e!==null&&t.enqueue(new Uint8Array([239,191,189]))}})}get encoding(){return`utf-8`}get readable(){return this.#n.readable}get writable(){return this.#n.writable}};function hasStreamingSupport(){try{return new TextDecoder().decode(new Uint8Array([195]),{stream:!0}),!0}catch{return!1}}const ei=hasStreamingSupport();function incompleteUtf8Tail$1(t){let n=t.length;if(n===0)return 0;for(let S=1;S<=Math.min(3,n);S++){let C=t[n-S];if(!(C&128))return 0;if((C&192)!=128){let t;if((C&224)==192)t=2;else if((C&240)==224)t=3;else if((C&248)==240)t=4;else return 0;return S<t?S:0}}return 0}__name$1(incompleteUtf8Tail$1,`incompleteUtf8Tail`);var TextDecoderStream=class{#e;#t;constructor(t,n){if(this.#e=new TextDecoder(t,n),ei)this.#t=new TransformStream({transform:(t,n)=>{let S=toUint8Array$3(t),C=this.#e.decode(S,{stream:!0});C&&n.enqueue(C)},flush:t=>{let n=this.#e.decode();n&&t.enqueue(n)},cancel:()=>{this.#e.decode()}});else{let t=new Uint8Array;this.#t=new TransformStream({transform:(n,S)=>{let C=toUint8Array$3(n),N;t.length>0?(N=new Uint8Array(t.length+C.length),N.set(t,0),N.set(C,t.length)):N=C;let F=incompleteUtf8Tail$1(N),I;if(F>0?(I=N.slice(0,N.length-F),t=N.slice(N.length-F)):(I=N,t=new Uint8Array),I.length>0){let t=this.#e.decode(I);t&&S.enqueue(t)}},flush:n=>{if(t.length>0){let S=this.#e.decode(t);S&&n.enqueue(S),t=new Uint8Array}},cancel:()=>{t=new Uint8Array}})}}get encoding(){return this.#e.encoding}get fatal(){return this.#e.fatal}get ignoreBOM(){return this.#e.ignoreBOM}get readable(){return this.#t.readable}get writable(){return this.#t.writable}};function toUint8Array$3(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`chunk must be a BufferSource`)}__name$1(toUint8Array$3,`toUint8Array`);function isNativeStreamUsable$3(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$3,`isNativeStreamUsable`);const ti=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,ni=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,ri=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,ii=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,ai=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,oi=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,si=typeof globalThis.TextDecoderStream==`function`?globalThis.TextDecoderStream:TextDecoderStream;function withCode(t,n){return Object.assign(t,{code:n})}function addNumericalSeparator(t){let n=``,S=t.length,C=+(t[0]===`-`);for(;S>=C+4;S-=3)n=`_${t.slice(S-3,S)}${n}`;return`${t.slice(0,S)}${n}`}function formatReceivedNumber(t){return Number.isInteger(t)&&Math.abs(t)>2**32?addNumericalSeparator(String(t)):Object.is(t,-0)?`-0`:String(t)}function describeType(t){if(t===null)return`null`;switch(typeof t){case`bigint`:return`type bigint (${t}n)`;case`boolean`:return`type boolean (${t})`;case`symbol`:return`type symbol (${String(t)})`;case`function`:return`function ${t.name}`;case`string`:{let n=t.length>28?`${t.slice(0,25)}...`:t;return n.includes(`'`)?`type string (${JSON.stringify(n)})`:`type string ('${n}')`}default:{let n=t.constructor;return n?.name?`an instance of ${n.name}`:`type ${typeof t}`}}}function outOfRange(t,n){return withCode(RangeError(`The value of "${li}" is out of range. It must be ${t}. Received ${formatReceivedNumber(n)}`),`ERR_OUT_OF_RANGE`)}function resolveMaxOutputLength(t){let n=t?.maxOutputLength;if(n===void 0)return ci;if(typeof n!=`number`)throw withCode(TypeError(`The "${li}" property must be of type number. Received ${describeType(n)}`),`ERR_INVALID_ARG_TYPE`);if(Number.isNaN(n))return ci;if(!Number.isFinite(n))throw outOfRange(`a finite number`,n);if(n<1||n>ci)throw outOfRange(`>= 1 and <= ${ci}`,n);return n}function bufferTooLargeError(t){return withCode(RangeError(`Cannot create a Buffer larger than ${t} bytes`),`ERR_BUFFER_TOO_LARGE`)}function isBufferTooLargeError(t){return t instanceof RangeError&&t.code===`ERR_BUFFER_TOO_LARGE`}function remainingReadBudget(t,n){return Math.floor(t-n)+1}var ci,li,di=__esmMin(()=>{ci=2**53-1,li=`options.maxOutputLength`}),fi,pi=__esmMin(()=>{fi=n}),mi,hi=__esmMin(()=>{pi(),mi=fi});function getGioFormat(t){switch(t){case`gzip`:return mi.ZlibCompressorFormat.GZIP;case`deflate`:return mi.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return mi.ZlibCompressorFormat.RAW}}function hasGzipMagic(t,n=0){return t.length-n>=2&&t[n]===31&&t[n+1]===139}function concat$2(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function assertLevel(t){if(!(t>=-1&&t<=9))throw RangeError(`The value of "level" is out of range. It must be >= -1 and <= 9. Received ${t}`)}function compressWithGio(t,n,S=-1){assertLevel(S);let C=new mi.ZlibCompressor({format:getGioFormat(n),level:Math.trunc(S)}),N=new mi.ConverterOutputStream({base_stream:mi.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new lt.Bytes(t),null),N.close(null);let F=N.get_base_stream().steal_as_bytes();return new Uint8Array(F.get_data()??[])}function decompressStreamWithGio(t,n,S=ci,C=0){let N=new mi.ZlibDecompressor({format:getGioFormat(n)}),F=mi.MemoryInputStream.new_from_bytes(new lt.Bytes(t)),I=new mi.ConverterInputStream({base_stream:F,converter:N}),H=[],W=C;try{for(;;){let t=Math.min(_i,remainingReadBudget(S,W)),n=I.read_bytes(t,null),C=n.get_size();if(C===0)break;if(W+=C,W>S)throw bufferTooLargeError(S);H.push(new Uint8Array(n.get_data()))}}finally{I.close(null)}return concat$2(H)}function findGzipMemberEnd(t,n=1/0){let S=new mi.ZlibDecompressor({format:mi.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0,F=0;for(;;){let I=t.subarray(N,N+gi);try{let[t,H,W]=S.convert(I,C,mi.ConverterFlags.NONE);if(N+=H,F+=W,t===mi.ConverterResult.FINISHED||F>n||H===0&&W===0)return N}catch{return N}}}function gunzipWithGio(t,n=ci){let S=[],C=0,N=0;for(;hasGzipMagic(t,C);){let F=t.subarray(C),I=findGzipMemberEnd(F,n-N);if(I<=0)break;let H=decompressStreamWithGio(F.subarray(0,I),`gzip`,n,N);S.push(H),N+=H.length,C+=I}return S.length===0?decompressStreamWithGio(t,`gzip`,n):concat$2(S)}var gi,_i,vi=__esmMin(()=>{di(),hi(),ut(),gi=256*1024,_i=1024*1024,__name$1(concat$2,`concat`)}),yi=__esmMin(()=>{ze()}),bi,xi,Si=__esmMin(()=>{bi=Object.defineProperty,xi=__name$1((t,n)=>{let S={};for(var C in t)bi(S,C,{get:t[C],enumerable:!0});return n||bi(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function _setPipeImpl(t){Ci=t}var Ci,Stream_,wi=__esmMin(()=>{qt(),Stream_=class extends It{constructor(t){super(t)}pipe(t,n){return Ci(this,t,n)}}});function finished$1(t,n,S){let C;C=typeof n==`function`?n:S;let N=!1;function done(t){N||(N=!0,C(t))}let onFinish=()=>done(),onEnd=()=>done(),onError=t=>done(t),onClose=()=>{let n=t,S=t;!n.writableFinished&&!S.readableEnded&&done(Error(`premature close`))};t.on(`finish`,onFinish),t.on(`end`,onEnd),t.on(`error`,onError),t.on(`close`,onClose);let F=t,I=typeof t.write==`function`,H=typeof t.read==`function`,W=F.writableFinished===!0,q=F.readableEnded===!0;if(F.destroyed===!0){let t=F._err;ve(t?()=>done(t):I&&W||H&&q?()=>done():()=>done(Error(`premature close`)))}else(I&&!H&&W||!I&&H&&q||I&&H&&W&&q)&&ve(()=>done());return function cleanup(){t.removeListener(`finish`,onFinish),t.removeListener(`end`,onEnd),t.removeListener(`error`,onError),t.removeListener(`close`,onClose)}}function addAbortSignal(t,n){if(!(t instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(n instanceof Stream_))throw TypeError(`The second argument must be a Stream`);let S=n;if(t.aborted)S.destroy(Error(`The operation was aborted`));else{let onAbort=()=>{S.destroy(Error(`The operation was aborted`))};t.addEventListener(`abort`,onAbort,{once:!0}),n.once(`close`,()=>{t.removeEventListener(`abort`,onAbort)})}return n}function isReadable(t){if(t==null)return!1;let n=t;return typeof n.readable!=`boolean`||typeof n.read!=`function`||n.destroyed===!0||n.readableEnded===!0?!1:n.readable===!0}function isWritable(t){if(t==null)return!1;let n=t;return typeof n.writable!=`boolean`||typeof n.write!=`function`||n.destroyed===!0||n.writableEnded===!0?!1:n.writable===!0}function isDestroyed(t){return t==null?!1:t.destroyed===!0}function isDisturbed(t){if(t==null)return!1;let n=t;return n.readableDidRead===!0||n.readableFlowing!==null&&n.readableFlowing!==void 0}function isErrored(t){if(t==null)return!1;let n=t;return n.destroyed===!0&&typeof n.readable==`boolean`&&n.readable===!1||n.destroyed===!0&&typeof n.writable==`boolean`&&n.writable===!1}var Ti=__esmMin(()=>{wi(),ze(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(t){return t?Di:Ei}function setDefaultHighWaterMark(t,n){if(typeof n!=`number`||n<0||Number.isNaN(n))throw TypeError(`Invalid highWaterMark: ${n}`);t?Di=n:Ei=n}function validateHighWaterMark(t,n){if(n!==void 0&&(typeof n!=`number`||Number.isNaN(n))){let S=TypeError(`The value of "${t}" is invalid. Received ${n}`);throw S.code=`ERR_INVALID_ARG_VALUE`,S}}var Ei,Di,Oi=__esmMin(()=>{Ei=16384,Di=16});function createAbortError(){let t=Error(`The operation was aborted`);return t.name=`AbortError`,t.code=`ABORT_ERR`,t}async function streamAsyncDispose(t,n){let S;t.destroyed||(S=n?void 0:createAbortError(),t.destroy(S)),await new Promise((n,C)=>{finished$1(t,t=>{t&&t!==S?C(t):n()})})}var ki,Ai=__esmMin(()=>{Ti(),ki=Symbol.asyncDispose??Symbol.for(`Symbol.asyncDispose`)});function chunkLength(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}function sliceChunk(t,n,S){if(typeof t==`string`)return S===void 0?t.slice(n):t.slice(n,S);let C=t.slice;return typeof C==`function`?C.call(t,n,S):t}var ji,Mi,Ni,Pi=__esmMin(()=>{wi(),Ai(),Oi(),ze(),ji=class Readable_ extends Stream_{readable=!0;readableFlowing=null;readableLength=0;readableHighWaterMark;readableEncoding;readableObjectMode;readableEnded=!1;readableAborted=!1;destroyed=!1;_pipeDests=[];_buffer=[];_readableState={ended:!1,endEmitted:!1,reading:!1,constructed:!0,highWaterMark:0,objectMode:!1,pipes:[]};_err;_readablePending=!1;_readImpl;_constructImpl;constructor(t){super(t),this.readableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.readableEncoding=t?.encoding??null,this.readableObjectMode=t?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,t?.read&&(this._readImpl=t.read),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Readable_.prototype._construct)&&(this._readableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._readableState.constructed=!0,t?this.destroy(t):this.readableFlowing===!0&&this._flow()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_read(t){this._readImpl&&this._readImpl.call(this,t)}read(t){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(t??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||t===0)return null;if(this.readableObjectMode){if(t===void 0){let t=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),t}if(t>this.readableLength)return null;let n=this._buffer.shift();return--this.readableLength,n}if(t!=null)return t>this.readableLength?null:this._readBytes(t);let n=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),n.length===1)return n[0];if(n.length===0)return null;if(typeof n[0]==`string`)return n.join(``);let S=globalThis.Buffer;return S?.concat?S.concat(n):n}_readBytes(t){let n=0,S=[];for(;n<t&&this._buffer.length>0;){let C=this._buffer[0],N=chunkLength(C);if(n+N<=t)S.push(this._buffer.shift()),n+=N,this.readableLength-=N;else{let N=t-n;S.push(sliceChunk(C,0,N)),this._buffer[0]=sliceChunk(C,N),this.readableLength-=N,n+=N}}if(S.length===1)return S[0];let C=globalThis.Buffer;return C?.concat?C.concat(S):S}push(t,n){if(t===null)return this._readableState.ended=!0,this.readableEnded=!0,this._buffer.length===0&&!this._readableState.endEmitted&&nextTick(()=>this._emitEnd()),this._scheduleReadable(),!1;if(!this.readableObjectMode&&!(typeof t==`string`||ArrayBuffer.isView(t))){let n=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof t}`),{code:`ERR_INVALID_ARG_TYPE`});return nextTick(()=>this.emit(`error`,n)),!1}return this._buffer.push(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t),this.readableFlowing&&!this._flowing&&nextTick(()=>this._flow()),this.readableFlowing!==!0&&this._scheduleReadable(),this.readableLength<this.readableHighWaterMark}_emitEnd(){this._readableState.endEmitted||(this._readableState.endEmitted=!0,this.emit(`end`),nextTick(()=>this._autoClose()))}_autoClose(){this.emit(`close`)}_scheduleReadable(){this._readablePending||this.listenerCount(`readable`)===0||(this._readablePending=!0,nextTick(()=>{this._readablePending=!1,this.destroyed||this.emit(`readable`)}))}on(t,n){return super.on(t,n),t===`data`&&this.readableFlowing!==!1&&this.listenerCount(`readable`)===0&&this.resume(),t===`readable`&&(this.readableFlowing=!1,this._buffer.length>0||this._readableState.ended?this._scheduleReadable():this._readableState.reading||nextTick(()=>{this.destroyed||this.read(0)})),this}removeListener(t,n){let S=super.removeListener(t,n);return t===`readable`&&nextTick(()=>this._updateReadableListening()),S}removeAllListeners(t){let n=t===void 0?super.removeAllListeners():super.removeAllListeners(t);return(t===`readable`||t===void 0)&&nextTick(()=>this._updateReadableListening()),n}_updateReadableListening(){this.listenerCount(`readable`)>0||(this.listenerCount(`data`)>0?this.resume():this.readableFlowing=null)}unshift(t){this._buffer.unshift(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t)}setEncoding(t){return this.readableEncoding=t,this}pause(){return this.readableFlowing=!1,this.emit(`pause`),this}resume(){return this.readableFlowing!==!0&&(this.readableFlowing=!0,this.emit(`resume`),this._readableState.constructed&&this._flow()),this}_flowing=!1;_flow(){if(!(this.readableFlowing!==!0||this._flowing||this.destroyed)&&this._readableState.constructed){this._flowing=!0;try{for(;this._buffer.length>0&&this.readableFlowing&&!this.destroyed;){let t=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:chunkLength(t),this.readableEncoding&&typeof t!=`string`){let n=globalThis.Buffer;n?.isBuffer&&n.isBuffer(t)?t=t.toString(this.readableEncoding):t instanceof Uint8Array&&(t=new TextDecoder(this.readableEncoding).decode(t))}this.emit(`data`,t)}if(this.destroyed)return;if(this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted){nextTick(()=>this._emitEnd());return}!this._readableState.ended&&!this._readableState.reading&&!this.destroyed&&(this._readableState.reading=!0,this._read(this.readableHighWaterMark),this._readableState.reading=!1)}finally{this._flowing=!1}this._buffer.length>0&&this.readableFlowing&&!this.destroyed&&nextTick(()=>this._flow())}}isPaused(){return this.readableFlowing===!1}unpipe(t){if(t){let n=this._pipeDests.findIndex(n=>n.dest===t);if(n!==-1){this._pipeDests[n].cleanup(),this._pipeDests.splice(n,1);let S=this._readableState.pipes.indexOf(t);S!==-1&&this._readableState.pipes.splice(S,1),t.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let t of this._pipeDests)t.cleanup(),t.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(t,n){n(t??void 0)}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}static toWeb(t){return new ReadableStream({start(n){t.on(`data`,t=>{typeof t==`string`?n.enqueue(new TextEncoder().encode(t)):t instanceof Uint8Array?n.enqueue(t):t&&typeof t.length==`number`&&n.enqueue(new Uint8Array(t))}),t.on(`end`,()=>{n.close()}),t.on(`error`,t=>{n.error(t)})},cancel(){t.destroy()}})}static fromWeb(t,n){let S=t.getReader();return new Readable_({...n,read(){S.read().then(({done:t,value:n})=>{t?this.push(null):this.push(n)},t=>{this.destroy(t)})},destroy(t,n){S.cancel(t?.message).then(()=>n(null),n)}})}[Symbol.asyncIterator](){let t=this,n=[],S=!1,C=null,N=null,F=null;return t.on(`data`,t=>{if(N){let n=N;N=null,F=null,n({value:t,done:!1})}else n.push(t)}),t.on(`end`,()=>{if(S=!0,N){let t=N;N=null,F=null,t({value:void 0,done:!0})}}),t.on(`error`,t=>{if(C=t,S=!0,F){let n=F;N=null,F=null,n(t)}}),{next(){return C?Promise.reject(C):n.length>0?Promise.resolve({value:n.shift(),done:!1}):S?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{N=t,F=n})},return(){return t.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(t,n){let S=new Readable_({objectMode:!0,...n,read(){}});return typeof t==`string`||ArrayBuffer.isView(t)?(S.push(t),S.push(null),S):((async()=>{try{for await(let n of t)S.push(n)||await new Promise(t=>S.once(`drain`,t));S.push(null)}catch(t){S.destroy(t)}})(),S)}},ji.prototype[ki]=function(){return streamAsyncDispose(this,this.readableEnded)},Mi=Object.getOwnPropertyDescriptor(ji.prototype,`on`),Ni=Object.getOwnPropertyDescriptor(ji.prototype,`removeListener`),Object.defineProperty(ji.prototype,"addListener",{...Mi}),Object.defineProperty(ji.prototype,"off",{...Ni})});function writeAfterEndError(){let t=Error(`write after end`);return t.code=`ERR_STREAM_WRITE_AFTER_END`,t}var Fi=__esmMin(()=>{});function chunkLen$1(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Duplex_,Ii=__esmMin(()=>{Fi(),Oi(),Pi(),ze(),Duplex_=class extends ji{writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;allowHalfOpen;_decodeStrings;_writableState={highWaterMark:0,objectMode:!1};_duplexCorkedBuffer=[];_duplexWriting=!1;_duplexWriteQueue=[];_writeImpl;_finalImpl;_defaultEncoding=`utf8`;_pendingWrites=0;_pendingEndCb=null;constructor(t){super(t),validateHighWaterMark(`writableHighWaterMark`,t?.writableHighWaterMark),validateHighWaterMark(`readableHighWaterMark`,t?.readableHighWaterMark),this.writableObjectMode=t?.writableObjectMode??t?.objectMode??!1,this.writableHighWaterMark=t?.highWaterMark??t?.writableHighWaterMark??getDefaultHighWaterMark(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,t?.highWaterMark===void 0&&t?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=t.readableHighWaterMark,this._readableState.highWaterMark=t.readableHighWaterMark),t?.readableObjectMode!==void 0&&(this.readableObjectMode=t.readableObjectMode,this._readableState.objectMode=t.readableObjectMode,t?.readableHighWaterMark===void 0&&t?.highWaterMark===void 0&&(this.readableHighWaterMark=getDefaultHighWaterMark(t.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=t?.allowHalfOpen!==!1,this._decodeStrings=t?.decodeStrings!==!1,t?.write&&(this._writeImpl=t.write),t?.final&&(this._finalImpl=t.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||nextTick(()=>this.end())})}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}destroy(t){return this.destroyed?this:(this.writable=!1,super.destroy(t))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen$1(t),this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._duplexDoWrite(t,N,C),F}_duplexDoWrite(t,n,S){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:t,encoding:n,callback:S});return}this._duplexWriting=!0,this._duplexStartWrite(t,n,S)}_duplexStartWrite(t,n,S){this._pendingWrites++,this._write(t,n,n=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:chunkLen$1(t),nextTick(n?()=>{if(S(n),this._duplexWriting=!1,this.destroyed||this.emit(`error`,n),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(t.chunk,t.encoding,t.callback)}}:()=>{if(S(),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexStartWrite(t.chunk,t.encoding,t.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let t=this._pendingEndCb;this._pendingEndCb=null,t()}})})}end(t,n,S){typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),t!=null&&this.write(t,n),this.writableEnded=!0;let doFinal=()=>{this._final(t=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),nextTick(()=>this.emit(`close`)),S&&S()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_doPrefinishHooks(t){t()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let t=this._duplexCorkedBuffer.splice(0);for(let{chunk:n,encoding:S,callback:C}of t)this._write(n,S,t=>{this.writableLength-=this.writableObjectMode?1:chunkLen$1(n),t?(C(t),this.destroyed||this.emit(`error`,t)):C()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,nextTick(()=>this.emit(`drain`)))}}setDefaultEncoding(t){return this._defaultEncoding=t,this}},__name$1(chunkLen$1,`chunkLen`)});function pipe(t,n,S){let C=t,N=S?.end!==!1,F=!1,ondrain=()=>{F=!1,n.removeListener(`drain`,ondrain);let t=C;typeof t.resume==`function`&&t.resume()},ondata=t=>{if(n.writable){let S=C;n.write(t)===!1&&typeof S.pause==`function`&&(S.pause(),F||(F=!0,n.on(`drain`,ondrain)))}};C.on(`data`,ondata);let I=!1,onend=()=>{I||(I=!0,N&&n.end())},onclose=()=>{if(!I&&(I=!0,N&&!(C instanceof ji))){let t=n;typeof t.destroy==`function`&&t.destroy()}};N&&(C.on(`end`,onend),C.on(`close`,onclose));let cleanup=()=>{C.removeListener(`data`,ondata),F&&n.removeListener(`drain`,ondrain),C.removeListener(`end`,onend),C.removeListener(`close`,onclose),C.removeListener(`end`,cleanup),C.removeListener(`close`,cleanup),n.removeListener(`close`,cleanup)};return C.on(`end`,cleanup),C.on(`close`,cleanup),n.on(`close`,cleanup),C instanceof ji&&(C._pipeDests.push({dest:n,cleanup}),C._readableState.pipes.push(n)),n.emit(`pipe`,C),n}var Li=__esmMin(()=>{wi(),Pi(),_setPipeImpl(pipe)});function chunkLen(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Ri,zi=__esmMin(()=>{Fi(),wi(),Ai(),Oi(),ze(),Ri=class Writable_ extends Stream_{static[Symbol.hasInstance](t){let n=this;return n.prototype!==void 0&&Object.prototype.isPrototypeOf.call(n.prototype,t)?!0:n.prototype!==Writable_.prototype||t==null?!1:typeof t.writableHighWaterMark==`number`}writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;destroyed=!1;_err;_writableState={ended:!1,finished:!1,constructed:!0,writing:!1};_corkedBuffer=[];_writeBuffer=[];_pendingConstruct=[];_ending=!1;_endCallback;_pendingEnd=null;_writeImpl;_writev;_finalImpl;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;_autoDestroy;constructor(t){super(t),this.writableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.writableObjectMode=t?.objectMode??!1,this._decodeStrings=t?.decodeStrings!==!1,this._autoDestroy=t?.autoDestroy!==!1,t?.write&&(this._writeImpl=t.write),t?.writev&&(this._writev=t.writev),t?.final&&(this._finalImpl=t.final),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Writable_.prototype._construct)&&(this._writableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._writableState.constructed=!0,t?this.destroy(t):this._maybeFlush()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}_destroy(t,n){n(t)}_maybeFlush(){let t=this._pendingConstruct.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}if(this._pendingEnd){let{chunk:t,encoding:n,callback:S}=this._pendingEnd;this._pendingEnd=null,this._doEnd(t,n,S)}}_doWrite(t,n,S){this._writableState.writing=!0;let C=!0;this._write(t,n,n=>{if(this.writableLength-=this.writableObjectMode?1:chunkLen(t),C){nextTick(()=>{if(n){S(n),this.emit(`error`,n);return}S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),n||this._drainWriteBuffer();return}nextTick(n?()=>{S(n),this.emit(`error`,n),this._drainWriteBuffer()}:()=>{S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),C=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let t=this._writeBuffer.shift();this._doWrite(t.chunk,t.encoding,t.callback)}else this._writableState.writing=!1,this._maybeFinish()}_maybeFinish(){!this._ending||this._writableState.finished||this._writableState.writing||this._writeBuffer.length>0||(this._ending=!1,this._final(t=>{this.writableFinished=!0,this._writableState.finished=!0,nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),this._autoDestroy?this.destroy():nextTick(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen(t),this.writableCorked>0)return this._corkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:t,encoding:N,callback:C}):this._doWrite(t,N,C),F}_doEnd(t,n,S){t!=null&&this.write(t,n),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=S,this._maybeFinish()}end(t,n,S){return typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),this.writableEnded?(S&&nextTick(S),this):this._writableState.constructed?(this._doEnd(t,n,S),this):(this._pendingEnd={chunk:t,encoding:n,callback:S},this)}cork(){this.writableCorked++}uncork(){this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._corkedBuffer.length>0&&this._flushCorkedBuffer())}_flushCorkedBuffer(){if(this._writev&&this._corkedBuffer.length>1){let t=this._corkedBuffer.splice(0),n=t.map(t=>({chunk:t.chunk,encoding:t.encoding}));this._writev.call(this,n,n=>{for(let n of t)this.writableLength-=this.writableObjectMode?1:chunkLen(n.chunk);if(n){for(let S of t)S.callback(n);this.emit(`error`,n)}else{for(let n of t)n.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let t=this._corkedBuffer.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}}}setDefaultEncoding(t){return this._defaultEncoding=t,this}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}},Ri.prototype[ki]=function(){return streamAsyncDispose(this,this.writableFinished)}}),Bi,Vi=__esmMin(()=>{Ii(),ze(),Bi=class Transform_ extends Duplex_{constructor(t){super({...t,write:void 0,final:void 0});let n=this;t?.transform&&(n._transform=t.transform),t?.flush&&(n._flush=t.flush),t?.final&&(n._final=t.final)}_transform(t,n,S){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(t){t()}_write(t,n,S){let C=!1;try{this._transform(t,n,(t,n)=>{if(C){let t=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});nextTick(()=>this.emit(`error`,t));return}if(C=!0,t){S(t);return}n!=null&&this.push(n),S()})}catch(t){if(t?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw t;S(t)}}_final(t){this._flush((n,S)=>{if(n){t(n);return}S!=null&&this.push(S),this.push(null),t()})}_doPrefinishHooks(t){let n=Transform_.prototype._final;this._final===n?t():n.call(this,t)}}}),PassThrough_,Hi=__esmMin(()=>{Vi(),PassThrough_=class extends Bi{constructor(t){super({...t,transform(t,n,S){S(null,t)}})}}});function pipeline$1(...t){let n=t,S=typeof n[n.length-1]==`function`?n.pop():void 0,C=n;if(C.length<2)throw Error(`pipeline requires at least 2 streams`);let N=null;function onError(t){if(!N){N=t;for(let t of C)typeof t.destroy==`function`&&t.destroy();S&&S(t)}}let F=C[0];for(let t=1;t<C.length;t++){let n=C[t];F.pipe(n),F.on(`error`,onError),F=n}let I=C[C.length-1];return I.on(`error`,onError),I.on(`finish`,()=>{S&&!N&&S(null)}),I}var Ui=__esmMin(()=>{__name$1(pipeline$1,`pipeline`)});function pipeline(...t){return new Promise((n,S)=>{let cb=t=>{t?S(t):n()};pipeline$1(...t,cb)})}function finished(t,n){return new Promise((S,C)=>{n&&typeof n!=`function`?finished$1(t,n,t=>{t?C(t):S()}):finished$1(t,t=>{t?C(t):S()})})}var Wi,Gi,Ki=__esmMin(()=>{Si(),Ti(),Ui(),Wi=xi({default:()=>Gi,finished:()=>finished,pipeline:()=>pipeline}),Gi={pipeline,finished}}),qi=__exportAll$5({Duplex:()=>Zi,PassThrough:()=>$i,Readable:()=>Yi,Stream:()=>Ji,Transform:()=>Qi,Writable:()=>Xi,addAbortSignal:()=>addAbortSignal,default:()=>ea,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>ea,pipeline:()=>pipeline$1,promises:()=>Wi,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta=__esmMin(()=>{yi(),wi(),Ti(),Oi(),Pi(),Ii(),Li(),zi(),Vi(),Hi(),Ui(),Ki(),Ji=makeCallable(Stream_),Yi=makeCallable(ji),Xi=makeCallable(Ri),Zi=makeCallable(Duplex_),Qi=makeCallable(Bi),$i=makeCallable(PassThrough_),ea=Object.assign(Ji,{Stream:Ji,Readable:Yi,Writable:Xi,Duplex:Zi,Transform:Qi,PassThrough:$i,pipeline:pipeline$1,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark,promises:Wi})});function toUint8Array$2(t){return typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function concat$1(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function createGzip(t){return new Gzip(t)}function createGunzip(t){return new Gunzip(t)}function createDeflate(t){return new Deflate(t)}function createInflate(t){return new Inflate(t)}function createDeflateRaw(t){return new DeflateRaw(t)}function createInflateRaw(t){return new InflateRaw(t)}function createUnzip(t){return new Unzip(t)}function createBrotliCompress(t){throw Error(`createBrotliCompress is not supported on GJS (no Brotli in GLib)`)}function createBrotliDecompress(t){throw Error(`createBrotliDecompress is not supported on GJS (no Brotli in GLib)`)}function createZstdCompress(t){let n=Error(`createZstdCompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}function createZstdDecompress(t){let n=Error(`createZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}var ZlibBase,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,na=__esmMin(()=>{di(),vi(),ta(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends Qi{_mode;_chunks=[];constructor(t,n){resolveMaxOutputLength(n),super(n),this._mode=t}_transform(t,n,S){this._chunks.push(toUint8Array$2(t)),S()}_flush(t){let n=concat$1(this._chunks);this._chunks=[];try{this.push(Buffer.from(this._run(n))),t()}catch(n){t(n instanceof Error?n:Error(String(n)))}}_run(t){let n=this._mode;switch(n.kind){case`compress`:return compressWithGio(t,n.format);case`decompress`:return decompressStreamWithGio(t,n.format);case`gunzip`:return gunzipWithGio(t);case`unzip`:return hasGzipMagic(t)?gunzipWithGio(t):decompressStreamWithGio(t,`deflate`)}}},Gzip=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`gzip`},t)}},Gunzip=class extends ZlibBase{constructor(t){super({kind:`gunzip`},t)}},Deflate=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate`},t)}},Inflate=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate`},t)}},DeflateRaw=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate-raw`},t)}},InflateRaw=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate-raw`},t)}},Unzip=class extends ZlibBase{constructor(t){super({kind:`unzip`},t)}},BrotliCompress=class extends Qi{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends Qi{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends Qi{constructor(){super();let t=Error(`ZstdCompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}},ZstdDecompress=class extends Qi{constructor(){super();let t=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}}}),ra=__exportAll$5({BrotliCompress:()=>BrotliCompress,BrotliDecompress:()=>BrotliDecompress,Deflate:()=>Deflate,DeflateRaw:()=>DeflateRaw,Gunzip:()=>Gunzip,Gzip:()=>Gzip,Inflate:()=>Inflate,InflateRaw:()=>InflateRaw,Unzip:()=>Unzip,ZlibTransform:()=>ZlibBase,ZstdCompress:()=>ZstdCompress,ZstdDecompress:()=>ZstdDecompress,brotliCompress:()=>brotliCompress,brotliCompressSync:()=>brotliCompressSync,brotliDecompress:()=>brotliDecompress,brotliDecompressSync:()=>brotliDecompressSync,constants:()=>aa,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>oa,deflate:()=>deflate,deflateRaw:()=>deflateRaw,deflateRawSync:()=>deflateRawSync,deflateSync:()=>deflateSync,gunzip:()=>gunzip$1,gunzipSync:()=>gunzipSync,gzip:()=>gzip$1,gzipSync:()=>gzipSync,inflate:()=>inflate,inflateRaw:()=>inflateRaw,inflateRawSync:()=>inflateRawSync,inflateSync:()=>inflateSync,unzip:()=>unzip,unzipSync:()=>unzipSync,zstdCompress:()=>zstdCompress,zstdCompressSync:()=>zstdCompressSync,zstdDecompress:()=>zstdDecompress,zstdDecompressSync:()=>zstdDecompressSync});function decompressWithGio(t,n,S){return n===`gzip`?gunzipWithGio(t,S):decompressStreamWithGio(t,n,S)}function unzipFormat(t){return hasGzipMagic(t)?`gzip`:`deflate`}function assertWithinLimit(t,n){if(t.length>n)throw bufferTooLargeError(n);return t}async function runWebTransform(t,n,S=1/0){let C=new ReadableStream({start(n){n.enqueue(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),n.close()}}),N=[],F=0,I=C.pipeThrough(n).getReader();for(;;){let{done:t,value:n}=await I.read();if(t)break;if(F+=n.length,F>S)throw await I.cancel(),bufferTooLargeError(S);N.push(n)}let H=N.reduce((t,n)=>t+n.length,0),W=new Uint8Array(H),q=0;for(let t of N)W.set(t,q),q+=t.length;return W}async function compressWithWeb(t,n){return runWebTransform(t,new CompressionStream(n))}async function decompressWithWeb(t,n,S){return runWebTransform(t,new DecompressionStream(n),S)}function requestedLevel(t){let n=t?.level;if(!(n===void 0||n===-1))return assertLevel(n),n}async function compress(t,n,S,C){return S===void 0&&hasWebCompression()?assertWithinLimit(await compressWithWeb(t,n),C):assertWithinLimit(compressWithGio(t,n,S),C)}async function decompress(t,n,S){if(hasWebCompression()&&S>=ci)try{return await decompressWithWeb(t,n,S)}catch(C){if(n!==`gzip`||isBufferTooLargeError(C))throw C;return decompressWithGio(t,n,S)}return decompressWithGio(t,n,S)}function toUint8Array$1(t){return typeof t==`string`?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function runAsync(t,n,S,C){let N=typeof n==`function`?n:S,F=typeof n==`function`?void 0:n,I=resolveMaxOutputLength(F);C(toUint8Array$1(t),F,I).then(t=>N(null,t),t=>N(t instanceof Error?t:Error(String(t)),new Uint8Array))}function compressAsync(t){return(n,S,C)=>compress(n,t,requestedLevel(S),C)}function decompressAsync(t){return(n,S,C)=>decompress(n,t,C)}function gzip$1(t,n,S){runAsync(t,n,S,compressAsync(`gzip`))}function gunzip$1(t,n,S){runAsync(t,n,S,decompressAsync(`gzip`))}function deflate(t,n,S){runAsync(t,n,S,compressAsync(`deflate`))}function inflate(t,n,S){runAsync(t,n,S,decompressAsync(`deflate`))}function deflateRaw(t,n,S){runAsync(t,n,S,compressAsync(`deflate-raw`))}function inflateRaw(t,n,S){runAsync(t,n,S,decompressAsync(`deflate-raw`))}function unzip(t,n,S){runAsync(t,n,S,(t,n,S)=>decompress(t,unzipFormat(t),S))}function compressSync(t,n,S){let C=resolveMaxOutputLength(S);return assertWithinLimit(compressWithGio(toUint8Array$1(t),n,S?.level??-1),C)}function gzipSync(t,n){return compressSync(t,`gzip`,n)}function gunzipSync(t,n){return decompressWithGio(toUint8Array$1(t),`gzip`,resolveMaxOutputLength(n))}function deflateSync(t,n){return compressSync(t,`deflate`,n)}function inflateSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate`,resolveMaxOutputLength(n))}function deflateRawSync(t,n){return compressSync(t,`deflate-raw`,n)}function inflateRawSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate-raw`,resolveMaxOutputLength(n))}function unzipSync(t,n){let S=toUint8Array$1(t);return decompressWithGio(S,unzipFormat(S),resolveMaxOutputLength(n))}function brotliCompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliCompress: Brotli is not supported in this environment`),ia)}function brotliDecompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliDecompress: Brotli is not supported in this environment`),ia)}function brotliCompressSync(t,n){throw Error(`brotliCompressSync: Brotli is not supported in this environment`)}function brotliDecompressSync(t,n){throw Error(`brotliDecompressSync: Brotli is not supported in this environment`)}function zstdCompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdCompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ia)}function zstdDecompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdDecompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ia)}function zstdCompressSync(t,n){let S=Error(`zstdCompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}function zstdDecompressSync(t,n){let S=Error(`zstdDecompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}var hasWebCompression,ia,aa,oa,sa=__esmMin(()=>{di(),vi(),na(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),ia=new Uint8Array,aa={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8},oa={gzip:gzip$1,gunzip:gunzip$1,deflate,inflate,deflateRaw,inflateRaw,unzip,gzipSync,gunzipSync,deflateSync,inflateSync,deflateRawSync,inflateRawSync,unzipSync,brotliCompress,brotliDecompress,brotliCompressSync,brotliDecompressSync,zstdCompress,zstdDecompress,zstdCompressSync,zstdDecompressSync,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,createGzip,createGunzip,createDeflate,createInflate,createDeflateRaw,createInflateRaw,createUnzip,createBrotliCompress,createBrotliDecompress,createZstdCompress,createZstdDecompress,constants:aa}});const ca=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(t){if(!ca.has(t))throw TypeError(`Unsupported compression format: '${t}'. Supported formats: 'gzip', 'deflate', 'deflate-raw'.`);return t}const la=typeof globalThis.CompressionStream==`function`&&typeof globalThis.DecompressionStream==`function`;let ua=!1,da,fa,pa,ma,ha,ga;async function loadZlib(){if(ua)return;let t=await Promise.resolve().then(()=>(sa(),ra));da=t.gzipSync,fa=t.gunzipSync,pa=t.deflateSync,ma=t.inflateSync,ha=t.deflateRawSync,ga=t.inflateRawSync,ua=!0}function getCompressFn(t){switch(t){case`gzip`:return t=>da(t);case`deflate`:return t=>pa(t);case`deflate-raw`:return t=>ha(t)}}function getDecompressFn(t){switch(t){case`gzip`:return t=>fa(t);case`deflate`:return t=>ma(t);case`deflate-raw`:return t=>ga(t)}}function concatChunks$1(t){if(t.length===1)return t[0];let n=0;for(let S of t)n+=S.length;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}__name$1(concatChunks$1,`concatChunks`);let _a,va;if(la)_a=globalThis.CompressionStream,va=globalThis.DecompressionStream;else{let t=loadZlib();_a=class CompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getCompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}},va=class DecompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getDecompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}}}const ya=globalThis;globalThis.CompressionStream===void 0&&(ya.CompressionStream=_a),globalThis.DecompressionStream===void 0&&(ya.DecompressionStream=va);const ba=globalThis;globalThis.DOMException===void 0&&(ba.DOMException=tr);var xa,__name,Sa=__esmMin(()=>{xa=Object.defineProperty,__name=(t,n)=>xa(t,`name`,{value:n,configurable:!0})});function validateHeaderName(t){if(typeof t!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let n=TypeError(`Header name must be a valid HTTP token ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),n}}function validateHeaderValue(t,n){if(n===void 0){let n=TypeError(`Header "${t}" value must not be undefined`);throw Object.defineProperty(n,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),n}if(typeof n==`string`&&/[^\t -~€-ÿ]/.test(n)){let n=TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_CHAR`}),n}}const Ca=Symbol(`Headers.headers`);function isBoxedPrimitive$2(t){return t instanceof String||t instanceof Number||t instanceof Boolean||typeof Symbol<`u`&&t instanceof Symbol||typeof BigInt<`u`&&t instanceof BigInt}__name$1(isBoxedPrimitive$2,`isBoxedPrimitive`);var wa=class Headers{[Ca];constructor(t){if(this[Ca]=new Map,t!=null){if(t instanceof Headers){for(let[n,S]of t[Ca])this[Ca].set(n,[...S]);return}if(typeof t==`object`&&!isBoxedPrimitive$2(t)){let n=t[Symbol.iterator];if(n==null)for(let[n,S]of Object.entries(t))validateHeaderName(n),validateHeaderValue(n,String(S)),this.append(n,String(S));else{if(typeof n!=`function`)throw TypeError(`Header pairs must be iterable`);for(let n of t){if(typeof n!=`object`||isBoxedPrimitive$2(n))throw TypeError(`Each header pair must be an iterable object`);let t=[...n];if(t.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(t[0]),validateHeaderValue(t[0],String(t[1])),this.append(t[0],String(t[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase(),C=String(n),N=this[Ca].get(S);N?N.push(C):this[Ca].set(S,[C])}set(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase();this[Ca].set(S,[String(n)])}delete(t){this[Ca].delete(String(t).toLowerCase())}has(t){return this[Ca].has(String(t).toLowerCase())}get(t){let n=this[Ca].get(String(t).toLowerCase());if(!n||n.length===0)return null;let S=n.join(`, `);return/^content-encoding$/i.test(t)&&(S=S.toLowerCase()),S}getAll(t){return this[Ca].get(String(t).toLowerCase())??[]}getSetCookie(){return this[Ca].get(`set-cookie`)??[]}forEach(t,n){for(let S of this.keys())Reflect.apply(t,n,[this.get(S),S,this])}*keys(){let t=[...this[Ca].keys()].sort(),n=new Set;for(let S of t)n.has(S)||(n.add(S),yield S)}*values(){for(let t of this.keys())yield this.get(t)}*entries(){for(let t of this.keys())yield[t,this.get(t)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let t={};for(let n of this.keys())t[n]=this.getAll(n);return t}_appendToSoupMessage(t,n,S=t.MessageHeadersType.REQUEST){let C=n?n.get_request_headers():new t.MessageHeaders(S);for(let[t,n]of this.entries())C.append(t,n);return C}static _newFromSoupMessage(t,n,S=t.MessageHeadersType.RESPONSE){let C=new Headers,N;return N=S===t.MessageHeadersType.RESPONSE?n.get_response_headers():n.get_request_headers(),N.foreach((t,n)=>{C.append(t,n)}),C}[Symbol.for(`nodejs.util.inspect.custom`)](){let t={};for(let n of this.keys()){let S=this.getAll(n);n===`host`?t[n]=S[0]:t[n]=S.length>1?S:S[0]}return t}};Object.defineProperties(wa.prototype,[`get`,`entries`,`forEach`,`values`].reduce((t,n)=>(t[n]={enumerable:!0},t),{}));var Ta=__esmMin(()=>{ot()});Ta();var FetchBaseError=class extends Error{type;constructor(t,n){super(t),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(t,n,S){super(t,n),S&&(this.code=this.errno=S.code,this.erroredSysCall=S.syscall)}};Hn();const Ea=Symbol.toStringTag,isURLSearchParameters=t=>typeof t==`object`&&typeof t.append==`function`&&typeof t.delete==`function`&&typeof t.get==`function`&&typeof t.getAll==`function`&&typeof t.has==`function`&&typeof t.set==`function`&&typeof t.sort==`function`&&t[Ea]===`URLSearchParams`,isBlob=t=>{if(!t||typeof t!=`object`)return!1;let n=t;return typeof n.arrayBuffer==`function`&&typeof n.type==`string`&&typeof n.stream==`function`&&typeof n.constructor==`function`&&/^(Blob|File)$/.test(n[Ea])},isAbortSignal=t=>{if(typeof t!=`object`||!t)return!1;let n=t;return n[Ea]===`AbortSignal`||n[Ea]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let S=new Bn(n).hostname,C=new Bn(t).hostname;return S===C||S.endsWith(`.${C}`)},isSameProtocol=(t,n)=>new Bn(n).protocol===new Bn(t).protocol;var Da,Oa,File,ka=__esmMin(()=>{Da=Symbol(`File.name`),Oa=Symbol(`File.lastModified`),File=class extends Blob{[Da];[Oa];webkitRelativePath=``;constructor(t,n,S){super(t,S),this[Da]=String(n),this[Oa]=S?.lastModified??Date.now()}get name(){return this[Da]}get lastModified(){return this[Oa]}get[Symbol.toStringTag](){return`File`}}});function generateBoundary(){let t=`----formdata-`;for(let n=0;n<24;n++)t+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return t}function escape(t){return t.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`)}function formDataToBlob(t,n){n??=generateBoundary();let S=[],C=`--${n}\r\nContent-Disposition: form-data; name="`;for(let[n,N]of t.entries())if(typeof N==`string`)S.push(`${C}${escape(n)}"\r\n\r\n${N.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
11
+ `,`\r`,` `,`#`,`/`,`:`,`<`,`>`,`?`,`@`,`[`,`\\`,`]`,`^`,`|`]),Bn=class URL{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(t,n){let S=t instanceof URL?t.href:String(t),C;try{if(n!==void 0){let t=n instanceof URL?n.href:String(n);C=lt.Uri.parse(t,Nn).parse_relative(S,Nn)}else C=lt.Uri.parse(S,Nn)}catch{throw TypeError(`Invalid URL: ${S}`)}if(!C)throw TypeError(`Invalid URL: ${S}`);this.#e=C.get_scheme();let N=isSpecialScheme(this.#e);this.#t=C.get_user()??``,this.#n=C.get_password()??``;let F=C.get_host(),I=F===null?null:bracketIPv6Host(F.toLowerCase());this.#r=I===null?N?``:null:this.#e===`file`&&I===`localhost`?``:I;let H=C.get_port();this.#i=H===-1||H===defaultPort(this.#e)?null:H,this.#a=C.get_path()??``,N&&this.#a===``&&(this.#a=`/`),this.#o=this.#r===null&&!this.#a.startsWith(`/`),this.#r===null&&!this.#o&&this.#a.startsWith(`/.//`)&&(this.#a=this.#a.slice(2)),this.#s=C.get_fragment()??null,this.#l=C.get_query()??null,this.#c=new Fn,this.#c._entries=parseFormUrlencoded(this.#l??``),Pn.set(this.#c,()=>{let t=this.#c.toString();this.#l=t===``?null:t})}get protocol(){return this.#e+`:`}set protocol(t){let n=String(t).replace(Rn,``)+`:`;if(!/^[A-Za-z]/.test(n))return;let S=``;for(let t of n){if(t===`:`)break;if(!isSchemeChar(t))return;S+=t.toLowerCase()}isSpecialScheme(this.#e)===isSpecialScheme(S)&&(S===`file`&&(this.#t!==``||this.#n!==``||this.#i!==null)||this.#e===`file`&&(this.#r===null||this.#r===``)||(this.#e=S,this.#i!==null&&this.#i===defaultPort(S)&&(this.#i=null)))}get hostname(){return this.#r??``}set hostname(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!0);n!==void 0&&(this.#r=n.host)}get port(){return this.#i===null?``:String(this.#i)}set port(t){if(this.#u())return;let n=String(t);if(n===``){this.#i=null;return}let S=digitPrefix(n.replace(Rn,``));if(S===``)return;let C=Number(S);C>65535||(this.#i=C===defaultPort(this.#e)?null:C)}get host(){let t=this.hostname,n=this.port;return n?`${t}:${n}`:t}set host(t){if(this.#o)return;let n=parseHostSetterValue(String(t),this.#e,this.#t!==``||this.#n!==``,this.#i!==null,!1);n!==void 0&&(this.#r=n.host,n.port!==void 0&&(this.#i=n.port))}get pathname(){return this.#a}set pathname(t){this.#o||(this.#a=parsePathSetterValue(String(t),isSpecialScheme(this.#e),this.#r===null))}get search(){return this.#l?`?`+this.#l:``}set search(t){let n=String(t);if(n===``){this.#l=null,this.#c._entries=[];return}let S=(n.startsWith(`?`)?n.slice(1):n).replace(Rn,``);this.#l=encodeQuery(S,isSpecialScheme(this.#e)),this.#c._entries=parseFormUrlencoded(S)}get hash(){return this.#s?`#`+this.#s:``}set hash(t){let n=String(t);if(n===``){this.#s=null;return}let S=(n.startsWith(`#`)?n.slice(1):n).replace(Rn,``);this.#s=percentEncode(S,'"<>`')}get origin(){return isSpecialScheme(this.#e)&&this.#e!==`file`?`${this.protocol}//${this.host}`:`null`}get username(){return this.#t}set username(t){this.#u()||(this.#t=percentEncode(String(t),Ln))}get password(){return this.#n}set password(t){this.#u()||(this.#n=percentEncode(String(t),Ln))}#u(){return this.#r===null||this.#r===``||this.#e===`file`}get href(){let t=this.#e+`:`;return this.#r===null?!this.#o&&this.#a.startsWith(`//`)&&(t+=`/.`):(t+=`//`,(this.#t!==``||this.#n!==``)&&(t+=this.#t,this.#n!==``&&(t+=`:`+this.#n),t+=`@`),t+=this.#r,this.#i!==null&&(t+=`:`+this.#i)),t+=this.#a,t+=this.#l===null?``:`?${this.#l}`,t+=this.#s===null?``:`#${this.#s}`,t}set href(t){let n=new URL(String(t));this.#e=n.#e,this.#t=n.#t,this.#n=n.#n,this.#r=n.#r,this.#i=n.#i,this.#a=n.#a,this.#o=n.#o,this.#l=n.#l,this.#s=n.#s,this.#c._entries=parseFormUrlencoded(this.#l??``)}get searchParams(){return this.#c}toString(){return this.href}toJSON(){return this.href}static _objectURLPaths=new Map;static _objectURLCounter=0;static createObjectURL(t){let n=t?._tmpPath;if(typeof n==`string`&&n.length>0){let t=`file://${n}`;return URL._objectURLPaths.set(t,n),t}return`file:///dev/null`}static revokeObjectURL(t){let n=URL._objectURLPaths.get(t);n&&(lt.unlink(n),URL._objectURLPaths.delete(t))}},__name$1(parse$3,`parse`),__name$1(format$1,`format`),__name$1(resolve$2,`resolve`),Vn={URL:Bn,URLSearchParams:Fn,parse:parse$3,format:format$1,resolve:resolve$2,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});Hn(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:Bn,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:Fn,enumerable:!1,writable:!0,configurable:!0});var Un=__exportAll$5({PerformanceEntry:()=>qn,PerformanceMark:()=>Yn,PerformanceMeasure:()=>Xn,PerformanceObserver:()=>Kn,PerformanceObserverEntryList:()=>Jn,default:()=>Zn,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>Wn,timerify:()=>timerify});function eventLoopUtilization(t,n){return{idle:0,active:0,utilization:0}}function timerify(t){let wrapped=function(...n){let S=Wn.now(),C=t.apply(this,n);return Wn.now()-S,C};return Object.defineProperty(wrapped,"name",{value:t.name}),wrapped}function monitorEventLoopDelay(t){let n=new Map;return{enable(){},disable(){},reset(){},percentile(t){return 0},get min(){return 0},get max(){return 0},get mean(){return 0},get stddev(){return 0},get percentiles(){return n}}}var Wn,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn=__esmMin(()=>{if(globalThis.performance)Wn=globalThis.performance;else{let t,_now;try{let n=globalThis.imports?.gi?.GLib;if(!n)throw Error(`GJS imports.gi.GLib not available`);t=n.get_monotonic_time(),_now=()=>(n.get_monotonic_time()-t)/1e3}catch{let n=Date.now();t=0,_now=()=>Date.now()-n}let n=[],S=Date.now()-_now();Wn={timeOrigin:S,now:_now,mark(t){let S={name:t,entryType:`mark`,startTime:_now(),duration:0};return n.push(S),S},measure(t,S,C){let N=0,F=_now();if(S){let t=n.find(t=>t.entryType===`mark`&&t.name===S);t&&(N=t.startTime)}if(C){let t=n.find(t=>t.entryType===`mark`&&t.name===C);t&&(F=t.startTime)}let I={name:t,entryType:`measure`,startTime:N,duration:F-N};return n.push(I),I},getEntries(){return[...n]},getEntriesByName(t){return n.filter(n=>n.name===t)},getEntriesByType(t){return n.filter(n=>n.entryType===t)},clearMarks(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`mark`&&(!t||n[S].name===t)&&n.splice(S,1)},clearMeasures(t){for(let S=n.length-1;S>=0;S--)n[S].entryType===`measure`&&(!t||n[S].name===t)&&n.splice(S,1)},clearResourceTimings(){},setResourceTimingBufferSize(){},toJSON(){return{timeOrigin:S}}}}PerformanceObserverStub=class{_callback;constructor(t){this._callback=t}observe(t){}disconnect(){}takeRecords(){return[]}},PerformanceEntryStub=class{name=``;entryType=``;startTime=0;duration=0;toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration}}},PerformanceObserverEntryListStub=class{getEntries(){return[]}getEntriesByName(t){return[]}getEntriesByType(t){return[]}},Gn=globalThis,Kn=Gn.PerformanceObserver||PerformanceObserverStub,qn=Gn.PerformanceEntry||PerformanceEntryStub,Jn=Gn.PerformanceObserverEntryList||PerformanceObserverEntryListStub,Yn=Gn.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},Xn=Gn.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Zn={performance:Wn,PerformanceObserver:Kn,PerformanceEntry:qn,PerformanceObserverEntryList:Jn,PerformanceMark:Yn,PerformanceMeasure:Xn,eventLoopUtilization,timerify,monitorEventLoopDelay}});Qn();const $n=globalThis;globalThis.performance===void 0&&($n.performance=Wn),typeof $n.PerformanceObserver!=`function`&&($n.PerformanceObserver=Kn);const er={IndexSizeError:1,HierarchyRequestError:3,WrongDocumentError:4,InvalidCharacterError:5,NoModificationAllowedError:7,NotFoundError:8,NotSupportedError:9,InUseAttributeError:10,InvalidStateError:11,SyntaxError:12,InvalidModificationError:13,NamespaceError:14,InvalidAccessError:15,TypeMismatchError:17,SecurityError:18,NetworkError:19,AbortError:20,URLMismatchError:21,QuotaExceededError:22,TimeoutError:23,InvalidNodeTypeError:24,DataCloneError:25};var _DOMExceptionPolyfill=class extends Error{code;constructor(t,n){super(t),this.name=n||`Error`,this.code=Object.hasOwn(er,this.name)?er[this.name]:0}};const tr=globalThis.DOMException??_DOMExceptionPolyfill;_e();const nr=Symbol(`type`),rr=Symbol(`bubbles`),ir=Symbol(`cancelable`),ar=Symbol(`composed`),sr=Symbol(`target`),cr=Symbol(`currentTarget`),lr=Symbol(`eventPhase`),ur=Symbol(`defaultPrevented`),dr=Symbol(`isTrusted`),fr=Symbol(`timeStamp`),pr=Symbol(`stop`),mr=Symbol(`immediateStop`),hr=Symbol(`dispatching`),gr=Symbol(`inPassiveListener`);var Event=class{[nr];[rr];[ir];[ar];[sr]=null;[cr]=null;[lr]=0;[ur]=!1;[dr]=!1;[fr];[pr]=!1;[mr]=!1;[hr]=!1;[gr]=!1;get type(){return this[nr]}get bubbles(){return this[rr]}get cancelable(){return this[ir]}get composed(){return this[ar]}get target(){return this[sr]}get currentTarget(){return this[cr]}get eventPhase(){return this[lr]}get defaultPrevented(){return this[ur]}get timeStamp(){return this[fr]}get cancelBubble(){return this[pr]}set cancelBubble(t){t&&this.stopPropagation()}get returnValue(){return!this[ur]}set returnValue(t){t||this.preventDefault()}get srcElement(){return this[sr]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(t,n){this[nr]=t,this[rr]=n?.bubbles??!1,this[ir]=n?.cancelable??!1,this[ar]=n?.composed??!1,this[fr]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[dr],enumerable:!0,configurable:!1})}composedPath(){return this[cr]?[this[cr]]:[]}preventDefault(){this[ir]&&!this[gr]&&(this[ur]=!0)}stopPropagation(){this[pr]=!0}stopImmediatePropagation(){this[pr]=!0,this[mr]=!0}},EventTarget=class{#e=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=typeof S==`object`?S?.once??!1:!1,F=typeof S==`object`?S?.passive??!1:!1,I=this.#e.get(t);I||(I=[],this.#e.set(t,I));for(let t of I)if(t.listener===n&&t.capture===C)return;let H={listener:n,capture:C,once:N,passive:F,removed:!1};I.push(H),typeof S==`object`&&S?.signal&&S.signal.addEventListener(`abort`,()=>{this.removeEventListener(t,n,{capture:C})},{once:!0})}removeEventListener(t,n,S){if(n===null)return;let C=typeof S==`boolean`?S:S?.capture??!1,N=this.#e.get(t);if(!N)return;let F=N.findIndex(t=>t.listener===n&&t.capture===C);F!==-1&&(N[F].removed=!0,N.splice(F,1),N.length===0&&this.#e.delete(t))}dispatchEvent(t){let n=t;if(n[hr])throw new tr(`The event is already being dispatched.`,`InvalidStateError`);n[hr]=!0,n[sr]=this,n[cr]=this,n[lr]=Event.AT_TARGET;try{let S=this.#e.get(t.type);if(S){let C=[...S];for(let S of C)if(!S.removed){if(n[mr]||n[pr])break;S.once&&this.removeEventListener(t.type,S.listener,{capture:S.capture});try{S.passive&&(n[gr]=!0),typeof S.listener==`function`?S.listener.call(this,t):typeof S.listener.handleEvent==`function`&&S.listener.handleEvent.call(S.listener,t)}catch(t){reportListenerException(t)}finally{n[gr]=!1}}}}finally{n[lr]=Event.NONE,n[cr]=null,n[hr]=!1}return!t.defaultPrevented}};function reportListenerException(t){try{let n=globalThis;if(typeof n.reportError==`function`)n.reportError(t);else if(t instanceof Error){let n=`${t.name}: ${t.message}`;ge.error(t.stack?`${n}\n${t.stack}`:n)}else ge.error(String(t))}catch{}}for(let[t,n]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,t,{value:n,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,t,{value:n,writable:!1,enumerable:!0,configurable:!1});const _r=Symbol(`abort`),vr=Symbol(`internal`);var yr=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(t){if(super(),t!==vr)throw TypeError(`Illegal constructor.`)}get aborted(){if(!(this instanceof AbortSignal))throw TypeError(`'get aborted' called on an object that is not a valid instance of AbortSignal.`);return this.#e}get reason(){return this.#t}get[Symbol.toStringTag](){return`AbortSignal`}throwIfAborted(){if(this.#e)throw this.#t}[_r](t){if(this.#e)return;this.#e=!0,this.#t=t??new tr(`The operation was aborted.`,`AbortError`);let n=new Event(`abort`);typeof this.onabort==`function`&&this.onabort.call(this,n),this.dispatchEvent(n)}static abort(t){let n=new AbortSignal(vr);return n[_r](t),n}static timeout(t){let n=new AbortSignal(vr);return setTimeout(()=>{n[_r](new tr(`The operation timed out.`,`TimeoutError`))},t),n}static any(t){let n=new AbortSignal(vr);for(let S of t)if(S.aborted)return n[_r](S.reason),n;let onAbort=()=>{if(!n.aborted){let S=t.find(t=>t.aborted);n[_r](S?.reason)}};for(let n of t)n.addEventListener(`abort`,onAbort,{once:!0});return n}},br=class AbortController{signal;constructor(){this.signal=new yr(vr)}get[Symbol.toStringTag](){return`AbortController`}abort(t){if(!(this instanceof AbortController))throw TypeError(`'abort' called on an object that is not a valid instance of AbortController.`);this.signal[_r](t)}};const Sr=globalThis;globalThis.AbortController===void 0&&(Sr.AbortController=br),globalThis.AbortSignal===void 0&&(Sr.AbortSignal=yr);const Cr=Symbol(`kState`),wr=Symbol(`kType`);function isBrandCheck(t){return n=>typeof n==`object`&&!!n&&n[Cr]!==void 0&&n[wr]===t}function dequeueValue(t){let n=t[Cr].queue.shift();if(n===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:S,size:C}=n;return t[Cr].queueTotalSize=Math.max(0,t[Cr].queueTotalSize-C),S}function resetQueue(t){t[Cr].queue=[],t[Cr].queueTotalSize=0}function peekQueueValue(t){return t[Cr].queue[0].value}function enqueueValueWithSize(t,n,S){if(S=+S,typeof S!=`number`||S<0||Number.isNaN(S)||S===1/0)throw RangeError(`Invalid size: ${S}`);t[Cr].queue.push({value:n,size:S}),t[Cr].queueTotalSize+=S}function extractHighWaterMark(t,n){if(t===void 0)return n;if(t=+t,typeof t!=`number`||Number.isNaN(t)||t<0)throw RangeError(`Invalid highWaterMark: ${t}`);return t}function extractSizeAlgorithm(t){if(t===void 0)return()=>1;if(typeof t!=`function`)throw TypeError(`strategy.size must be a function`);return t}function transferArrayBuffer(t){return typeof ArrayBuffer.prototype.transfer==`function`?t.transfer():t.slice(0)}function isDetachedBuffer(t){if(typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||t.byteLength!==0)return!1;try{return t.slice(0,0),!1}catch{return!0}}function typedArrayConstructorByTag(t){switch(t){case`Int8Array`:return Int8Array;case`Uint8Array`:return Uint8Array;case`Uint8ClampedArray`:return Uint8ClampedArray;case`Int16Array`:return Int16Array;case`Uint16Array`:return Uint16Array;case`Int32Array`:return Int32Array;case`Uint32Array`:return Uint32Array;case`Float32Array`:return Float32Array;case`Float64Array`:return Float64Array;case`BigInt64Array`:return typeof BigInt64Array<`u`?BigInt64Array:void 0;case`BigUint64Array`:return typeof BigUint64Array<`u`?BigUint64Array:void 0;default:return}}function elementSizeByTag(t){switch(t){case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:return 1;case`Int16Array`:case`Uint16Array`:return 2;case`Int32Array`:case`Uint32Array`:case`Float32Array`:return 4;case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:return 8;default:return 1}}function setPromiseHandled(t){t.then(()=>{},()=>{})}function createPromiseCallback(t,n,S){if(typeof n!=`function`)throw TypeError(`${t} must be a function`);return async(...t)=>n.call(S,...t)}async function nonOpFlush(){}function nonOpStart(){}async function nonOpPull(){}async function nonOpCancel(){}async function nonOpWrite(){}const Tr={__proto__:Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),next:void 0,return:void 0};function createAsyncFromSyncIterator(t){let n={[Symbol.iterator]:()=>t.iterator},S=(async function*(){return yield*n})();return{iterator:S,nextMethod:S.next,done:!1}}function getIterator(t,n=`sync`,S){if(S===void 0)if(n===`async`){if(S=t[Symbol.asyncIterator],S==null){let n=t[Symbol.iterator];if(n===void 0)throw TypeError(`Object is not iterable`);return createAsyncFromSyncIterator(getIterator(t,`sync`,n))}}else S=t[Symbol.iterator];if(S===void 0)throw TypeError(`Object is not iterable`);let C=S.call(t);if(typeof C!=`object`||!C)throw TypeError(`The iterator method must return an object`);return{iterator:C,nextMethod:C.next,done:!1}}function iteratorNext(t,n){let S;if(S=n===void 0?t.nextMethod.call(t.iterator):t.nextMethod.call(t.iterator,n),typeof S!=`object`||!S)throw TypeError(`The iterator.next() method must return an object`);return S}const Er=typeof globalThis.AbortController==`function`?globalThis.AbortController:class AbortControllerShim{signal={aborted:!1,reason:void 0,addEventListener(){},removeEventListener(){}};abort(t){this.signal.aborted=!0,this.signal.reason=t}},Dr=Symbol(`kAbort`),Or=Symbol(`kCloseSentinel`),kr=Symbol(`kError`),Ar=Symbol(`kSkipThrow`);var WritableStream=class{[wr]=`WritableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`sink must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);let S=t?.type;if(S!==void 0)throw RangeError(`Invalid type: ${S}`);this[Cr]=createWritableStreamState();let C=extractSizeAlgorithm(n?.size),N=extractHighWaterMark(n?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,t,N,C)}get locked(){if(!jr(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(t){return jr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){return jr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamCloseQueuedOrInFlight(this)?Promise.reject(TypeError(`Failure closing WritableStream`)):writableStreamClose(this):Promise.reject(TypeError(`Invalid this`))}getWriter(){if(!jr(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[wr]=`WritableStreamDefaultWriter`;[Cr];constructor(t){if(!jr(t))throw TypeError(`Expected a WritableStream`);this[Cr]={stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0},ready:{promise:void 0,resolve:void 0,reject:void 0}},setupWritableStreamDefaultWriter(this,t)}get closed(){return Mr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!Mr(this))throw TypeError(`Invalid this`);if(this[Cr].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return Mr(this)?this[Cr].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){if(!Mr(this))return Promise.reject(TypeError(`Invalid this`));let{stream:t}=this[Cr];return t===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamCloseQueuedOrInFlight(t)?Promise.reject(TypeError(`Failure to close WritableStream`)):writableStreamDefaultWriterClose(this)}releaseLock(){if(!Mr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr];t!==void 0&&writableStreamDefaultWriterRelease(this)}write(t){return Mr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterWrite(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`WritableStreamDefaultWriter`}},WritableStreamDefaultController=class{[wr]=`WritableStreamDefaultController`;[Cr];constructor(t){if(t!==Ar)throw TypeError(`Illegal constructor`)}[Dr](t){let n=this[Cr].abortAlgorithm(t);return writableStreamDefaultControllerClearAlgorithms(this),n}[kr](){resetQueue(this)}get signal(){if(!Nr(this))throw TypeError(`Invalid this`);return this[Cr].abortController.signal}error(t){if(!Nr(this))throw TypeError(`Invalid this`);this[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(this,t)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const jr=isBrandCheck(`WritableStream`),Mr=isBrandCheck(`WritableStreamDefaultWriter`),Nr=isBrandCheck(`WritableStreamDefaultController`);function createEmptyPromiseRecord(){return{promise:void 0,resolve:void 0,reject:void 0}}function createWritableStreamState(){return{close:Promise.withResolvers(),closeRequest:createEmptyPromiseRecord(),inFlightWriteRequest:createEmptyPromiseRecord(),inFlightCloseRequest:createEmptyPromiseRecord(),pendingAbortRequest:{abort:createEmptyPromiseRecord(),reason:void 0,wasAlreadyErroring:!1},backpressure:!1,controller:void 0,state:`writable`,storedError:void 0,writeRequests:[],writer:void 0}}function isWritableStreamLocked(t){return t[Cr].writer!==void 0}function setupWritableStreamDefaultWriter(t,n){if(isWritableStreamLocked(n))throw TypeError(`WritableStream is locked`);switch(t[Cr].stream=n,n[Cr].writer=t,n[Cr].state){case`writable`:!writableStreamCloseQueuedOrInFlight(n)&&n[Cr].backpressure?t[Cr].ready=Promise.withResolvers():t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close=Promise.withResolvers();break;case`erroring`:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:t[Cr].ready={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise),setPromiseHandled(t[Cr].close.promise)}}function writableStreamAbort(t,n){let{state:S,controller:C}=t[Cr];if(S===`closed`||S===`errored`)return Promise.resolve();if(C[Cr].abortController.abort(n),t[Cr].pendingAbortRequest.abort.promise!==void 0)return t[Cr].pendingAbortRequest.abort.promise;let N=!1;S===`erroring`&&(N=!0,n=void 0);let F=Promise.withResolvers();return t[Cr].pendingAbortRequest={abort:F,reason:n,wasAlreadyErroring:N},N||writableStreamStartErroring(t,n),F.promise}function writableStreamClose(t){let{state:n,writer:S,backpressure:C,controller:N}=t[Cr];if(n===`closed`||n===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));t[Cr].closeRequest=Promise.withResolvers();let{promise:F}=t[Cr].closeRequest;return S!==void 0&&C&&n===`writable`&&S[Cr].ready.resolve?.(),writableStreamDefaultControllerClose(N),F}function writableStreamUpdateBackpressure(t,n){let{writer:S}=t[Cr];S!==void 0&&t[Cr].backpressure!==n&&(n?S[Cr].ready=Promise.withResolvers():S[Cr].ready.resolve?.()),t[Cr].backpressure=n}function writableStreamStartErroring(t,n){let{controller:S,writer:C}=t[Cr];t[Cr].state=`erroring`,t[Cr].storedError=n,C!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(C,n),!writableStreamHasOperationMarkedInFlight(t)&&S[Cr].started&&writableStreamFinishErroring(t)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(t){t[Cr].closeRequest.promise!==void 0&&(t[Cr].closeRequest.reject?.(t[Cr].storedError),t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(t[Cr].close.promise),t[Cr].close.reject?.(t[Cr].storedError);let{writer:n}=t[Cr];n!==void 0&&(setPromiseHandled(n[Cr].close.promise),n[Cr].close.reject?.(t[Cr].storedError))}function writableStreamMarkFirstWriteRequestInFlight(t){let n=t[Cr].writeRequests.shift();t[Cr].inFlightWriteRequest=n}function writableStreamMarkCloseRequestInFlight(t){t[Cr].inFlightCloseRequest=t[Cr].closeRequest,t[Cr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(t){return t[Cr].inFlightWriteRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(t,n){t[Cr].inFlightWriteRequest.reject?.(n),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightWrite(t){t[Cr].inFlightWriteRequest.resolve?.(),t[Cr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(t,n){t[Cr].inFlightCloseRequest.reject?.(n),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.reject?.(n),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightClose(t){t[Cr].inFlightCloseRequest.resolve?.(),t[Cr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Cr].state===`erroring`&&(t[Cr].storedError=void 0,t[Cr].pendingAbortRequest.abort.promise!==void 0&&(t[Cr].pendingAbortRequest.abort.resolve?.(),t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),t[Cr].state=`closed`,t[Cr].writer!==void 0&&t[Cr].writer[Cr].close.resolve?.(),t[Cr].close.resolve?.()}function writableStreamFinishErroring(t){t[Cr].state=`errored`,t[Cr].controller[kr]();let n=t[Cr].storedError;for(let S of t[Cr].writeRequests)S.reject?.(n);if(t[Cr].writeRequests=[],t[Cr].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}let S=t[Cr].pendingAbortRequest;if(t[Cr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1},S.wasAlreadyErroring){S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}t[Cr].controller[Dr](S.reason).then(()=>{S.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)},n=>{S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)})}function writableStreamDealWithRejection(t,n){if(t[Cr].state===`writable`){writableStreamStartErroring(t,n);return}writableStreamFinishErroring(t)}function writableStreamCloseQueuedOrInFlight(t){return t[Cr].closeRequest.promise!==void 0||t[Cr].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(t){let{promise:n,resolve:S,reject:C}=Promise.withResolvers();return t[Cr].writeRequests.push({promise:n,resolve:S,reject:C}),n}function writableStreamDefaultWriterWrite(t,n){let{stream:S}=t[Cr],{controller:C}=S[Cr],N=writableStreamDefaultControllerGetChunkSize(C,n);if(S!==t[Cr].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:F}=S[Cr];if(F===`errored`)return Promise.reject(S[Cr].storedError);if(writableStreamCloseQueuedOrInFlight(S)||F===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(F===`erroring`)return Promise.reject(S[Cr].storedError);let I=writableStreamAddWriteRequest(S);return writableStreamDefaultControllerWrite(C,n,N),I}function writableStreamDefaultWriterRelease(t){let{stream:n}=t[Cr],S=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(t,S),writableStreamDefaultWriterEnsureClosedPromiseRejected(t,S),n[Cr].writer=void 0,t[Cr].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(t){let{stream:n}=t[Cr];switch(n[Cr].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(n[Cr].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(t,n){t[Cr].ready.reject?(t[Cr].ready.reject(n),t[Cr].ready.resolve=void 0,t[Cr].ready.reject=void 0):t[Cr].ready={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(t,n){t[Cr].close.reject?(t[Cr].close.reject(n),t[Cr].close.resolve=void 0,t[Cr].close.reject=void 0):t[Cr].close={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(t){let{stream:n}=t[Cr],{state:S}=n[Cr];return writableStreamCloseQueuedOrInFlight(n)||S===`closed`?Promise.resolve():S===`errored`?Promise.reject(n[Cr].storedError):writableStreamDefaultWriterClose(t)}function writableStreamDefaultWriterClose(t){return writableStreamClose(t[Cr].stream)}function writableStreamDefaultWriterAbort(t,n){return writableStreamAbort(t[Cr].stream,n)}function writableStreamDefaultControllerWrite(t,n,S){try{enqueueValueWithSize(t,n,S)}catch(n){writableStreamDefaultControllerErrorIfNeeded(t,n);return}let{stream:C}=t[Cr];!writableStreamCloseQueuedOrInFlight(C)&&C[Cr].state===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerProcessWrite(t,n){let{stream:S,writeAlgorithm:C}=t[Cr];writableStreamMarkFirstWriteRequestInFlight(S),C(n,t).then(()=>{writableStreamFinishInFlightWrite(S);let{state:n}=S[Cr];dequeueValue(t),!writableStreamCloseQueuedOrInFlight(S)&&n===`writable`&&writableStreamUpdateBackpressure(S,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)},n=>{S[Cr].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(t),writableStreamFinishInFlightWriteWithError(S,n)})}function writableStreamDefaultControllerProcessClose(t){let{closeAlgorithm:n,stream:S}=t[Cr];writableStreamMarkCloseRequestInFlight(S),dequeueValue(t);let C=n();writableStreamDefaultControllerClearAlgorithms(t),C.then(()=>writableStreamFinishInFlightClose(S),t=>writableStreamFinishInFlightCloseWithError(S,t))}function writableStreamDefaultControllerGetDesiredSize(t){return t[Cr].highWaterMark-t[Cr].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(t,n){let{sizeAlgorithm:S}=t[Cr];if(S===void 0)return 1;try{return S(n)}catch(n){return writableStreamDefaultControllerErrorIfNeeded(t,n),1}}function writableStreamDefaultControllerErrorIfNeeded(t,n){t[Cr].stream[Cr].state===`writable`&&writableStreamDefaultControllerError(t,n)}function writableStreamDefaultControllerError(t,n){writableStreamDefaultControllerClearAlgorithms(t),writableStreamStartErroring(t[Cr].stream,n)}function writableStreamDefaultControllerClose(t){enqueueValueWithSize(t,Or,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerClearAlgorithms(t){t[Cr].writeAlgorithm=void 0,t[Cr].closeAlgorithm=void 0,t[Cr].abortAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(t){return writableStreamDefaultControllerGetDesiredSize(t)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(t){let{queue:n,started:S,stream:C}=t[Cr];if(!S||C[Cr].inFlightWriteRequest.promise!==void 0)return;if(C[Cr].state===`erroring`){writableStreamFinishErroring(C);return}if(!n.length)return;let N=peekQueueValue(t);N===Or?writableStreamDefaultControllerProcessClose(t):writableStreamDefaultControllerProcessWrite(t,N)}function setupWritableStreamDefaultControllerFromSink(t,n,S,C){let N=new WritableStreamDefaultController(Ar),F=n?.start,I=n?.write,H=n?.close,W=n?.abort;setupWritableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`sink.write`,I,n):nonOpWrite,H?createPromiseCallback(`sink.close`,H,n):nonOpCancel,W?createPromiseCallback(`sink.abort`,W,n):nonOpCancel,S,C)}function setupWritableStreamDefaultController(t,n,S,C,N,F,I,H){n[Cr]={abortAlgorithm:F,closeAlgorithm:N,highWaterMark:I,queue:[],queueTotalSize:0,abortController:new Er,sizeAlgorithm:H,started:!1,stream:t,writeAlgorithm:C},t[Cr].controller=n,writableStreamUpdateBackpressure(t,writableStreamDefaultControllerGetBackpressure(n));let W=S();new Promise(t=>t(W)).then(()=>{n[Cr].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{n[Cr].started=!0,writableStreamDealWithRejection(t,S)})}function createWritableStream(t,n,S,C,N=1,F=()=>1){let I=Object.create(WritableStream.prototype);return I[wr]=`WritableStream`,I[Cr]=createWritableStreamState(),setupWritableStreamDefaultController(I,new WritableStreamDefaultController(Ar),t,n,S,C,N,F),I}ze();const Pr=Symbol(`kCancel`),Fr=Symbol(`kClose`),Ir=Symbol(`kChunk`),Lr=Symbol(`kError`),Rr=Symbol(`kPull`),zr=Symbol(`kRelease`),Br=Symbol(`kSkipThrow`);let Vr,Hr;function lazyReadableReleasedError(){return Vr||(Vr=TypeError(`Reader released`),Vr)}function lazyReadableReleasingError(){return Hr||(Hr=TypeError(`Releasing reader`),Hr)}function createAbortError$1(){if(typeof globalThis.DOMException==`function`)return new DOMException(`The operation was aborted`,`AbortError`);let t=Error(`The operation was aborted`);return t.name=`AbortError`,t}__name$1(createAbortError$1,`createAbortError`);function createReadableStreamState(){return{disturbed:!1,reader:void 0,state:`readable`,storedError:void 0,controller:void 0,closedPromise:Promise.withResolvers()}}var ReadableStream$1=class{static{__name$1(this,`ReadableStream`)}[wr]=`ReadableStream`;[Cr];constructor(t={},n={}){if(t!=null&&typeof t!=`object`)throw TypeError(`source must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`strategy must be an object`);this[Cr]=createReadableStreamState();let S=n?.size,C=n?.highWaterMark,N=t?.type;if(N!==void 0){if(`${N}`==`bytes`){if(S!==void 0)throw RangeError(`strategy.size must not be set for a byte stream`);setupReadableByteStreamControllerFromSource(this,t,extractHighWaterMark(C,0));return}throw RangeError(`Invalid type: ${N}`)}setupReadableStreamDefaultControllerFromSource(this,t,extractHighWaterMark(C,1),extractSizeAlgorithm(S))}get locked(){if(!Ur(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(t){return readableStreamFromIterable(t)}cancel(t=void 0){return Ur(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,t):Promise.reject(TypeError(`Invalid this`))}getReader(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=t?.mode;if(n===void 0)return new ReadableStreamDefaultReader(this);if(`${n}`==`byob`)return new ReadableStreamBYOBReader(this);throw RangeError(`Invalid mode: ${n}`)}pipeThrough(t,n={}){if(!Ur(this))throw TypeError(`Invalid this`);let S=t?.readable;if(!Ur(S))throw TypeError(`transform.readable must be a ReadableStream`);let C=t?.writable;if(!jr(C))throw TypeError(`transform.writable must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let N=n?.preventAbort,F=n?.preventCancel,I=n?.preventClose,H=n?.signal;if(H!==void 0&&!(H instanceof Object&&`aborted`in H))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(C))throw TypeError(`The WritableStream is locked`);return setPromiseHandled(readableStreamPipeTo(this,C,!!I,!!N,!!F,H)),S}pipeTo(t,n={}){try{if(!Ur(this))throw TypeError(`Invalid this`);if(!jr(t))throw TypeError(`destination must be a WritableStream`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=n?.preventAbort,C=n?.preventCancel,N=n?.preventClose,F=n?.signal;if(F!==void 0&&!(F instanceof Object&&`aborted`in F))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(t))throw TypeError(`The WritableStream is locked`);return readableStreamPipeTo(this,t,!!N,!!S,!!C,F)}catch(t){return Promise.reject(t)}}tee(){if(!Ur(this))throw TypeError(`Invalid this`);let t=this[Cr].controller;return Kr(t)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(t={}){if(!Ur(this))throw TypeError(`Invalid this`);if(t!=null&&typeof t!=`object`)throw TypeError(`options must be an object`);let n=!!t?.preventCancel,S=new ReadableStreamDefaultReader(this),C={done:!1,current:void 0},N=!1;function nextSteps(){if(C.done)return Promise.resolve({done:!0,value:void 0});if(S[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not bound to a ReadableStream`));let{promise:t,resolve:n,reject:N}=Promise.withResolvers();return readableStreamDefaultReaderRead(S,{[Ir](t){C.current=void 0,n({value:t,done:!1})},[Fr](){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),n({done:!0,value:void 0})},[Lr](t){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),N(t)}}),t}async function returnSteps(t){if(C.done)return{done:!0,value:t};if(C.done=!0,S[Cr].stream===void 0)throw TypeError(`The reader is not bound to a ReadableStream`);if(!n){let n=readableStreamReaderGenericCancel(S,t);return readableStreamReaderGenericRelease(S),await n,{done:!0,value:t}}return readableStreamReaderGenericRelease(S),{done:!0,value:t}}return Object.setPrototypeOf({next(){return N||=(C.current=Promise.resolve(),!0),C.current=C.current===void 0?nextSteps():C.current.then(nextSteps,nextSteps),C.current},return(t){return N=!0,C.current=C.current===void 0?returnSteps(t):C.current.then(()=>returnSteps(t),()=>returnSteps(t)),C.current},[Symbol.asyncIterator](){return this}},Tr)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](){this[Cr].resolve?.({value:void 0,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamDefaultReader=class{[wr]=`ReadableStreamDefaultReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,t)}read(){if(!Gr(this))return Promise.reject(TypeError(`Invalid this`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let t=this[Cr].stream,n=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(n)&&n[Cr].queue.length>0){t[Cr].disturbed=!0;let S=dequeueValue(n);return n[Cr].closeRequested&&!n[Cr].queue.length?(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(t)):readableStreamDefaultControllerCallPullIfNeeded(n),Promise.resolve({value:S,done:!1})}let S=new DefaultReadRequest;return readableStreamDefaultReaderRead(this,S),S.promise}releaseLock(){if(!Gr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return Gr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return Gr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`The reader is not attached to a stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamDefaultReader`}},ReadableStreamDefaultController=class{[wr]=`ReadableStreamDefaultController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get desiredSize(){return readableStreamDefaultControllerGetDesiredSize(this)}close(){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerClose(this)}enqueue(t=void 0){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerEnqueue(this,t)}error(t=void 0){readableStreamDefaultControllerError(this,t)}[Pr](t){return readableStreamDefaultControllerCancelSteps(this,t)}[Rr](t){readableStreamDefaultControllerPullSteps(this,t)}[zr](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const Ur=isBrandCheck(`ReadableStream`),Wr=isBrandCheck(`ReadableStreamDefaultController`),Gr=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(t){return t[Cr].reader!==void 0}function readableStreamCancel(t,n){switch(t[Cr].disturbed=!0,t[Cr].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(t[Cr].storedError)}readableStreamClose(t);let S=t[Cr].reader;if(S!==void 0&&readableStreamHasBYOBReader(t)){let t=S[Cr].readIntoRequests;S[Cr].readIntoRequests=[];for(let n=0;n<t.length;n++)t[n][Fr](void 0)}return t[Cr].controller[Pr](n).then(()=>{})}function readableStreamClose(t){t[Cr].state=`closed`,t[Cr].closedPromise.resolve();let{reader:n}=t[Cr];if(n!==void 0&&(n[Cr].close.resolve?.(),readableStreamHasDefaultReader(t))){for(let t=0;t<n[Cr].readRequests.length;t++)n[Cr].readRequests[t][Fr]();n[Cr].readRequests=[]}}function readableStreamError(t,n){t[Cr].state=`errored`,t[Cr].storedError=n,setPromiseHandled(t[Cr].closedPromise.promise),t[Cr].closedPromise.reject(n);let{reader:S}=t[Cr];if(S!==void 0){if(setPromiseHandled(S[Cr].close.promise),S[Cr].close.reject?.(n),readableStreamHasDefaultReader(t)){for(let t=0;t<S[Cr].readRequests.length;t++)S[Cr].readRequests[t][Lr](n);S[Cr].readRequests=[]}else if(readableStreamHasBYOBReader(t)){for(let t=0;t<S[Cr].readIntoRequests.length;t++)S[Cr].readIntoRequests[t][Lr](n);S[Cr].readIntoRequests=[]}}}function readableStreamHasDefaultReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(t){return t[Cr].reader[Cr].readRequests.length}function readableStreamFulfillReadRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readRequests.shift();S?N[Fr]():N[Ir](n)}function readableStreamAddReadRequest(t,n){t[Cr].reader[Cr].readRequests.push(n)}function readableStreamReaderGenericCancel(t,n){let{stream:S}=t[Cr];return readableStreamCancel(S,n)}function readableStreamReaderGenericInitialize(t,n){switch(t[Cr].stream=n,n[Cr].reader=t,n[Cr].state){case`readable`:t[Cr].close=Promise.withResolvers();break;case`closed`:t[Cr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:t[Cr].close={promise:Promise.reject(n[Cr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise);break}}function readableStreamReaderGenericRelease(t){let{stream:n}=t[Cr],S=lazyReadableReleasedError();n[Cr].state===`readable`?t[Cr].close.reject?.(S):t[Cr].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(t[Cr].close.promise),n[Cr].controller[zr](),n[Cr].reader=void 0,t[Cr].stream=void 0}function readableStreamDefaultReaderRelease(t){readableStreamReaderGenericRelease(t),readableStreamDefaultReaderErrorReadRequests(t,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(t,n){for(let S=0;S<t[Cr].readRequests.length;++S)t[Cr].readRequests[S][Lr](n);t[Cr].readRequests=[]}function readableStreamDefaultReaderRead(t,n){let{stream:S}=t[Cr];switch(S[Cr].disturbed=!0,S[Cr].state){case`closed`:n[Fr]();break;case`errored`:n[Lr](S[Cr].storedError);break;case`readable`:S[Cr].controller[Rr](n);break}}function setupReadableStreamDefaultReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(t,n),t[Cr].readRequests=[]}function readableStreamDefaultControllerClose(t){readableStreamDefaultControllerCanCloseOrEnqueue(t)&&(t[Cr].closeRequested=!0,t[Cr].queue.length||(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)))}function readableStreamDefaultControllerEnqueue(t,n){if(!readableStreamDefaultControllerCanCloseOrEnqueue(t))return;let{stream:S}=t[Cr];if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))readableStreamFulfillReadRequest(S,n,!1);else try{enqueueValueWithSize(t,n,t[Cr].sizeAlgorithm(n))}catch(n){throw readableStreamDefaultControllerError(t,n),n}readableStreamDefaultControllerCallPullIfNeeded(t)}function readableStreamDefaultControllerCanCloseOrEnqueue(t){let{stream:n}=t[Cr];return!t[Cr].closeRequested&&n[Cr].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(t){let{stream:n,highWaterMark:S,queueTotalSize:C}=t[Cr];switch(n[Cr].state){case`errored`:return null;case`closed`:return 0;default:return S-C}}function readableStreamDefaultControllerHasBackpressure(t){return!readableStreamDefaultControllerShouldCallPull(t)}function readableStreamDefaultControllerShouldCallPull(t){let{stream:n}=t[Cr];if(!readableStreamDefaultControllerCanCloseOrEnqueue(t)||!t[Cr].started)return!1;if(isReadableStreamLocked(n)&&readableStreamGetNumReadRequests(n))return!0;let S=readableStreamDefaultControllerGetDesiredSize(t);return S!==null&&S>0}function readableStreamDefaultControllerCallPullIfNeeded(t){if(readableStreamDefaultControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(t))},n=>readableStreamDefaultControllerError(t,n))}}function readableStreamDefaultControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0,t[Cr].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(resetQueue(t),readableStreamDefaultControllerClearAlgorithms(t),readableStreamError(S,n))}function readableStreamDefaultControllerCancelSteps(t,n){resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(t),S}function readableStreamDefaultControllerPullSteps(t,n){let{stream:S,queue:C}=t[Cr];if(C.length){let N=dequeueValue(t);t[Cr].closeRequested&&!C.length?(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(S)):readableStreamDefaultControllerCallPullIfNeeded(t),n[Ir](N);return}readableStreamAddReadRequest(S,n),readableStreamDefaultControllerCallPullIfNeeded(t)}function setupReadableStreamDefaultController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:I,stream:t},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableStreamDefaultControllerCallPullIfNeeded(n)},t=>readableStreamDefaultControllerError(n,t))}function setupReadableStreamDefaultControllerFromSource(t,n,S,C){let N=new ReadableStreamDefaultController(Br),F=n?.start,I=n?.pull,H=n?.cancel;setupReadableStreamDefaultController(t,N,F?F.bind(n,N):nonOpStart,I?createPromiseCallback(`source.pull`,I,n):nonOpPull,H?createPromiseCallback(`source.cancel`,H,n):nonOpCancel,S,C)}function createReadableStream(t,n,S,C=1,N=()=>1){let F=Object.create(ReadableStream$1.prototype);return F[wr]=`ReadableStream`,F[Cr]=createReadableStreamState(),setupReadableStreamDefaultController(F,new ReadableStreamDefaultController(Br),t,n,S,C,N),F}function readableStreamFromIterable(t){let n,S=getIterator(t,`async`),C=nonOpStart;async function pullAlgorithm(){let t=iteratorNext(S);return Promise.resolve(t).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.next() method must fulfill with an object`);t.done?readableStreamDefaultControllerClose(n[Cr].controller):readableStreamDefaultControllerEnqueue(n[Cr].controller,t.value)})}async function cancelAlgorithm(t){let n=S.iterator,C=n.return;if(C===void 0)return Promise.resolve();let N=C.call(n,t);return Promise.resolve(N).then(t=>{if(typeof t!=`object`||!t)throw TypeError(`The promise returned by the iterator.return() method must fulfill with an object`)})}return n=createReadableStream(C,pullAlgorithm,cancelAlgorithm,0),n}function readableStreamPipeTo(t,n,S,C,N,F){let I,H;try{I=new ReadableStreamDefaultReader(t),H=new WritableStreamDefaultWriter(n)}catch(t){return Promise.reject(t)}t[Cr].disturbed=!0;let W=!1,{promise:q,resolve:Y,reject:X}=Promise.withResolvers(),Z={currentWrite:Promise.resolve()},te;function finalize(t,n){writableStreamDefaultWriterRelease(H),readableStreamReaderGenericRelease(I),F!==void 0&&te&&(F.removeEventListener(`abort`,te),te=void 0),t?X(n):Y()}async function waitForCurrentWrite(){let t=Z.currentWrite;await t,t!==Z.currentWrite&&await waitForCurrentWrite()}function shutdownWithAnAction(t,S,C){if(W)return;if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(complete,t=>finalize(!0,t));return}complete();function complete(){t().then(()=>finalize(!!S,C),t=>finalize(!0,t))}}function shutdown(t,S){if(!W){if(W=!0,n[Cr].state===`writable`&&!writableStreamCloseQueuedOrInFlight(n)){waitForCurrentWrite().then(()=>finalize(!!t,S),t=>finalize(!0,t));return}finalize(!!t,S)}}function abortAlgorithm(){let S;S=F.reason&&F.reason.name===`AbortError`?createAbortError$1():F.reason;let I=[];C||I.push(()=>n[Cr].state===`writable`?writableStreamAbort(n,S):Promise.resolve()),N||I.push(()=>t[Cr].state===`readable`?readableStreamCancel(t,S):Promise.resolve()),shutdownWithAnAction(()=>Promise.all(I.map(t=>t())).then(()=>void 0),!0,S)}function watchErrored(t,n,S){t[Cr].state===`errored`?S(t[Cr].storedError):n.then(void 0,S)}function watchClosed(t,n,S){t[Cr].state===`closed`?S():n.then(S,()=>{})}class PipeToReadRequest{[Ir](t){ve(()=>{Z.currentWrite=writableStreamDefaultWriterWrite(H,t),setPromiseHandled(Z.currentWrite),ne.resolve(!1)})}[Fr](){ne.resolve(!0)}[Lr](t){ne.reject(t)}}let ne={resolve:null,reject:null};async function step(){if(W||n[Cr].backpressure&&(await H[Cr].ready.promise,W))return!0;let S=t[Cr].controller;if(t[Cr].state===`readable`&&Wr(S)&&S[Cr].queue.length>0){for(;S[Cr].queue.length>0;){if(W)return!0;let C=dequeueValue(S);if(S[Cr].closeRequested&&!S[Cr].queue.length&&(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(t)),Z.currentWrite=writableStreamDefaultWriterWrite(H,C),setPromiseHandled(Z.currentWrite),n[Cr].backpressure||n[Cr].state!==`writable`||writableStreamCloseQueuedOrInFlight(n))break}return readableStreamDefaultControllerCallPullIfNeeded(S),t[Cr].state===`closed`}let{promise:C,resolve:N,reject:F}=Promise.withResolvers();return ne={resolve:N,reject:F},readableStreamDefaultReaderRead(I,new PipeToReadRequest),C}async function run(){for(;!await step(););}if(F!==void 0){if(F.aborted)return abortAlgorithm(),q;te=abortAlgorithm,F.addEventListener(`abort`,te,{once:!0})}if(setPromiseHandled(run()),watchErrored(t,I[Cr].close.promise,t=>{if(!C)return shutdownWithAnAction(()=>writableStreamAbort(n,t),!0,t);shutdown(!0,t)}),watchErrored(n,H[Cr].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n);shutdown(!0,n)}),watchClosed(t,I[Cr].close.promise,()=>{if(!S)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(H));shutdown()}),writableStreamCloseQueuedOrInFlight(n)||n[Cr].state===`closed`){let n=TypeError(`Destination WritableStream is closed`);N?shutdown(!0,n):shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n)}return q}function readableStreamDefaultTee(t,n){let S=new ReadableStreamDefaultReader(t),C=!1,N=!1,F=!1,I,H,W,q,Y=Promise.withResolvers();async function pullAlgorithm(){C||(C=!0,readableStreamDefaultReaderRead(S,{[Ir](t){ve(()=>{C=!1;let S=t,I=t;if(!F&&n)try{I=structuredClone(I)}catch{}N||readableStreamDefaultControllerEnqueue(W[Cr].controller,S),F||readableStreamDefaultControllerEnqueue(q[Cr].controller,I)})},[Fr](){ve(()=>{C=!1,N||readableStreamDefaultControllerClose(W[Cr].controller),F||readableStreamDefaultControllerClose(q[Cr].controller),(!N||!F)&&Y.resolve(void 0)})},[Lr](){C=!1}}))}function cancel1Algorithm(n){if(N=!0,I=n,F){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}function cancel2Algorithm(n){if(F=!0,H=n,N){let n=[I,H];Y.resolve(readableStreamCancel(t,n))}return Y.promise}return W=createReadableStream(nonOpStart,pullAlgorithm,cancel1Algorithm),q=createReadableStream(nonOpStart,pullAlgorithm,cancel2Algorithm),S[Cr].close.promise.then(void 0,t=>{readableStreamDefaultControllerError(W[Cr].controller,t),readableStreamDefaultControllerError(q[Cr].controller,t),(!N||!F)&&Y.resolve(void 0)}),[W,q]}var BYOBReadIntoRequest=class{[Cr];constructor(){this[Cr]=Promise.withResolvers()}[Ir](t){this[Cr].resolve?.({value:t,done:!1})}[Fr](t){this[Cr].resolve?.({value:t,done:!0})}[Lr](t){this[Cr].reject?.(t)}get promise(){return this[Cr].promise}},ReadableStreamBYOBReader=class{[wr]=`ReadableStreamBYOBReader`;[Cr];constructor(t){if(!Ur(t))throw TypeError(`Expected a ReadableStream`);this[Cr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,t)}read(t,n={}){if(!qr(this))return Promise.reject(TypeError(`Invalid this`));if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))return Promise.reject(TypeError(`view must be an ArrayBufferView`));let S=t.buffer,C=t.byteLength;if(C===0)return Promise.reject(TypeError(`view must have non-zero byteLength`));if(S.byteLength===0)return isDetachedBuffer(S)?Promise.reject(TypeError(`view's buffer has been detached`)):Promise.reject(TypeError(`view's buffer must have non-zero byteLength`));let N=n?.min??1;if(typeof N!=`number`||N<1||!Number.isInteger(N)||Number.isNaN(N))return Promise.reject(TypeError(`options.min must be a positive integer`));let F=t[Symbol.toStringTag];if(F!==void 0&&F!==`DataView`){if(N>t.length)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`))}else if(N>C)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`));if(this[Cr].stream===void 0)return Promise.reject(TypeError(`Reader has no associated stream`));let I=new BYOBReadIntoRequest;return readableStreamBYOBReaderRead(this,t,N,I),I.promise}releaseLock(){if(!qr(this))throw TypeError(`Invalid this`);this[Cr].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return qr(this)?this[Cr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return qr(this)?this[Cr].stream===void 0?Promise.reject(TypeError(`Reader has no associated stream`)):readableStreamReaderGenericCancel(this,t):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamBYOBReader`}},ReadableStreamBYOBRequest=class{[wr]=`ReadableStreamBYOBRequest`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get view(){if(!Jr(this))throw TypeError(`Invalid this`);return this[Cr].view}respond(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(t=+t,!Number.isInteger(t)||t<0||!Number.isFinite(t))throw RangeError(`bytesWritten must be a non-negative integer`);let n=this[Cr].view;if(isDetachedBuffer(n.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Cr].controller,t)}respondWithNewView(t){if(!Jr(this))throw TypeError(`Invalid this`);if(this[Cr].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`view must be an ArrayBufferView`);if(isDetachedBuffer(t.buffer))throw TypeError(`The given view's buffer has been detached`);readableByteStreamControllerRespondWithNewView(this[Cr].controller,t)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[wr]=`ReadableByteStreamController`;[Cr];constructor(t){if(t!==Br)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!Kr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!Kr(this))throw TypeError(`Invalid this`);if(this[Cr].closeRequested)throw TypeError(`Close already requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(t){if(!Kr(this))throw TypeError(`Invalid this`);if(typeof t!=`object`||!t||!ArrayBuffer.isView(t))throw TypeError(`chunk must be an ArrayBufferView`);if(t.byteLength===0)throw TypeError(`chunk length must be non-zero`);if(t.buffer.byteLength===0)throw TypeError(`chunk's buffer length must be non-zero`);if(this[Cr].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Cr].stream[Cr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,t)}error(t=void 0){if(!Kr(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,t)}[Pr](t){return readableByteStreamControllerCancelSteps(this,t)}[Rr](t){readableByteStreamControllerPullSteps(this,t)}[zr](){if(this[Cr].pendingPullIntos.length>0){let t=this[Cr].pendingPullIntos[0];t.readerType=`none`,this[Cr].pendingPullIntos=[t]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const Kr=isBrandCheck(`ReadableByteStreamController`),qr=isBrandCheck(`ReadableStreamBYOBReader`),Jr=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(t){let{reader:n}=t[Cr];return n===void 0?!1:n[Cr]!==void 0&&n[wr]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(t){return t[Cr].reader[Cr].readIntoRequests.length}function readableStreamAddReadIntoRequest(t,n){t[Cr].reader[Cr].readIntoRequests.push(n)}function readableStreamFulfillReadIntoRequest(t,n,S){let{reader:C}=t[Cr],N=C[Cr].readIntoRequests.shift();S?N[Fr](n):N[Ir](n)}function setupReadableStreamBYOBReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);if(!Kr(n[Cr].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(t,n),t[Cr].readIntoRequests=[]}function readableStreamBYOBReaderRead(t,n,S,C){let{stream:N}=t[Cr];N[Cr].disturbed=!0,N[Cr].state===`errored`?C[Lr](N[Cr].storedError):readableByteStreamControllerPullInto(N[Cr].controller,n,S,C)}function readableStreamBYOBReaderRelease(t){readableStreamReaderGenericRelease(t);let n=TypeError(`Reader was released`);for(let S=0;S<t[Cr].readIntoRequests.length;S++)t[Cr].readIntoRequests[S][Lr](n);t[Cr].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(t){t[Cr].pullAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(t){readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(t){let n=t[Cr].byobRequest;n!=null&&(n[Cr].controller=void 0,n[Cr].view=null,t[Cr].byobRequest=null)}function readableByteStreamControllerError(t,n){let{stream:S}=t[Cr];S[Cr].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t),readableByteStreamControllerClearAlgorithms(t),readableStreamError(S,n))}function readableByteStreamControllerGetDesiredSize(t){let n=t[Cr].stream[Cr].state;return n===`errored`?null:n===`closed`?0:t[Cr].highWaterMark-t[Cr].queueTotalSize}function readableByteStreamControllerShouldCallPull(t){let{stream:n}=t[Cr];if(n[Cr].state!==`readable`||t[Cr].closeRequested||!t[Cr].started)return!1;if(readableStreamHasDefaultReader(n)&&readableStreamGetNumReadRequests(n)>0||readableStreamHasBYOBReader(n)&&readableStreamGetNumReadIntoRequests(n)>0)return!0;let S=readableByteStreamControllerGetDesiredSize(t);return S!==null&&S>0}function readableByteStreamControllerCallPullIfNeeded(t){if(readableByteStreamControllerShouldCallPull(t)){if(t[Cr].pulling){t[Cr].pullAgain=!0;return}t[Cr].pulling=!0,t[Cr].pullAlgorithm(t).then(()=>{t[Cr].pulling=!1,t[Cr].pullAgain&&(t[Cr].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(t))},n=>readableByteStreamControllerError(t,n))}}function readableByteStreamControllerHandleQueueDrain(t){t[Cr].queueTotalSize===0&&t[Cr].closeRequested?(readableByteStreamControllerClearAlgorithms(t),readableStreamClose(t[Cr].stream)):readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerEnqueueChunkToQueue(t,n,S,C){t[Cr].queue.push({buffer:n,byteOffset:S,byteLength:C}),t[Cr].queueTotalSize+=C}function readableByteStreamControllerEnqueueClonedChunkToQueue(t,n,S,C){let N;try{N=n.slice(S,S+C)}catch(n){readableByteStreamControllerError(t,n);return}readableByteStreamControllerEnqueueChunkToQueue(t,N,0,C)}function readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n){n.bytesFilled>0&&readableByteStreamControllerEnqueueClonedChunkToQueue(t,n.buffer,n.byteOffset,n.bytesFilled),readableByteStreamControllerShiftPendingPullInto(t)}function readableByteStreamControllerShiftPendingPullInto(t){return t[Cr].pendingPullIntos.shift()}function readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S){S.bytesFilled+=n}function readableByteStreamControllerConvertPullIntoDescriptor(t){let n=t.bytesFilled,S=t.elementSize,C=transferArrayBuffer(t.buffer);return t.buffer=C,new t.viewConstructor(C,t.byteOffset,n/S)}function readableByteStreamControllerCommitPullIntoDescriptor(t,n){let S=!1;t[Cr].state===`closed`&&(S=!0);let C=readableByteStreamControllerConvertPullIntoDescriptor(n);n.readerType==="default"?readableStreamFulfillReadRequest(t,C,S):readableStreamFulfillReadIntoRequest(t,C,S)}function readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n){let S=Math.min(t[Cr].queueTotalSize,n.byteLength-n.bytesFilled),C=n.bytesFilled+S,N=S,F=!1,I=C-C%n.elementSize;I>=n.minimumFill&&(N=I-n.bytesFilled,F=!0);let H=t[Cr].queue;for(;N>0;){let S=H[0],C=Math.min(N,S.byteLength),F=n.byteOffset+n.bytesFilled,I=new Uint8Array(n.buffer,F,C),W=new Uint8Array(S.buffer,S.byteOffset,C);I.set(W),S.byteLength===C?H.shift():(S.byteOffset+=C,S.byteLength-=C),t[Cr].queueTotalSize-=C,readableByteStreamControllerFillHeadPullIntoDescriptor(t,C,n),N-=C}return F}function readableByteStreamControllerFillReadRequestFromQueue(t,n){let S=t[Cr].queue.shift();t[Cr].queueTotalSize-=S.byteLength,readableByteStreamControllerHandleQueueDrain(t);let C=new Uint8Array(S.buffer,S.byteOffset,S.byteLength);n[Ir](C)}function readableByteStreamControllerProcessReadRequestsUsingQueue(t){let n=t[Cr].stream[Cr].reader;for(;n[Cr].readRequests.length!==0;){if(t[Cr].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(t,n[Cr].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t){for(;t[Cr].pendingPullIntos.length!==0;){if(t[Cr].queueTotalSize===0)return;let n=t[Cr].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n)&&(readableByteStreamControllerShiftPendingPullInto(t),readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,n))}}function readableByteStreamControllerGetBYOBRequest(t){if(t[Cr].byobRequest===null&&t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0],S=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),C=new ReadableStreamBYOBRequest(Br);C[Cr]={controller:t,view:S},t[Cr].byobRequest=C}return t[Cr].byobRequest}function readableByteStreamControllerEnqueue(t,n){let{stream:S}=t[Cr];if(t[Cr].closeRequested||S[Cr].state!==`readable`)return;let C=n.buffer,N=n.byteLength,F=n.byteOffset;if(isDetachedBuffer(C))throw TypeError(`chunk's buffer is detached`);let I=transferArrayBuffer(C);if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(isDetachedBuffer(n.buffer))throw TypeError(`BYOB request's buffer has been detached`);readableByteStreamControllerInvalidateBYOBRequest(t),n.buffer=transferArrayBuffer(n.buffer),n.readerType===`none`&&readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,n)}readableStreamHasDefaultReader(S)?(readableByteStreamControllerProcessReadRequestsUsingQueue(t),readableStreamGetNumReadRequests(S)===0?readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N):(t[Cr].pendingPullIntos.length!==0&&readableByteStreamControllerShiftPendingPullInto(t),readableStreamFulfillReadRequest(S,new Uint8Array(I,F,N),!1))):readableStreamHasBYOBReader(S)?(readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)):readableByteStreamControllerEnqueueChunkToQueue(t,I,F,N),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerClose(t){let{stream:n}=t[Cr];if(!(t[Cr].closeRequested||n[Cr].state!==`readable`)){if(t[Cr].queueTotalSize>0){t[Cr].closeRequested=!0;return}if(t[Cr].pendingPullIntos.length!==0){let n=t[Cr].pendingPullIntos[0];if(n.bytesFilled%n.elementSize!==0){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);throw readableByteStreamControllerError(t,n),n}}readableByteStreamControllerClearAlgorithms(t),readableStreamClose(n)}}function readableByteStreamControllerPullInto(t,n,S,C){let N=t[Cr].stream,F=n[Symbol.toStringTag],I,H;if(F===void 0||F===`DataView`)I=DataView,H=1;else{let t=typedArrayConstructorByTag(F);if(!t){C[Lr](TypeError(`Unsupported typed array: ${F}`));return}I=t,H=elementSizeByTag(F)}let W=n.buffer,q=n.byteLength,Y=n.byteOffset,X=S*H,Z;try{Z=transferArrayBuffer(W)}catch(t){C[Lr](t);return}let te={buffer:Z,bufferByteLength:Z.byteLength,byteOffset:Y,byteLength:q,bytesFilled:0,minimumFill:X,elementSize:H,viewConstructor:I,readerType:`byob`};if(t[Cr].pendingPullIntos.length!==0){t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C);return}if(N[Cr].state===`closed`){let t=new I(te.buffer,te.byteOffset,0);C[Fr](t);return}if(t[Cr].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,te)){let n=readableByteStreamControllerConvertPullIntoDescriptor(te);readableByteStreamControllerHandleQueueDrain(t),C[Ir](n);return}if(t[Cr].closeRequested){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(t,n),C[Lr](n);return}}t[Cr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespond(t,n){let S=t[Cr].pendingPullIntos[0];if(t[Cr].stream[Cr].state===`closed`){if(n!==0)throw TypeError(`bytesWritten must be 0 when calling respond() on a closed stream`)}else{if(n===0)throw TypeError(`bytesWritten must be greater than 0 when calling respond() on a readable stream`);if(S.bytesFilled+n>S.byteLength)throw RangeError(`bytesWritten out of range`)}S.buffer=transferArrayBuffer(S.buffer),readableByteStreamControllerRespondInternal(t,n)}function readableByteStreamControllerRespondWithNewView(t,n){let S=t[Cr].pendingPullIntos[0],C=t[Cr].stream[Cr].state,N=n.byteLength,F=n.byteOffset,I=n.buffer;if(C===`closed`){if(N!==0)throw TypeError(`view's length must be 0 when calling respondWithNewView() on a closed stream`)}else if(N===0)throw TypeError(`view's length must be greater than 0 when calling respondWithNewView() on a readable stream`);if(S.byteOffset+S.bytesFilled!==F)throw RangeError(`The region specified by view does not match byobRequest`);if(S.bufferByteLength!==I.byteLength)throw RangeError(`The buffer of view has different capacity than byobRequest`);if(S.bytesFilled+N>S.byteLength)throw RangeError(`The region specified by view is larger than byobRequest`);S.buffer=transferArrayBuffer(I),readableByteStreamControllerRespondInternal(t,N)}function readableByteStreamControllerRespondInternal(t,n){let S=t[Cr].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(t),t[Cr].stream[Cr].state===`closed`?readableByteStreamControllerRespondInClosedState(t,S):readableByteStreamControllerRespondInReadableState(t,n,S),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespondInClosedState(t,n){n.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(t);let S=t[Cr].stream;if(readableStreamHasBYOBReader(S))for(;readableStreamGetNumReadIntoRequests(S)>0;)readableByteStreamControllerCommitPullIntoDescriptor(S,readableByteStreamControllerShiftPendingPullInto(t))}function readableByteStreamControllerRespondInReadableState(t,n,S){if(readableByteStreamControllerFillHeadPullIntoDescriptor(t,n,S),S.readerType===`none`){readableByteStreamControllerEnqueueDetachedPullIntoToQueue(t,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t);return}if(S.bytesFilled<S.minimumFill)return;readableByteStreamControllerShiftPendingPullInto(t);let C=S.bytesFilled%S.elementSize;if(C>0){let n=S.byteOffset+S.bytesFilled;readableByteStreamControllerEnqueueClonedChunkToQueue(t,S.buffer,n-C,C)}S.bytesFilled-=C,readableByteStreamControllerCommitPullIntoDescriptor(t[Cr].stream,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)}function readableByteStreamControllerCancelSteps(t,n){readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t);let S=t[Cr].cancelAlgorithm?.(n)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(t),S}function readableByteStreamControllerPullSteps(t,n){let S=t[Cr].stream;if(t[Cr].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(t,n);return}let C=t[Cr].autoAllocateChunkSize;if(C!==void 0){let S;try{S=new ArrayBuffer(C)}catch(t){n[Lr](t);return}let N={buffer:S,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};t[Cr].pendingPullIntos.push(N)}readableStreamAddReadRequest(S,n),readableByteStreamControllerCallPullIfNeeded(t)}function setupReadableByteStreamController(t,n,S,C,N,F,I){n[Cr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,stream:t,byobRequest:null,pendingPullIntos:[],autoAllocateChunkSize:I},t[Cr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Cr].started=!0,readableByteStreamControllerCallPullIfNeeded(n)},t=>readableByteStreamControllerError(n,t))}function setupReadableByteStreamControllerFromSource(t,n,S){let C=new ReadableByteStreamController(Br),N=n?.start,F=n?.pull,I=n?.cancel,H=n?.autoAllocateChunkSize;if(H!==void 0&&(H===0||!Number.isInteger(H)||H<0))throw TypeError(`autoAllocateChunkSize must be a positive integer`);setupReadableByteStreamController(t,C,N?N.bind(n,C):nonOpStart,F?createPromiseCallback(`source.pull`,F,n):nonOpPull,I?createPromiseCallback(`source.cancel`,I,n):nonOpCancel,S,H)}function readableByteStreamTee(t){let n=new ReadableStreamDefaultReader(t),S=!1,C=!1,N=!1,F,I,H=Promise.withResolvers(),W,q,Y,X;function pullAlgorithm(){return S?Promise.resolve():(S=!0,n.read().then(t=>{if(S=!1,t.done){C||Y.close(),N||X.close();return}let n=t.value,F=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength));C||Y.enqueue(F),N||X.enqueue(new Uint8Array(F))},()=>{}),Promise.resolve())}return W=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(C=!0,F=n,N){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),q=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(n){if(N=!0,I=n,C){let n=readableStreamCancel(t,[F,I]);return H.resolve(),n}return H.promise}}),Y=W[Cr].controller,X=q[Cr].controller,n.closed.catch(t=>{Y.error(t),X.error(t),(!C||!N)&&H.resolve()}),[W,q]}const Yr=Symbol(`kSkipThrow`);var TransformStream=class{[wr]=`TransformStream`;[Cr];constructor(t={},n={},S={}){if(t!=null&&typeof t!=`object`)throw TypeError(`transformer must be an object`);if(n!=null&&typeof n!=`object`)throw TypeError(`writableStrategy must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`readableStrategy must be an object`);let C=t?.readableType,N=t?.writableType,F=t?.start;if(C!==void 0)throw RangeError(`Invalid readableType: ${C}`);if(N!==void 0)throw RangeError(`Invalid writableType: ${N}`);let I=extractHighWaterMark(S?.highWaterMark,0),H=extractSizeAlgorithm(S?.size),W=extractHighWaterMark(n?.highWaterMark,1),q=extractSizeAlgorithm(n?.size),Y=Promise.withResolvers();initializeTransformStream(this,Y,W,q,I,H),setupTransformStreamDefaultControllerFromTransformer(this,t),F===void 0?Y.resolve():Y.resolve(F.call(t,this[Cr].controller))}get readable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].readable}get writable(){if(!Xr(this))throw TypeError(`Invalid this`);return this[Cr].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[wr]=`TransformStreamDefaultController`;[Cr];constructor(t){if(t!==Yr)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!Zr(this))throw TypeError(`Invalid this`);let{stream:t}=this[Cr],{readable:n}=t[Cr],S=n[Cr].controller;return readableStreamDefaultControllerGetDesiredSize(S)}enqueue(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,t)}error(t){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,t)}terminate(){if(!Zr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Xr=isBrandCheck(`TransformStream`),Zr=isBrandCheck(`TransformStreamDefaultController`);async function defaultTransformAlgorithm(t,n){transformStreamDefaultControllerEnqueue(n,t)}function initializeTransformStream(t,n,S,C,N,F){let startAlgorithm=()=>n.promise,I=createWritableStream(startAlgorithm,n=>transformStreamDefaultSinkWriteAlgorithm(t,n),()=>transformStreamDefaultSinkCloseAlgorithm(t),n=>transformStreamDefaultSinkAbortAlgorithm(t,n),S,C);t[Cr]={readable:createReadableStream(startAlgorithm,()=>transformStreamDefaultSourcePullAlgorithm(t),n=>transformStreamDefaultSourceCancelAlgorithm(t,n),N,F),writable:I,controller:void 0,backpressure:void 0,backpressureChange:{promise:void 0,resolve:void 0,reject:void 0}},transformStreamSetBackpressure(t,!0)}function transformStreamError(t,n){let{readable:S}=t[Cr];readableStreamDefaultControllerError(S[Cr].controller,n),transformStreamErrorWritableAndUnblockWrite(t,n)}function transformStreamErrorWritableAndUnblockWrite(t,n){let{controller:S,writable:C}=t[Cr];transformStreamDefaultControllerClearAlgorithms(S),writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t)}function transformStreamUnblockWrite(t){t[Cr].backpressure&&transformStreamSetBackpressure(t,!1)}function transformStreamSetBackpressure(t,n){t[Cr].backpressureChange.promise!==void 0&&t[Cr].backpressureChange.resolve?.(),t[Cr].backpressureChange=Promise.withResolvers(),t[Cr].backpressure=n}function setupTransformStreamDefaultController(t,n,S,C,N){n[Cr]={stream:t,transformAlgorithm:S,flushAlgorithm:C,cancelAlgorithm:N,finishPromise:void 0},t[Cr].controller=n}function setupTransformStreamDefaultControllerFromTransformer(t,n){let S=new TransformStreamDefaultController(Yr),C=n?.transform,N=n?.flush,F=n?.cancel;setupTransformStreamDefaultController(t,S,C?createPromiseCallback(`transformer.transform`,C,n):defaultTransformAlgorithm,N?createPromiseCallback(`transformer.flush`,N,n):nonOpFlush,F?createPromiseCallback(`transformer.cancel`,F,n):nonOpCancel)}function transformStreamDefaultControllerClearAlgorithms(t){t[Cr].transformAlgorithm=void 0,t[Cr].flushAlgorithm=void 0,t[Cr].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(t,n){let{stream:S}=t[Cr],{readable:C}=S[Cr],N=C[Cr].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(N))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(N,n)}catch(t){throw transformStreamErrorWritableAndUnblockWrite(S,t),C[Cr].storedError}readableStreamDefaultControllerHasBackpressure(N)!==S[Cr].backpressure&&transformStreamSetBackpressure(S,!0)}function transformStreamDefaultControllerError(t,n){transformStreamError(t[Cr].stream,n)}async function transformStreamDefaultControllerPerformTransform(t,n){try{let S=t[Cr].transformAlgorithm;if(S===void 0)return;await S(n,t)}catch(n){throw transformStreamError(t[Cr].stream,n),n}}function transformStreamDefaultControllerTerminate(t){let{stream:n}=t[Cr],{readable:S}=n[Cr];readableStreamDefaultControllerClose(S[Cr].controller),transformStreamErrorWritableAndUnblockWrite(n,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(t,n){let{controller:S}=t[Cr];return t[Cr].backpressure?t[Cr].backpressureChange.promise.then(()=>{let{writable:C}=t[Cr];if(C[Cr].state===`erroring`)throw C[Cr].storedError;return transformStreamDefaultControllerPerformTransform(S,n)}):transformStreamDefaultControllerPerformTransform(S,n)}async function transformStreamDefaultSinkAbortAlgorithm(t,n){let{controller:S,readable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(readableStreamDefaultControllerError(C[Cr].controller,n),F())},t=>{readableStreamDefaultControllerError(C[Cr].controller,t),I(t)}),S[Cr].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(t){let{readable:n,controller:S}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:C,resolve:N,reject:F}=Promise.withResolvers();S[Cr].finishPromise=C;let I=S[Cr].flushAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(S),I.then(()=>{n[Cr].state===`errored`?F(n[Cr].storedError):(readableStreamDefaultControllerClose(n[Cr].controller),N())},t=>{readableStreamDefaultControllerError(n[Cr].controller,t),F(t)}),S[Cr].finishPromise}function transformStreamDefaultSourcePullAlgorithm(t){return transformStreamSetBackpressure(t,!1),t[Cr].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(t,n){let{controller:S,writable:C}=t[Cr];if(S[Cr].finishPromise!==void 0)return S[Cr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Cr].finishPromise=N;let H=S[Cr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Cr].state===`errored`?I(C[Cr].storedError):(writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),F())},n=>{writableStreamDefaultControllerErrorIfNeeded(C[Cr].controller,n),transformStreamUnblockWrite(t),I(n)}),S[Cr].finishPromise}const Qr=Object.defineProperty(t=>t.byteLength,"name",{value:`size`}),$r=Object.defineProperty(()=>1,"name",{value:`size`});var ByteLengthQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return Qr}get[Symbol.toStringTag](){return`ByteLengthQueuingStrategy`}},CountQueuingStrategy=class{#e;constructor(t){if(typeof t!=`object`||!t)throw TypeError(`init must be an object`);if(t.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+t.highWaterMark}get highWaterMark(){return this.#e}get size(){return $r}get[Symbol.toStringTag](){return`CountQueuingStrategy`}},TextEncoderStream=class{#e=null;#t=new TextEncoder;#n;constructor(){this.#n=new TransformStream({transform:(t,n)=>{if(t=String(t),t===``)return;this.#e!==null&&(t=this.#e+t);let S=t.charCodeAt(t.length-1);55296<=S&&S<=56319?(this.#e=t.slice(-1),t=t.slice(0,-1)):this.#e=null,t&&n.enqueue(this.#t.encode(t))},flush:t=>{this.#e!==null&&t.enqueue(new Uint8Array([239,191,189]))}})}get encoding(){return`utf-8`}get readable(){return this.#n.readable}get writable(){return this.#n.writable}};function hasStreamingSupport(){try{return new TextDecoder().decode(new Uint8Array([195]),{stream:!0}),!0}catch{return!1}}const ei=hasStreamingSupport();function incompleteUtf8Tail$1(t){let n=t.length;if(n===0)return 0;for(let S=1;S<=Math.min(3,n);S++){let C=t[n-S];if(!(C&128))return 0;if((C&192)!=128){let t;if((C&224)==192)t=2;else if((C&240)==224)t=3;else if((C&248)==240)t=4;else return 0;return S<t?S:0}}return 0}__name$1(incompleteUtf8Tail$1,`incompleteUtf8Tail`);var TextDecoderStream=class{#e;#t;constructor(t,n){if(this.#e=new TextDecoder(t,n),ei)this.#t=new TransformStream({transform:(t,n)=>{let S=toUint8Array$3(t),C=this.#e.decode(S,{stream:!0});C&&n.enqueue(C)},flush:t=>{let n=this.#e.decode();n&&t.enqueue(n)},cancel:()=>{this.#e.decode()}});else{let t=new Uint8Array;this.#t=new TransformStream({transform:(n,S)=>{let C=toUint8Array$3(n),N;t.length>0?(N=new Uint8Array(t.length+C.length),N.set(t,0),N.set(C,t.length)):N=C;let F=incompleteUtf8Tail$1(N),I;if(F>0?(I=N.slice(0,N.length-F),t=N.slice(N.length-F)):(I=N,t=new Uint8Array),I.length>0){let t=this.#e.decode(I);t&&S.enqueue(t)}},flush:n=>{if(t.length>0){let S=this.#e.decode(t);S&&n.enqueue(S),t=new Uint8Array}},cancel:()=>{t=new Uint8Array}})}}get encoding(){return this.#e.encoding}get fatal(){return this.#e.fatal}get ignoreBOM(){return this.#e.ignoreBOM}get readable(){return this.#t.readable}get writable(){return this.#t.writable}};function toUint8Array$3(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`chunk must be a BufferSource`)}__name$1(toUint8Array$3,`toUint8Array`);function isNativeStreamUsable$3(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$3,`isNativeStreamUsable`);const ti=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,ni=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,ri=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,ii=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,ai=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,oi=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,si=typeof globalThis.TextDecoderStream==`function`?globalThis.TextDecoderStream:TextDecoderStream;function withCode(t,n){return Object.assign(t,{code:n})}function addNumericalSeparator(t){let n=``,S=t.length,C=+(t[0]===`-`);for(;S>=C+4;S-=3)n=`_${t.slice(S-3,S)}${n}`;return`${t.slice(0,S)}${n}`}function formatReceivedNumber(t){return Number.isInteger(t)&&Math.abs(t)>2**32?addNumericalSeparator(String(t)):Object.is(t,-0)?`-0`:String(t)}function describeType(t){if(t===null)return`null`;switch(typeof t){case`bigint`:return`type bigint (${t}n)`;case`boolean`:return`type boolean (${t})`;case`symbol`:return`type symbol (${String(t)})`;case`function`:return`function ${t.name}`;case`string`:{let n=t.length>28?`${t.slice(0,25)}...`:t;return n.includes(`'`)?`type string (${JSON.stringify(n)})`:`type string ('${n}')`}default:{let n=t.constructor;return n?.name?`an instance of ${n.name}`:`type ${typeof t}`}}}function outOfRange(t,n){return withCode(RangeError(`The value of "${li}" is out of range. It must be ${t}. Received ${formatReceivedNumber(n)}`),`ERR_OUT_OF_RANGE`)}function resolveMaxOutputLength(t){let n=t?.maxOutputLength;if(n===void 0)return ci;if(typeof n!=`number`)throw withCode(TypeError(`The "${li}" property must be of type number. Received ${describeType(n)}`),`ERR_INVALID_ARG_TYPE`);if(Number.isNaN(n))return ci;if(!Number.isFinite(n))throw outOfRange(`a finite number`,n);if(n<1||n>ci)throw outOfRange(`>= 1 and <= ${ci}`,n);return n}function bufferTooLargeError(t){return withCode(RangeError(`Cannot create a Buffer larger than ${t} bytes`),`ERR_BUFFER_TOO_LARGE`)}function isBufferTooLargeError(t){return t instanceof RangeError&&t.code===`ERR_BUFFER_TOO_LARGE`}function remainingReadBudget(t,n){return Math.floor(t-n)+1}var ci,li,di=__esmMin(()=>{ci=2**53-1,li=`options.maxOutputLength`}),fi,pi=__esmMin(()=>{fi=n}),mi,hi=__esmMin(()=>{pi(),mi=fi});function getGioFormat(t){switch(t){case`gzip`:return mi.ZlibCompressorFormat.GZIP;case`deflate`:return mi.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return mi.ZlibCompressorFormat.RAW}}function hasGzipMagic(t,n=0){return t.length-n>=2&&t[n]===31&&t[n+1]===139}function concat$2(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function assertLevel(t){if(!(t>=-1&&t<=9))throw RangeError(`The value of "level" is out of range. It must be >= -1 and <= 9. Received ${t}`)}function compressWithGio(t,n,S=-1){assertLevel(S);let C=new mi.ZlibCompressor({format:getGioFormat(n),level:Math.trunc(S)}),N=new mi.ConverterOutputStream({base_stream:mi.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new lt.Bytes(t),null),N.close(null);let F=N.get_base_stream().steal_as_bytes();return new Uint8Array(F.get_data()??[])}function decompressStreamWithGio(t,n,S=ci,C=0){let N=new mi.ZlibDecompressor({format:getGioFormat(n)}),F=mi.MemoryInputStream.new_from_bytes(new lt.Bytes(t)),I=new mi.ConverterInputStream({base_stream:F,converter:N}),H=[],W=C;try{for(;;){let t=Math.min(_i,remainingReadBudget(S,W)),n=I.read_bytes(t,null),C=n.get_size();if(C===0)break;if(W+=C,W>S)throw bufferTooLargeError(S);H.push(new Uint8Array(n.get_data()))}}finally{I.close(null)}return concat$2(H)}function findGzipMemberEnd(t,n=1/0){let S=new mi.ZlibDecompressor({format:mi.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0,F=0;for(;;){let I=t.subarray(N,N+gi);try{let[t,H,W]=S.convert(I,C,mi.ConverterFlags.NONE);if(N+=H,F+=W,t===mi.ConverterResult.FINISHED||F>n||H===0&&W===0)return N}catch{return N}}}function gunzipWithGio(t,n=ci){let S=[],C=0,N=0;for(;hasGzipMagic(t,C);){let F=t.subarray(C),I=findGzipMemberEnd(F,n-N);if(I<=0)break;let H=decompressStreamWithGio(F.subarray(0,I),`gzip`,n,N);S.push(H),N+=H.length,C+=I}return S.length===0?decompressStreamWithGio(t,`gzip`,n):concat$2(S)}var gi,_i,vi=__esmMin(()=>{di(),hi(),ut(),gi=256*1024,_i=1024*1024,__name$1(concat$2,`concat`)}),yi=__esmMin(()=>{ze()}),bi,xi,Si=__esmMin(()=>{bi=Object.defineProperty,xi=__name$1((t,n)=>{let S={};for(var C in t)bi(S,C,{get:t[C],enumerable:!0});return n||bi(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function _setPipeImpl(t){Ci=t}var Ci,Stream_,wi=__esmMin(()=>{qt(),Stream_=class extends It{constructor(t){super(t)}pipe(t,n){return Ci(this,t,n)}}});function finished$1(t,n,S){let C;C=typeof n==`function`?n:S;let N=!1;function done(t){N||(N=!0,C(t))}let onFinish=()=>done(),onEnd=()=>done(),onError=t=>done(t),onClose=()=>{let n=t,S=t;!n.writableFinished&&!S.readableEnded&&done(Error(`premature close`))};t.on(`finish`,onFinish),t.on(`end`,onEnd),t.on(`error`,onError),t.on(`close`,onClose);let F=t,I=typeof t.write==`function`,H=typeof t.read==`function`,W=F.writableFinished===!0,q=F.readableEnded===!0;if(F.destroyed===!0){let t=F._err;ve(t?()=>done(t):I&&W||H&&q?()=>done():()=>done(Error(`premature close`)))}else(I&&!H&&W||!I&&H&&q||I&&H&&W&&q)&&ve(()=>done());return function cleanup(){t.removeListener(`finish`,onFinish),t.removeListener(`end`,onEnd),t.removeListener(`error`,onError),t.removeListener(`close`,onClose)}}function addAbortSignal(t,n){if(!(t instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(n instanceof Stream_))throw TypeError(`The second argument must be a Stream`);let S=n;if(t.aborted)S.destroy(Error(`The operation was aborted`));else{let onAbort=()=>{S.destroy(Error(`The operation was aborted`))};t.addEventListener(`abort`,onAbort,{once:!0}),n.once(`close`,()=>{t.removeEventListener(`abort`,onAbort)})}return n}function isReadable(t){if(t==null)return!1;let n=t;return typeof n.readable!=`boolean`||typeof n.read!=`function`||n.destroyed===!0||n.readableEnded===!0?!1:n.readable===!0}function isWritable(t){if(t==null)return!1;let n=t;return typeof n.writable!=`boolean`||typeof n.write!=`function`||n.destroyed===!0||n.writableEnded===!0?!1:n.writable===!0}function isDestroyed(t){return t==null?!1:t.destroyed===!0}function isDisturbed(t){if(t==null)return!1;let n=t;return n.readableDidRead===!0||n.readableFlowing!==null&&n.readableFlowing!==void 0}function isErrored(t){if(t==null)return!1;let n=t;return n.destroyed===!0&&typeof n.readable==`boolean`&&n.readable===!1||n.destroyed===!0&&typeof n.writable==`boolean`&&n.writable===!1}var Ti=__esmMin(()=>{wi(),ze(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(t){return t?Di:Ei}function setDefaultHighWaterMark(t,n){if(typeof n!=`number`||n<0||Number.isNaN(n))throw TypeError(`Invalid highWaterMark: ${n}`);t?Di=n:Ei=n}function validateHighWaterMark(t,n){if(n!==void 0&&(typeof n!=`number`||Number.isNaN(n))){let S=TypeError(`The value of "${t}" is invalid. Received ${n}`);throw S.code=`ERR_INVALID_ARG_VALUE`,S}}var Ei,Di,Oi=__esmMin(()=>{Ei=16384,Di=16});function createAbortError(){let t=Error(`The operation was aborted`);return t.name=`AbortError`,t.code=`ABORT_ERR`,t}async function streamAsyncDispose(t,n){let S;t.destroyed||(S=n?void 0:createAbortError(),t.destroy(S)),await new Promise((n,C)=>{finished$1(t,t=>{t&&t!==S?C(t):n()})})}var ki,Ai=__esmMin(()=>{Ti(),ki=Symbol.asyncDispose??Symbol.for(`Symbol.asyncDispose`)});function chunkLength(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}function sliceChunk(t,n,S){if(typeof t==`string`)return S===void 0?t.slice(n):t.slice(n,S);let C=t.slice;return typeof C==`function`?C.call(t,n,S):t}var ji,Mi,Ni,Pi=__esmMin(()=>{wi(),Ai(),Oi(),ze(),ji=class Readable_ extends Stream_{readable=!0;readableFlowing=null;readableLength=0;readableHighWaterMark;readableEncoding;readableObjectMode;readableEnded=!1;readableAborted=!1;destroyed=!1;_pipeDests=[];_buffer=[];_readableState={ended:!1,endEmitted:!1,reading:!1,constructed:!0,highWaterMark:0,objectMode:!1,pipes:[]};_err;_readablePending=!1;_readImpl;_constructImpl;constructor(t){super(t),this.readableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.readableEncoding=t?.encoding??null,this.readableObjectMode=t?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,t?.read&&(this._readImpl=t.read),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Readable_.prototype._construct)&&(this._readableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._readableState.constructed=!0,t?this.destroy(t):this.readableFlowing===!0&&this._flow()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_read(t){this._readImpl&&this._readImpl.call(this,t)}read(t){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(t??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||t===0)return null;if(this.readableObjectMode){if(t===void 0){let t=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),t}if(t>this.readableLength)return null;let n=this._buffer.shift();return--this.readableLength,n}if(t!=null)return t>this.readableLength?null:this._readBytes(t);let n=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),n.length===1)return n[0];if(n.length===0)return null;if(typeof n[0]==`string`)return n.join(``);let S=globalThis.Buffer;return S?.concat?S.concat(n):n}_readBytes(t){let n=0,S=[];for(;n<t&&this._buffer.length>0;){let C=this._buffer[0],N=chunkLength(C);if(n+N<=t)S.push(this._buffer.shift()),n+=N,this.readableLength-=N;else{let N=t-n;S.push(sliceChunk(C,0,N)),this._buffer[0]=sliceChunk(C,N),this.readableLength-=N,n+=N}}if(S.length===1)return S[0];let C=globalThis.Buffer;return C?.concat?C.concat(S):S}push(t,n){if(t===null)return this._readableState.ended=!0,this.readableEnded=!0,this._buffer.length===0&&!this._readableState.endEmitted&&nextTick(()=>this._emitEnd()),this._scheduleReadable(),!1;if(!this.readableObjectMode&&!(typeof t==`string`||ArrayBuffer.isView(t))){let n=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof t}`),{code:`ERR_INVALID_ARG_TYPE`});return nextTick(()=>this.emit(`error`,n)),!1}return this._buffer.push(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t),this.readableFlowing&&!this._flowing&&nextTick(()=>this._flow()),this.readableFlowing!==!0&&this._scheduleReadable(),this.readableLength<this.readableHighWaterMark}_emitEnd(){this._readableState.endEmitted||(this._readableState.endEmitted=!0,this.emit(`end`),nextTick(()=>this._autoClose()))}_autoClose(){this.emit(`close`)}_scheduleReadable(){this._readablePending||this.listenerCount(`readable`)===0||(this._readablePending=!0,nextTick(()=>{this._readablePending=!1,this.destroyed||this.emit(`readable`)}))}on(t,n){return super.on(t,n),t===`data`&&this.readableFlowing!==!1&&this.listenerCount(`readable`)===0&&this.resume(),t===`readable`&&(this.readableFlowing=!1,this._buffer.length>0||this._readableState.ended?this._scheduleReadable():this._readableState.reading||nextTick(()=>{this.destroyed||this.read(0)})),this}removeListener(t,n){let S=super.removeListener(t,n);return t===`readable`&&nextTick(()=>this._updateReadableListening()),S}removeAllListeners(t){let n=t===void 0?super.removeAllListeners():super.removeAllListeners(t);return(t===`readable`||t===void 0)&&nextTick(()=>this._updateReadableListening()),n}_updateReadableListening(){this.listenerCount(`readable`)>0||(this.listenerCount(`data`)>0?this.resume():this.readableFlowing=null)}unshift(t){this._buffer.unshift(t),this.readableLength+=this.readableObjectMode?1:chunkLength(t)}setEncoding(t){return this.readableEncoding=t,this}pause(){return this.readableFlowing=!1,this.emit(`pause`),this}resume(){return this.readableFlowing!==!0&&(this.readableFlowing=!0,this.emit(`resume`),this._readableState.constructed&&this._flow()),this}_flowing=!1;_flow(){if(!(this.readableFlowing!==!0||this._flowing||this.destroyed)&&this._readableState.constructed){this._flowing=!0;try{for(;this._buffer.length>0&&this.readableFlowing&&!this.destroyed;){let t=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:chunkLength(t),this.readableEncoding&&typeof t!=`string`){let n=globalThis.Buffer;n?.isBuffer&&n.isBuffer(t)?t=t.toString(this.readableEncoding):t instanceof Uint8Array&&(t=new TextDecoder(this.readableEncoding).decode(t))}this.emit(`data`,t)}if(this.destroyed)return;if(this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted){nextTick(()=>this._emitEnd());return}!this._readableState.ended&&!this._readableState.reading&&!this.destroyed&&(this._readableState.reading=!0,this._read(this.readableHighWaterMark),this._readableState.reading=!1)}finally{this._flowing=!1}this._buffer.length>0&&this.readableFlowing&&!this.destroyed&&nextTick(()=>this._flow())}}isPaused(){return this.readableFlowing===!1}unpipe(t){if(t){let n=this._pipeDests.findIndex(n=>n.dest===t);if(n!==-1){this._pipeDests[n].cleanup(),this._pipeDests.splice(n,1);let S=this._readableState.pipes.indexOf(t);S!==-1&&this._readableState.pipes.splice(S,1),t.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let t of this._pipeDests)t.cleanup(),t.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(t,n){n(t??void 0)}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}static toWeb(t){return new ReadableStream({start(n){t.on(`data`,t=>{typeof t==`string`?n.enqueue(new TextEncoder().encode(t)):t instanceof Uint8Array?n.enqueue(t):t&&typeof t.length==`number`&&n.enqueue(new Uint8Array(t))}),t.on(`end`,()=>{n.close()}),t.on(`error`,t=>{n.error(t)})},cancel(){t.destroy()}})}static fromWeb(t,n){let S=t.getReader();return new Readable_({...n,read(){S.read().then(({done:t,value:n})=>{t?this.push(null):this.push(n)},t=>{this.destroy(t)})},destroy(t,n){S.cancel(t?.message).then(()=>n(null),n)}})}[Symbol.asyncIterator](){let t=this,n=[],S=!1,C=null,N=null,F=null;return t.on(`data`,t=>{if(N){let n=N;N=null,F=null,n({value:t,done:!1})}else n.push(t)}),t.on(`end`,()=>{if(S=!0,N){let t=N;N=null,F=null,t({value:void 0,done:!0})}}),t.on(`error`,t=>{if(C=t,S=!0,F){let n=F;N=null,F=null,n(t)}}),{next(){return C?Promise.reject(C):n.length>0?Promise.resolve({value:n.shift(),done:!1}):S?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{N=t,F=n})},return(){return t.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(t,n){let S=new Readable_({objectMode:!0,...n,read(){}});return typeof t==`string`||ArrayBuffer.isView(t)?(S.push(t),S.push(null),S):((async()=>{try{for await(let n of t)S.push(n)||await new Promise(t=>S.once(`drain`,t));S.push(null)}catch(t){S.destroy(t)}})(),S)}},ji.prototype[ki]=function(){return streamAsyncDispose(this,this.readableEnded)},Mi=Object.getOwnPropertyDescriptor(ji.prototype,`on`),Ni=Object.getOwnPropertyDescriptor(ji.prototype,`removeListener`),Object.defineProperty(ji.prototype,"addListener",{...Mi}),Object.defineProperty(ji.prototype,"off",{...Ni})});function writeAfterEndError(){let t=Error(`write after end`);return t.code=`ERR_STREAM_WRITE_AFTER_END`,t}var Fi=__esmMin(()=>{});function chunkLen$1(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Duplex_,Ii=__esmMin(()=>{Fi(),Oi(),Pi(),ze(),Duplex_=class extends ji{writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;allowHalfOpen;_decodeStrings;_writableState={highWaterMark:0,objectMode:!1};_duplexCorkedBuffer=[];_duplexWriting=!1;_duplexWriteQueue=[];_writeImpl;_finalImpl;_defaultEncoding=`utf8`;_pendingWrites=0;_pendingEndCb=null;constructor(t){super(t),validateHighWaterMark(`writableHighWaterMark`,t?.writableHighWaterMark),validateHighWaterMark(`readableHighWaterMark`,t?.readableHighWaterMark),this.writableObjectMode=t?.writableObjectMode??t?.objectMode??!1,this.writableHighWaterMark=t?.highWaterMark??t?.writableHighWaterMark??getDefaultHighWaterMark(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,t?.highWaterMark===void 0&&t?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=t.readableHighWaterMark,this._readableState.highWaterMark=t.readableHighWaterMark),t?.readableObjectMode!==void 0&&(this.readableObjectMode=t.readableObjectMode,this._readableState.objectMode=t.readableObjectMode,t?.readableHighWaterMark===void 0&&t?.highWaterMark===void 0&&(this.readableHighWaterMark=getDefaultHighWaterMark(t.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=t?.allowHalfOpen!==!1,this._decodeStrings=t?.decodeStrings!==!1,t?.write&&(this._writeImpl=t.write),t?.final&&(this._finalImpl=t.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||nextTick(()=>this.end())})}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}destroy(t){return this.destroyed?this:(this.writable=!1,super.destroy(t))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen$1(t),this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._duplexDoWrite(t,N,C),F}_duplexDoWrite(t,n,S){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:t,encoding:n,callback:S});return}this._duplexWriting=!0,this._duplexStartWrite(t,n,S)}_duplexStartWrite(t,n,S){this._pendingWrites++,this._write(t,n,n=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:chunkLen$1(t),nextTick(n?()=>{if(S(n),this._duplexWriting=!1,this.destroyed||this.emit(`error`,n),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(t.chunk,t.encoding,t.callback)}}:()=>{if(S(),this._duplexWriteQueue.length>0){let t=this._duplexWriteQueue.shift();this._duplexStartWrite(t.chunk,t.encoding,t.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let t=this._pendingEndCb;this._pendingEndCb=null,t()}})})}end(t,n,S){typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),t!=null&&this.write(t,n),this.writableEnded=!0;let doFinal=()=>{this._final(t=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),nextTick(()=>this.emit(`close`)),S&&S()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_doPrefinishHooks(t){t()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let t=this._duplexCorkedBuffer.splice(0);for(let{chunk:n,encoding:S,callback:C}of t)this._write(n,S,t=>{this.writableLength-=this.writableObjectMode?1:chunkLen$1(n),t?(C(t),this.destroyed||this.emit(`error`,t)):C()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,nextTick(()=>this.emit(`drain`)))}}setDefaultEncoding(t){return this._defaultEncoding=t,this}},__name$1(chunkLen$1,`chunkLen`)});function pipe(t,n,S){let C=t,N=S?.end!==!1,F=!1,ondrain=()=>{F=!1,n.removeListener(`drain`,ondrain);let t=C;typeof t.resume==`function`&&t.resume()},ondata=t=>{if(n.writable){let S=C;n.write(t)===!1&&typeof S.pause==`function`&&(S.pause(),F||(F=!0,n.on(`drain`,ondrain)))}};C.on(`data`,ondata);let I=!1,onend=()=>{I||(I=!0,N&&n.end())},onclose=()=>{if(!I&&(I=!0,N&&!(C instanceof ji))){let t=n;typeof t.destroy==`function`&&t.destroy()}};N&&(C.on(`end`,onend),C.on(`close`,onclose));let cleanup=()=>{C.removeListener(`data`,ondata),F&&n.removeListener(`drain`,ondrain),C.removeListener(`end`,onend),C.removeListener(`close`,onclose),C.removeListener(`end`,cleanup),C.removeListener(`close`,cleanup),n.removeListener(`close`,cleanup)};return C.on(`end`,cleanup),C.on(`close`,cleanup),n.on(`close`,cleanup),C instanceof ji&&(C._pipeDests.push({dest:n,cleanup}),C._readableState.pipes.push(n)),n.emit(`pipe`,C),n}var Li=__esmMin(()=>{wi(),Pi(),_setPipeImpl(pipe)});function chunkLen(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Ri,zi=__esmMin(()=>{Fi(),wi(),Ai(),Oi(),ze(),Ri=class Writable_ extends Stream_{static[Symbol.hasInstance](t){let n=this;return n.prototype!==void 0&&Object.prototype.isPrototypeOf.call(n.prototype,t)?!0:n.prototype!==Writable_.prototype||t==null?!1:typeof t.writableHighWaterMark==`number`}writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;destroyed=!1;_err;_writableState={ended:!1,finished:!1,constructed:!0,writing:!1};_corkedBuffer=[];_writeBuffer=[];_pendingConstruct=[];_ending=!1;_endCallback;_pendingEnd=null;_writeImpl;_writev;_finalImpl;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;_autoDestroy;constructor(t){super(t),this.writableHighWaterMark=t?.highWaterMark??getDefaultHighWaterMark(t?.objectMode??!1),this.writableObjectMode=t?.objectMode??!1,this._decodeStrings=t?.decodeStrings!==!1,this._autoDestroy=t?.autoDestroy!==!1,t?.write&&(this._writeImpl=t.write),t?.writev&&(this._writev=t.writev),t?.final&&(this._finalImpl=t.final),t?.destroy&&(this._destroy=t.destroy),t?.construct&&(this._constructImpl=t.construct),(this._constructImpl||this._construct!==Writable_.prototype._construct)&&(this._writableState.constructed=!1,nextTick(()=>{this._construct(t=>{this._writableState.constructed=!0,t?this.destroy(t):this._maybeFlush()})}))}_construct(t){this._constructImpl?this._constructImpl.call(this,t):t()}_write(t,n,S){this._writeImpl?this._writeImpl.call(this,t,n,S):S()}_final(t){this._finalImpl?this._finalImpl.call(this,t):t()}_destroy(t,n){n(t)}_maybeFlush(){let t=this._pendingConstruct.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}if(this._pendingEnd){let{chunk:t,encoding:n,callback:S}=this._pendingEnd;this._pendingEnd=null,this._doEnd(t,n,S)}}_doWrite(t,n,S){this._writableState.writing=!0;let C=!0;this._write(t,n,n=>{if(this.writableLength-=this.writableObjectMode?1:chunkLen(t),C){nextTick(()=>{if(n){S(n),this.emit(`error`,n);return}S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),n||this._drainWriteBuffer();return}nextTick(n?()=>{S(n),this.emit(`error`,n),this._drainWriteBuffer()}:()=>{S(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),C=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let t=this._writeBuffer.shift();this._doWrite(t.chunk,t.encoding,t.callback)}else this._writableState.writing=!1,this._maybeFinish()}_maybeFinish(){!this._ending||this._writableState.finished||this._writableState.writing||this._writeBuffer.length>0||(this._ending=!1,this._final(t=>{this.writableFinished=!0,this._writableState.finished=!0,nextTick(()=>{t&&this.emit(`error`,t),this.emit(`finish`),this._autoDestroy?this.destroy():nextTick(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(t,n,S){let C,N;if(typeof n==`function`?(C=n,N=this._defaultEncoding):(N=n??this._defaultEncoding,C=S??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof t==`string`){let n=globalThis.Buffer;n&&(t=n.from(t,N),N=`buffer`)}if(typeof t!=`string`&&!this.writableObjectMode){let n=globalThis.Buffer;(n&&n.isBuffer(t)||t instanceof Uint8Array)&&(N=`buffer`)}if(this.writableEnded){let t=writeAfterEndError();return nextTick(()=>{C(t),this.emit(`error`,t)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen(t),this.writableCorked>0)return this._corkedBuffer.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:t,encoding:N,callback:C}),this.writableLength<this.writableHighWaterMark;let F=this.writableLength<this.writableHighWaterMark;return F||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:t,encoding:N,callback:C}):this._doWrite(t,N,C),F}_doEnd(t,n,S){t!=null&&this.write(t,n),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=S,this._maybeFinish()}end(t,n,S){return typeof t==`function`&&(S=t,t=void 0),typeof n==`function`&&(S=n,n=void 0),this.writableEnded?(S&&nextTick(S),this):this._writableState.constructed?(this._doEnd(t,n,S),this):(this._pendingEnd={chunk:t,encoding:n,callback:S},this)}cork(){this.writableCorked++}uncork(){this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._corkedBuffer.length>0&&this._flushCorkedBuffer())}_flushCorkedBuffer(){if(this._writev&&this._corkedBuffer.length>1){let t=this._corkedBuffer.splice(0),n=t.map(t=>({chunk:t.chunk,encoding:t.encoding}));this._writev.call(this,n,n=>{for(let n of t)this.writableLength-=this.writableObjectMode?1:chunkLen(n.chunk);if(n){for(let S of t)S.callback(n);this.emit(`error`,n)}else{for(let n of t)n.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let t=this._corkedBuffer.splice(0);if(t.length>0){let[n,...S]=t;this._writeBuffer.push(...S),this._doWrite(n.chunk,n.encoding,n.callback)}}}setDefaultEncoding(t){return this._defaultEncoding=t,this}destroy(t){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,t&&(this._err=t);let n=!1,cb=t=>{n||(n=!0,t&&nextTick(()=>this.emit(`error`,t)),nextTick(()=>this.emit(`close`)))};try{this._destroy(t??null,cb)}catch(t){cb(t)}return this}},Ri.prototype[ki]=function(){return streamAsyncDispose(this,this.writableFinished)}}),Bi,Vi=__esmMin(()=>{Ii(),ze(),Bi=class Transform_ extends Duplex_{constructor(t){super({...t,write:void 0,final:void 0});let n=this;t?.transform&&(n._transform=t.transform),t?.flush&&(n._flush=t.flush),t?.final&&(n._final=t.final)}_transform(t,n,S){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(t){t()}_write(t,n,S){let C=!1;try{this._transform(t,n,(t,n)=>{if(C){let t=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});nextTick(()=>this.emit(`error`,t));return}if(C=!0,t){S(t);return}n!=null&&this.push(n),S()})}catch(t){if(t?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw t;S(t)}}_final(t){this._flush((n,S)=>{if(n){t(n);return}S!=null&&this.push(S),this.push(null),t()})}_doPrefinishHooks(t){let n=Transform_.prototype._final;this._final===n?t():n.call(this,t)}}}),PassThrough_,Hi=__esmMin(()=>{Vi(),PassThrough_=class extends Bi{constructor(t){super({...t,transform(t,n,S){S(null,t)}})}}});function pipeline$1(...t){let n=t,S=typeof n[n.length-1]==`function`?n.pop():void 0,C=n;if(C.length<2)throw Error(`pipeline requires at least 2 streams`);let N=null;function onError(t){if(!N){N=t;for(let t of C)typeof t.destroy==`function`&&t.destroy();S&&S(t)}}let F=C[0];for(let t=1;t<C.length;t++){let n=C[t];F.pipe(n),F.on(`error`,onError),F=n}let I=C[C.length-1];return I.on(`error`,onError),I.on(`finish`,()=>{S&&!N&&S(null)}),I}var Ui=__esmMin(()=>{__name$1(pipeline$1,`pipeline`)});function pipeline(...t){return new Promise((n,S)=>{let cb=t=>{t?S(t):n()};pipeline$1(...t,cb)})}function finished(t,n){return new Promise((S,C)=>{n&&typeof n!=`function`?finished$1(t,n,t=>{t?C(t):S()}):finished$1(t,t=>{t?C(t):S()})})}var Wi,Gi,Ki=__esmMin(()=>{Si(),Ti(),Ui(),Wi=xi({default:()=>Gi,finished:()=>finished,pipeline:()=>pipeline}),Gi={pipeline,finished}}),qi=__exportAll$5({Duplex:()=>Zi,PassThrough:()=>$i,Readable:()=>Yi,Stream:()=>Ji,Transform:()=>Qi,Writable:()=>Xi,addAbortSignal:()=>addAbortSignal,default:()=>ea,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>ea,pipeline:()=>pipeline$1,promises:()=>Wi,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta=__esmMin(()=>{yi(),wi(),Ti(),Oi(),Pi(),Ii(),Li(),zi(),Vi(),Hi(),Ui(),Ki(),Ji=makeCallable(Stream_),Yi=makeCallable(ji),Xi=makeCallable(Ri),Zi=makeCallable(Duplex_),Qi=makeCallable(Bi),$i=makeCallable(PassThrough_),ea=Object.assign(Ji,{Stream:Ji,Readable:Yi,Writable:Xi,Duplex:Zi,Transform:Qi,PassThrough:$i,pipeline:pipeline$1,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark,promises:Wi})});function toUint8Array$2(t){return typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function concat$1(t){let n=t.reduce((t,n)=>t+n.length,0),S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}function createGzip(t){return new Gzip(t)}function createGunzip(t){return new Gunzip(t)}function createDeflate(t){return new Deflate(t)}function createInflate(t){return new Inflate(t)}function createDeflateRaw(t){return new DeflateRaw(t)}function createInflateRaw(t){return new InflateRaw(t)}function createUnzip(t){return new Unzip(t)}function createBrotliCompress(t){throw Error(`createBrotliCompress is not supported on GJS (no Brotli in GLib)`)}function createBrotliDecompress(t){throw Error(`createBrotliDecompress is not supported on GJS (no Brotli in GLib)`)}function createZstdCompress(t){let n=Error(`createZstdCompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}function createZstdDecompress(t){let n=Error(`createZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}var ZlibBase,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,na=__esmMin(()=>{di(),vi(),ta(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends Qi{_mode;_chunks=[];constructor(t,n){resolveMaxOutputLength(n),super(n),this._mode=t}_transform(t,n,S){this._chunks.push(toUint8Array$2(t)),S()}_flush(t){let n=concat$1(this._chunks);this._chunks=[];try{this.push(Buffer.from(this._run(n))),t()}catch(n){t(n instanceof Error?n:Error(String(n)))}}_run(t){let n=this._mode;switch(n.kind){case`compress`:return compressWithGio(t,n.format);case`decompress`:return decompressStreamWithGio(t,n.format);case`gunzip`:return gunzipWithGio(t);case`unzip`:return hasGzipMagic(t)?gunzipWithGio(t):decompressStreamWithGio(t,`deflate`)}}},Gzip=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`gzip`},t)}},Gunzip=class extends ZlibBase{constructor(t){super({kind:`gunzip`},t)}},Deflate=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate`},t)}},Inflate=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate`},t)}},DeflateRaw=class extends ZlibBase{constructor(t){super({kind:`compress`,format:`deflate-raw`},t)}},InflateRaw=class extends ZlibBase{constructor(t){super({kind:`decompress`,format:`deflate-raw`},t)}},Unzip=class extends ZlibBase{constructor(t){super({kind:`unzip`},t)}},BrotliCompress=class extends Qi{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends Qi{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends Qi{constructor(){super();let t=Error(`ZstdCompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}},ZstdDecompress=class extends Qi{constructor(){super();let t=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}}}),ra=__exportAll$5({BrotliCompress:()=>BrotliCompress,BrotliDecompress:()=>BrotliDecompress,Deflate:()=>Deflate,DeflateRaw:()=>DeflateRaw,Gunzip:()=>Gunzip,Gzip:()=>Gzip,Inflate:()=>Inflate,InflateRaw:()=>InflateRaw,Unzip:()=>Unzip,ZlibTransform:()=>ZlibBase,ZstdCompress:()=>ZstdCompress,ZstdDecompress:()=>ZstdDecompress,brotliCompress:()=>brotliCompress,brotliCompressSync:()=>brotliCompressSync,brotliDecompress:()=>brotliDecompress,brotliDecompressSync:()=>brotliDecompressSync,constants:()=>aa,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>oa,deflate:()=>deflate,deflateRaw:()=>deflateRaw,deflateRawSync:()=>deflateRawSync,deflateSync:()=>deflateSync,gunzip:()=>gunzip$1,gunzipSync:()=>gunzipSync,gzip:()=>gzip$1,gzipSync:()=>gzipSync,inflate:()=>inflate,inflateRaw:()=>inflateRaw,inflateRawSync:()=>inflateRawSync,inflateSync:()=>inflateSync,unzip:()=>unzip,unzipSync:()=>unzipSync,zstdCompress:()=>zstdCompress,zstdCompressSync:()=>zstdCompressSync,zstdDecompress:()=>zstdDecompress,zstdDecompressSync:()=>zstdDecompressSync});function decompressWithGio(t,n,S){return n===`gzip`?gunzipWithGio(t,S):decompressStreamWithGio(t,n,S)}function unzipFormat(t){return hasGzipMagic(t)?`gzip`:`deflate`}function assertWithinLimit(t,n){if(t.length>n)throw bufferTooLargeError(n);return t}async function runWebTransform(t,n,S=1/0){let C=new ReadableStream({start(n){n.enqueue(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),n.close()}}),N=[],F=0,I=C.pipeThrough(n).getReader();for(;;){let{done:t,value:n}=await I.read();if(t)break;if(F+=n.length,F>S)throw await I.cancel(),bufferTooLargeError(S);N.push(n)}let H=N.reduce((t,n)=>t+n.length,0),W=new Uint8Array(H),q=0;for(let t of N)W.set(t,q),q+=t.length;return W}async function compressWithWeb(t,n){return runWebTransform(t,new CompressionStream(n))}async function decompressWithWeb(t,n,S){return runWebTransform(t,new DecompressionStream(n),S)}function requestedLevel(t){let n=t?.level;if(!(n===void 0||n===-1))return assertLevel(n),n}async function compress(t,n,S,C){return S===void 0&&hasWebCompression()?assertWithinLimit(await compressWithWeb(t,n),C):assertWithinLimit(compressWithGio(t,n,S),C)}async function decompress(t,n,S){if(hasWebCompression()&&S>=ci)try{return await decompressWithWeb(t,n,S)}catch(C){if(n!==`gzip`||isBufferTooLargeError(C))throw C;return decompressWithGio(t,n,S)}return decompressWithGio(t,n,S)}function toUint8Array$1(t){return typeof t==`string`?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function runAsync(t,n,S,C){let N=typeof n==`function`?n:S,F=typeof n==`function`?void 0:n,I=resolveMaxOutputLength(F);C(toUint8Array$1(t),F,I).then(t=>N(null,t),t=>N(t instanceof Error?t:Error(String(t)),new Uint8Array))}function compressAsync(t){return(n,S,C)=>compress(n,t,requestedLevel(S),C)}function decompressAsync(t){return(n,S,C)=>decompress(n,t,C)}function gzip$1(t,n,S){runAsync(t,n,S,compressAsync(`gzip`))}function gunzip$1(t,n,S){runAsync(t,n,S,decompressAsync(`gzip`))}function deflate(t,n,S){runAsync(t,n,S,compressAsync(`deflate`))}function inflate(t,n,S){runAsync(t,n,S,decompressAsync(`deflate`))}function deflateRaw(t,n,S){runAsync(t,n,S,compressAsync(`deflate-raw`))}function inflateRaw(t,n,S){runAsync(t,n,S,decompressAsync(`deflate-raw`))}function unzip(t,n,S){runAsync(t,n,S,(t,n,S)=>decompress(t,unzipFormat(t),S))}function compressSync(t,n,S){let C=resolveMaxOutputLength(S);return assertWithinLimit(compressWithGio(toUint8Array$1(t),n,S?.level??-1),C)}function gzipSync(t,n){return compressSync(t,`gzip`,n)}function gunzipSync(t,n){return decompressWithGio(toUint8Array$1(t),`gzip`,resolveMaxOutputLength(n))}function deflateSync(t,n){return compressSync(t,`deflate`,n)}function inflateSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate`,resolveMaxOutputLength(n))}function deflateRawSync(t,n){return compressSync(t,`deflate-raw`,n)}function inflateRawSync(t,n){return decompressWithGio(toUint8Array$1(t),`deflate-raw`,resolveMaxOutputLength(n))}function unzipSync(t,n){let S=toUint8Array$1(t);return decompressWithGio(S,unzipFormat(S),resolveMaxOutputLength(n))}function brotliCompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliCompress: Brotli is not supported in this environment`),ia)}function brotliDecompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliDecompress: Brotli is not supported in this environment`),ia)}function brotliCompressSync(t,n){throw Error(`brotliCompressSync: Brotli is not supported in this environment`)}function brotliDecompressSync(t,n){throw Error(`brotliDecompressSync: Brotli is not supported in this environment`)}function zstdCompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdCompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ia)}function zstdDecompress(t,n,S){let C=typeof n==`function`?n:S,N=Error(`zstdDecompress: Zstd is not supported in this environment`);N.code=`ERR_UNSUPPORTED_OPERATION`,C(N,ia)}function zstdCompressSync(t,n){let S=Error(`zstdCompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}function zstdDecompressSync(t,n){let S=Error(`zstdDecompressSync: Zstd is not supported in this environment`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}var hasWebCompression,ia,aa,oa,sa=__esmMin(()=>{di(),vi(),na(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),ia=new Uint8Array,aa={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8},oa={gzip:gzip$1,gunzip:gunzip$1,deflate,inflate,deflateRaw,inflateRaw,unzip,gzipSync,gunzipSync,deflateSync,inflateSync,deflateRawSync,inflateRawSync,unzipSync,brotliCompress,brotliDecompress,brotliCompressSync,brotliDecompressSync,zstdCompress,zstdDecompress,zstdCompressSync,zstdDecompressSync,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,createGzip,createGunzip,createDeflate,createInflate,createDeflateRaw,createInflateRaw,createUnzip,createBrotliCompress,createBrotliDecompress,createZstdCompress,createZstdDecompress,constants:aa}});const ca=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(t){if(!ca.has(t))throw TypeError(`Unsupported compression format: '${t}'. Supported formats: 'gzip', 'deflate', 'deflate-raw'.`);return t}const la=typeof globalThis.CompressionStream==`function`&&typeof globalThis.DecompressionStream==`function`;let ua=!1,da,fa,pa,ma,ha,ga;async function loadZlib(){if(ua)return;let t=await Promise.resolve().then(()=>(sa(),ra));da=t.gzipSync,fa=t.gunzipSync,pa=t.deflateSync,ma=t.inflateSync,ha=t.deflateRawSync,ga=t.inflateRawSync,ua=!0}function getCompressFn(t){switch(t){case`gzip`:return t=>da(t);case`deflate`:return t=>pa(t);case`deflate-raw`:return t=>ha(t)}}function getDecompressFn(t){switch(t){case`gzip`:return t=>fa(t);case`deflate`:return t=>ma(t);case`deflate-raw`:return t=>ga(t)}}function concatChunks$1(t){if(t.length===1)return t[0];let n=0;for(let S of t)n+=S.length;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return S}__name$1(concatChunks$1,`concatChunks`);let _a,va;if(la)_a=globalThis.CompressionStream,va=globalThis.DecompressionStream;else{let t=loadZlib();_a=class CompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getCompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}},va=class DecompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new ri({transform(t){C.push(t)},async flush(n){try{await t;let N=getDecompressFn(S)(concatChunks$1(C));N.length>0&&n.enqueue(N)}catch(t){n.error(t)}}});this.readable=N.readable,this.writable=N.writable}}}const ya=globalThis;globalThis.CompressionStream===void 0&&(ya.CompressionStream=_a),globalThis.DecompressionStream===void 0&&(ya.DecompressionStream=va);const ba=globalThis;globalThis.DOMException===void 0&&(ba.DOMException=tr);var xa,__name,Sa=__esmMin(()=>{xa=Object.defineProperty,__name=(t,n)=>xa(t,`name`,{value:n,configurable:!0})});function validateHeaderName(t){if(typeof t!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let n=TypeError(`Header name must be a valid HTTP token ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),n}}function validateHeaderValue(t,n){if(n===void 0){let n=TypeError(`Header "${t}" value must not be undefined`);throw Object.defineProperty(n,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),n}if(typeof n==`string`&&/[^\t -~€-ÿ]/.test(n)){let n=TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:`ERR_INVALID_CHAR`}),n}}const Ca=Symbol(`Headers.headers`);function isBoxedPrimitive$2(t){return t instanceof String||t instanceof Number||t instanceof Boolean||typeof Symbol<`u`&&t instanceof Symbol||typeof BigInt<`u`&&t instanceof BigInt}__name$1(isBoxedPrimitive$2,`isBoxedPrimitive`);var wa=class Headers{[Ca];constructor(t){if(this[Ca]=new Map,t!=null){if(t instanceof Headers){for(let[n,S]of t[Ca])this[Ca].set(n,[...S]);return}if(typeof t==`object`&&!isBoxedPrimitive$2(t)){let n=t[Symbol.iterator];if(n==null)for(let[n,S]of Object.entries(t))validateHeaderName(n),validateHeaderValue(n,String(S)),this.append(n,String(S));else{if(typeof n!=`function`)throw TypeError(`Header pairs must be iterable`);for(let n of t){if(typeof n!=`object`||isBoxedPrimitive$2(n))throw TypeError(`Each header pair must be an iterable object`);let t=[...n];if(t.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(t[0]),validateHeaderValue(t[0],String(t[1])),this.append(t[0],String(t[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase(),C=String(n),N=this[Ca].get(S);N?N.push(C):this[Ca].set(S,[C])}set(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase();this[Ca].set(S,[String(n)])}delete(t){this[Ca].delete(String(t).toLowerCase())}has(t){return this[Ca].has(String(t).toLowerCase())}get(t){let n=this[Ca].get(String(t).toLowerCase());if(!n||n.length===0)return null;let S=n.join(`, `);return/^content-encoding$/i.test(t)&&(S=S.toLowerCase()),S}getAll(t){return this[Ca].get(String(t).toLowerCase())??[]}getSetCookie(){return this[Ca].get(`set-cookie`)??[]}forEach(t,n){for(let S of this.keys())Reflect.apply(t,n,[this.get(S),S,this])}*keys(){let t=[...this[Ca].keys()].sort(),n=new Set;for(let S of t)n.has(S)||(n.add(S),yield S)}*values(){for(let t of this.keys())yield this.get(t)}*entries(){for(let t of this.keys())yield[t,this.get(t)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let t={};for(let n of this.keys())t[n]=this.getAll(n);return t}_appendToSoupMessage(t,n,S=t.MessageHeadersType.REQUEST){let C=n?n.get_request_headers():new t.MessageHeaders(S);for(let[t,n]of this.entries())C.append(t,n);return C}static _newFromSoupMessage(t,n,S=t.MessageHeadersType.RESPONSE){let C=new Headers,N;return N=S===t.MessageHeadersType.RESPONSE?n.get_response_headers():n.get_request_headers(),N.foreach((t,n)=>{C.append(t,n)}),C}[Symbol.for(`nodejs.util.inspect.custom`)](){let t={};for(let n of this.keys()){let S=this.getAll(n);n===`host`?t[n]=S[0]:t[n]=S.length>1?S:S[0]}return t}};Object.defineProperties(wa.prototype,[`get`,`entries`,`forEach`,`values`].reduce((t,n)=>(t[n]={enumerable:!0},t),{}));var Ta=__esmMin(()=>{ot()});Ta();var FetchBaseError=class extends Error{type;constructor(t,n){super(t),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(t,n,S){super(t,n),S&&(this.code=this.errno=S.code,this.erroredSysCall=S.syscall)}};Hn();const Ea=Symbol.toStringTag,isURLSearchParameters=t=>typeof t==`object`&&typeof t.append==`function`&&typeof t.delete==`function`&&typeof t.get==`function`&&typeof t.getAll==`function`&&typeof t.has==`function`&&typeof t.set==`function`&&typeof t.sort==`function`&&t[Ea]===`URLSearchParams`,isBlob=t=>{if(!t||typeof t!=`object`)return!1;let n=t;return typeof n.arrayBuffer==`function`&&typeof n.type==`string`&&typeof n.stream==`function`&&typeof n.constructor==`function`&&/^(Blob|File)$/.test(n[Ea])},isAbortSignal=t=>{if(typeof t!=`object`||!t)return!1;let n=t;return n[Ea]===`AbortSignal`||n[Ea]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let S=new Bn(n).hostname,C=new Bn(t).hostname;return S===C||S.endsWith(`.${C}`)},isSameProtocol=(t,n)=>new Bn(n).protocol===new Bn(t).protocol;var Da,Oa,File,ka=__esmMin(()=>{Da=Symbol(`File.name`),Oa=Symbol(`File.lastModified`),File=class extends Blob{[Da];[Oa];webkitRelativePath=``;constructor(t,n,S){super(t,S),this[Da]=String(n),this[Oa]=S?.lastModified??Date.now()}get name(){return this[Da]}get lastModified(){return this[Oa]}get[Symbol.toStringTag](){return`File`}}});function generateBoundary(){let t=`----formdata-`;for(let n=0;n<24;n++)t+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return t}function escape(t){return t.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`)}function formDataToBlob(t,n){n??=generateBoundary();let S=[],C=`--${n}\r\nContent-Disposition: form-data; name="`;for(let[n,N]of t.entries())if(typeof N==`string`)S.push(`${C}${escape(n)}"\r\n\r\n${N.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
12
12
  `)}\r\n`);else{let t=N instanceof File?N:new File([N],`blob`,{type:N.type});S.push(`${C}${escape(n)}"; filename="${escape(t.name)}"\r\nContent-Type: ${t.type||`application/octet-stream`}\r\n\r\n`),S.push(t),S.push(`\r
13
13
  `)}return S.push(`--${n}--`),new Blob(S,{type:`multipart/form-data; boundary=${n}`})}var Aa=__esmMin(()=>{ka()});function normalizeValue(t,n,S){return typeof n==`string`?n:(n instanceof Blob&&!(n instanceof File)&&(n=new File([n],S??`blob`,{type:n.type})),n instanceof File&&S!==void 0&&(n=new File([n],S,{type:n.type,lastModified:n.lastModified})),n)}var ja,FormData,Ma=__esmMin(()=>{ka(),ja=Symbol(`FormData.entries`),FormData=class{[ja]=[];constructor(){}append(t,n,S){this[ja].push({name:String(t),value:normalizeValue(t,n,S)})}delete(t){let n=String(t);this[ja]=this[ja].filter(t=>t.name!==n)}get(t){let n=String(t),S=this[ja].find(t=>t.name===n);return S?S.value:null}getAll(t){let n=String(t);return this[ja].filter(t=>t.name===n).map(t=>t.value)}has(t){let n=String(t);return this[ja].some(t=>t.name===n)}set(t,n,S){let C=String(t),N=normalizeValue(C,n,S),F=!1;this[ja]=this[ja].filter(t=>t.name===C?F?!1:(F=!0,t.value=N,!0):!0),F||this[ja].push({name:C,value:N})}forEach(t,n){for(let S of this[ja])t.call(n,S.value,S.name,this)}*entries(){for(let t of this[ja])yield[t.name,t.value]}*keys(){for(let t of this[ja])yield t.name}*values(){for(let t of this[ja])yield t.value}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`FormData`}}}),Na=__esmMin(()=>{Aa(),Ma()}),Pa=__exportAll$5({toFormData:()=>toFormData});function _fileName(t){let n=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!n)return;let S=n[2]||n[3]||``,C=S.slice(S.lastIndexOf(`\\`)+1);return C=C.replace(/%22/g,`"`),C=C.replace(/&#(\d{4});/g,(t,n)=>String.fromCharCode(n)),C}async function toFormData(t,n){if(!/multipart/i.test(n))throw TypeError(`Failed to fetch`);let S=n.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!S)throw TypeError(`no or bad content-type header, no multipart boundary`);let C=new MultipartParser(S[1]||S[2]),N,F,I,H,W,q,Y=[],X=new FormData,onPartData=t=>{I+=Z.decode(t,{stream:!0})},appendToFile=t=>{Y.push(t)},appendFileToFormData=()=>{let t=new ne(Y,q,{type:W});X.append(H,t)},appendEntryToFormData=()=>{X.append(H,I)},Z=new TextDecoder(`utf-8`);Z.decode(),C.onPartBegin=function(){C.onPartData=onPartData,C.onPartEnd=appendEntryToFormData,N=``,F=``,I=``,H=``,W=``,q=null,Y.length=0},C.onHeaderField=function(t){N+=Z.decode(t,{stream:!0})},C.onHeaderValue=function(t){F+=Z.decode(t,{stream:!0})},C.onHeaderEnd=function(){if(F+=Z.decode(),N=N.toLowerCase(),N===`content-disposition`){let t=F.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);t&&(H=t[2]||t[3]||``),q=_fileName(F),q&&(C.onPartData=appendToFile,C.onPartEnd=appendFileToFormData)}else N===`content-type`&&(W=F);F=``,N=``};for await(let n of t)C.write(n);return C.end(),X}var Fa,Ia,lower,noop,MultipartParser,La=__esmMin(()=>{Na(),Fa=1,Ia={PART_BOUNDARY:Fa,LAST_BOUNDARY:Fa*=2},lower=t=>t|32,noop=(...t)=>{},MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=noop;onHeaderField=noop;onHeadersEnd=noop;onHeaderValue=noop;onPartBegin=noop;onPartData=noop;onPartEnd=noop;boundaryChars={};constructor(t){t=`\r
14
- --`+t;let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S),this.boundaryChars[n[S]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(t){let n=0,S=t.length,C=this.index,{lookbehind:N,boundary:F,boundaryChars:I,index:H,state:W,flags:q}=this,Y=this.boundary.length,X=Y-1,Z=t.length,te,ne,mark=t=>{this[t+`Mark`]=n},clear=t=>{delete this[t+`Mark`]},callback=(t,n,S,C)=>{(n===void 0||n!==S)&&this[t](C&&C.subarray(n,S))},dataCallback=(S,C=!1)=>{let N=S+`Mark`;N in this&&(C?(callback(S,this[N],n,t),delete this[N]):(callback(S,this[N],t.length,t),this[N]=0))};for(n=0;n<S;n++)switch(te=t[n],W){case 0:if(H===F.length-2){if(te===45)q|=Ia.LAST_BOUNDARY;else if(te!==13)return;H++;break}else if(H-1==F.length-2){if(q&Ia.LAST_BOUNDARY&&te===45)W=9,q=0;else if(!(q&Ia.LAST_BOUNDARY)&&te===10)H=0,callback(`onPartBegin`),W=1;else return;break}te!==F[H+2]&&(H=-2),te===F[H+2]&&H++;break;case 1:W=2,mark(`onHeaderField`),H=0;case 2:if(te===13){clear(`onHeaderField`),W=6;break}if(H++,te===45)break;if(te===58){if(H===1)return;dataCallback(`onHeaderField`,!0),W=3;break}if(ne=lower(te),ne<97||ne>122)return;break;case 3:if(te===32)break;mark(`onHeaderValue`),W=4;case 4:te===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),W=5);break;case 5:if(te!==10)return;W=1;break;case 6:if(te!==10)return;callback(`onHeadersEnd`),W=7;break;case 7:W=8,mark(`onPartData`);case 8:if(C=H,H===0){for(n+=X;n<Z&&!(t[n]in I);)n+=Y;n-=X,te=t[n]}if(H<F.length)F[H]===te?(H===0&&dataCallback(`onPartData`,!0),H++):H=0;else if(H===F.length)H++,te===13?q|=Ia.PART_BOUNDARY:te===45?q|=Ia.LAST_BOUNDARY:H=0;else if(H-1===F.length)if(q&Ia.PART_BOUNDARY){if(H=0,te===10){q&=~Ia.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),W=1;break}}else q&Ia.LAST_BOUNDARY&&te===45?(callback(`onPartEnd`),W=9,q=0):H=0;if(H>0)N[H-1]=te;else if(C>0){let t=new Uint8Array(N.buffer,N.byteOffset,N.byteLength);callback(`onPartData`,0,C,t),C=0,mark(`onPartData`),n--}break;case 9:break;default:throw Error(`Unexpected state entered: ${W}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=H,this.state=W,this.flags=q}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}});_e(),Sa(),Ta(),Hn(),ot(),ta(),Na(),__name((t,n)=>new Promise((S,C)=>{pipeline$1(t,n,t=>{t?C(t):S()})}),`pipeline`);const Ra=Symbol(`Body internals`);function isAnyArrayBuffer$2(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer}__name$1(isAnyArrayBuffer$2,`isAnyArrayBuffer`);var Body=class{[Ra]={body:null,stream:null,webStream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(t,n={size:0}){if(this.size=n.size||0,t==null)this[Ra].body=null;else if(isURLSearchParameters(t))this[Ra].body=Xe.from(t.toString());else if(isBlob(t))this[Ra].body=t;else if(Xe.isBuffer(t))this[Ra].body=t;else if(isAnyArrayBuffer$2(t))this[Ra].body=Xe.from(t);else if(ArrayBuffer.isView(t))this[Ra].body=Xe.from(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof Yi)this[Ra].body=t;else if(typeof ReadableStream<`u`&&t instanceof ReadableStream)this[Ra].body=readableStreamToReadable(t);else if(t instanceof FormData){let n=formDataToBlob(t);this[Ra].body=n,this[Ra].boundary=n.type?.split(`boundary=`)?.[1]??``}else typeof t==`string`?this[Ra].body=Xe.from(t):t instanceof Fn?this[Ra].body=Xe.from(t.toString()):(ge.warn(`Unknown body type "${typeof t}", try to parse the body to string!`),this[Ra].body=Xe.from(String(t)));let S=this[Ra].body;Xe.isBuffer(S)?this[Ra].stream=Yi.from(S):isBlob(S)?this[Ra].stream=Yi.from(blobToAsyncIterable(S)):S instanceof Yi&&(this[Ra].stream=S),S instanceof Ji&&S.on(`error`,t=>{let n=t instanceof FetchBaseError?t:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${t.message}`,`system`,t);this[Ra].error=n})}get body(){let t=this[Ra].stream;if(!t)return null;let n=this[Ra].webStream;if(n)return n;if(typeof ReadableStream<`u`){let n=!1,S=new ReadableStream({start(S){t.on(`data`,t=>{if(!n)try{S.enqueue(t instanceof Uint8Array?t:new Uint8Array(t))}catch{}}),t.on(`end`,()=>{if(!n){n=!0;try{S.close()}catch{}}}),t.on(`error`,t=>{if(!n){n=!0;try{S.error(t)}catch{}}})},cancel(){n=!0,t.destroy()}});return this[Ra].webStream=S,S}return null}get _stream(){return this[Ra].stream}get _rawBodyBuffer(){let t=this[Ra].body;return t===null?null:Xe.isBuffer(t)?t:t instanceof Uint8Array?Xe.from(t.buffer,t.byteOffset,t.byteLength):null}get bodyUsed(){return this[Ra].disturbed}async arrayBuffer(){let{buffer:t,byteOffset:n,byteLength:S}=await consumeBody(this);return t.slice(n,n+S)}async formData(){let t=this.headers?.get(`content-type`);if(t?.startsWith(`application/x-www-form-urlencoded`)){let t=new FormData,n=new Fn(await this.text());for(let[S,C]of n)t.append(S,C);return t}let{toFormData:n}=await Promise.resolve().then(()=>(La(),Pa));return n(this.body,t)}async blob(){let t=this.headers?.get(`content-type`)||this[Ra].body&&this[Ra].body.type||``;return new te([await this.arrayBuffer()],{type:t})}async json(){let t=await this.text();return JSON.parse(t)}async text(){let t=await consumeBody(this);return new TextDecoder().decode(t)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(t){if(t[Ra].disturbed)throw TypeError(`body used already for: ${t.url}`);if(t[Ra].disturbed=!0,t[Ra].error)throw t[Ra].error;let{_stream:n}=t;if(n===null||!(n instanceof Ji))return Xe.alloc(0);let S=[],C=0;try{for await(let N of n){if(t.size>0&&C+N.length>t.size){let S=new FetchError(`content size at ${t.url} over limit: ${t.size}`,`max-size`);throw n.destroy(S),S}C+=N.length,S.push(N)}}catch(n){let S=n instanceof Error?n:Error(String(n));throw n instanceof FetchBaseError?n:new FetchError(`Invalid response body while trying to fetch ${t.url}: ${S.message}`,`system`,S)}try{return S.every(t=>typeof t==`string`)?Xe.from(S.join(``)):Xe.concat(S,C)}catch(n){let S=n instanceof Error?n:Error(String(n));throw new FetchError(`Could not create Buffer from response body for ${t.url}: ${S.message}`,`system`,S)}}const clone=(t,n)=>{let S,C,{body:N}=t[Ra];if(t.bodyUsed)throw Error(`cannot clone body after it is used`);return N instanceof Ji&&typeof N.getBoundary!=`function`&&(S=new $i({highWaterMark:n}),C=new $i({highWaterMark:n}),N.pipe(S),N.pipe(C),t[Ra].stream=S,N=C),N},extractContentType=(t,n)=>t===null?null:typeof t==`string`?`text/plain;charset=UTF-8`:isURLSearchParameters(t)?`application/x-www-form-urlencoded;charset=UTF-8`:isBlob(t)?t.type||null:Xe.isBuffer(t)||isAnyArrayBuffer$2(t)||ArrayBuffer.isView(t)?null:t instanceof FormData?`multipart/form-data; boundary=${n[Ra].boundary}`:t instanceof Ji?null:`text/plain;charset=UTF-8`,getTotalBytes=t=>{let{body:n}=t[Ra];if(n===null)return 0;if(isBlob(n))return n.size;if(Xe.isBuffer(n))return n.length;if(n&&typeof n.getLengthSync==`function`){let t=n;return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null}return null};function readableStreamToReadable(t){let n=t.getReader();return new Yi({async read(){try{let{done:t,value:S}=await n.read();t?this.push(null):this.push(Xe.from(S))}catch(t){this.destroy(t)}},destroy(t,S){n.cancel().then(()=>S(null),S)}})}async function*blobToAsyncIterable(t){if(typeof t.stream==`function`){let n=t.stream().getReader();for(;;){let{done:t,value:S}=await n.read();if(t)break;yield S}}else yield new Uint8Array(await t.arrayBuffer())}const za=new Set([301,302,303,307,308]),isRedirect=t=>za.has(t);Hn(),ut(),hi();const Ba=Symbol(`Response internals`);var Va=class Response extends Body{[Ba];_inputStream=null;constructor(t=null,n={}){super(t,n);let S=n.status==null?200:n.status,C=new wa(n.headers);if(t!==null&&!C.has(`Content-Type`)){let n=extractContentType(t,this);n&&C.append(`Content-Type`,n)}this[Ba]={type:`default`,url:n.url,status:S,statusText:n.statusText||``,headers:C,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ba].type}get url(){return this[Ba].url||``}get status(){return this[Ba].status}get ok(){return this[Ba].status>=200&&this[Ba].status<300}get redirected(){return this[Ba].counter>0}get statusText(){return this[Ba].statusText}get headers(){return this[Ba].headers}get highWaterMark(){return this[Ba].highWaterMark}clone(){return new Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!isRedirect(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new Bn(t).toString()},status:n})}static error(){let t=new Response(null,{status:0,statusText:``});return t[Ba].type=`error`,t}static json(t,n){let S=JSON.stringify(t),C={...n},N=new wa(C.headers);return N.has(`content-type`)||N.set(`content-type`,`application/json`),C.headers=N,new Response(S,C)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let t=mi.MemoryOutputStream.new_resizable();await new Promise((n,S)=>{t.splice_async(this._inputStream,mi.OutputStreamSpliceFlags.CLOSE_TARGET|mi.OutputStreamSpliceFlags.CLOSE_SOURCE,lt.PRIORITY_DEFAULT,null,(C,N)=>{try{n(t.splice_finish(N))}catch(t){S(t)}})});let n=t.steal_as_bytes();return new TextDecoder().decode(n.toArray())}};Object.defineProperties(Va.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function gbytesToUint8Array(t){return t.toArray()}var Ha=__esmMin(()=>{}),Ua,cli,Wa=__esmMin(()=>{ut(),Ua=new TextDecoder,cli=t=>{let[n,S,C,N]=lt.spawn_command_line_sync(t);if(C.byteLength)throw Error(Ua.decode(C));return Ua.decode(S)}}),Ga,readJSON,Ka=__esmMin(()=>{ut(),Ga=new TextDecoder,readJSON=t=>{let[n,S]=lt.file_get_contents(t);if(n)return JSON.parse(Ga.decode(S));throw Error(`Error on require "${t}"`)}}),qa,Ja=__esmMin(()=>{qa=S}),Ya,Xa=__esmMin(()=>{Ja(),Ya=qa});function existsSync(t){return typeof t!=`string`||t===``?!1:mi.File.new_for_path(t).query_exists(null)}var Za=__esmMin(()=>{hi(),Xa()});async function readBytesAsync(t,n=4096,S=lt.PRIORITY_DEFAULT,C=null){return new Promise((N,F)=>{t.read_bytes_async(n,S,C,(n,S)=>{try{let n=t.read_bytes_finish(S);return n.get_size()===0?N(null):N(gbytesToUint8Array(n))}catch(t){let n=t;if(typeof n.matches==`function`&&(n.matches(mi.IOErrorEnum,mi.IOErrorEnum.PARTIAL_INPUT)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.CONNECTION_CLOSED)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.BROKEN_PIPE)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.CLOSED)))return N(null);F(t)}})})}async function*inputStreamAsyncIterator(t,n=4096,S=lt.PRIORITY_DEFAULT,C=null){let N;for(;(N=await readBytesAsync(t,n,S,C))!==null;)yield N}var Qa=__esmMin(()=>{Ha(),ut(),hi()}),$a,eo,getPathSeparator,to=__esmMin(()=>{ut(),hi(),{File:$a}=mi,eo=__name$1((t,...n)=>{let S=$a.new_for_path(t);for(let t of n)S=S.resolve_relative_path(t);return S},`resolve`),getPathSeparator=()=>lt.get_current_dir().startsWith(`/`)?`/`:`\\`}),no=__esmMin(()=>{Ha(),Wa(),ae(),Me(),Ka(),Za(),Qa(),to()});ta(),ut(),hi(),no();async function soupSendAsync(t,n,S=lt.PRIORITY_DEFAULT,C=null){return new Promise((N,F)=>{let I=!1,onCancel=()=>{I||(I=!0,F(new mi.IOErrorEnum({code:mi.IOErrorEnum.CANCELLED,message:`Operation was cancelled`})))},H=C?C.connect(onCancel):0;I||t.send_async(n,S,C,(n,S)=>{H&&C.disconnect(H);let W;try{W=t.send_finish(S)}catch(t){I||(I=!0,F(t));return}if(I){closeInputStream(W);return}I=!0,N(W)})})}function closeInputStream(t){return new Promise(n=>{t.close_async(lt.PRIORITY_DEFAULT,null,(S,C)=>{try{t.close_finish(C)}catch{}n()})})}function inputStreamToReadable(t,n={}){let S=new mi.Cancellable,C=null,close=()=>C||(t.has_pending()?Promise.resolve():(C=closeInputStream(t),C));async function*chunks(){try{yield*inputStreamAsyncIterator(t,4096,lt.PRIORITY_DEFAULT,S)}finally{await close()}}let N=Yi.from(chunks(),n);return N.once(`close`,()=>{t.has_pending()?S.cancel():close()}),N}let ro=null;async function loadSoup(){return ro??=(await import(`gi://Soup?version=3.0`)).default}function isIP(t){if(typeof t!=`string`)return 0;let n=t.includes(`%`)?t.slice(0,t.indexOf(`%`)):t,S=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(n);if(S)return S.slice(1).every(t=>(t.length===1||t[0]!==`0`)&&Number(t)<=255)?4:0;if(n.length===0||!n.includes(`:`))return 0;let C=/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(n),N=C?n.slice(0,n.length-C[0].length):n;if(C&&isIP(C[1])!==4)return 0;let F=N.split(`::`);if(F.length>2)return 0;let I=0;for(let t of F)if(t!==``)for(let n of t.split(`:`)){if(!/^[0-9a-fA-F]{1,4}$/.test(n))return 0;I++}let H=C?6:8;return F.length===2?I<H?6:0:I===H?6:0}hi(),ut(),ta(),hi(),qt(),Hn();function stripURLForUseAsAReferrer(t,n=!1){if(t==null||t===`no-referrer`)return`no-referrer`;let S=new Bn(t);return/^(about|blob|data):$/.test(S.protocol)?`no-referrer`:(S.username=``,S.password=``,S.hash=``,n&&(S.pathname=``,S.search=``),S)}const io=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]);function validateReferrerPolicy(t){if(!io.has(t))throw TypeError(`Invalid referrerPolicy: ${t}`);return t}function isOriginPotentiallyTrustworthy(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let n=t.host.replace(/(^\[)|(]$)/g,``),S=isIP(n);return S===4&&n.startsWith(`127.`)||S===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(n)?!0:t.host===`localhost`||t.host.endsWith(`.localhost`)?!1:t.protocol===`file:`}function isUrlPotentiallyTrustworthy(t){return/^about:(blank|srcdoc)$/.test(t.toString())||(typeof t==`string`&&(t=new Bn(t)),t.protocol===`data:`)||/^(blob|filesystem):$/.test(t.protocol)?!0:isOriginPotentiallyTrustworthy(t)}function determineRequestsReferrer(t,n={}){let{referrerURLCallback:S,referrerOriginCallback:C}=n;if(t.referrer===`no-referrer`||t.referrerPolicy===``)return null;let N=t.referrerPolicy;if(t.referrer===`about:client`)return`no-referrer`;let F=new Bn(t.referrer),I=stripURLForUseAsAReferrer(F),H=stripURLForUseAsAReferrer(F,!0);I.toString().length>4096&&(I=H),S&&(I=S(I)),C&&(H=C(H));let W=new Bn(t.url);switch(N){case`no-referrer`:return`no-referrer`;case`origin`:return H;case`unsafe-url`:return I;case`strict-origin`:return isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:H.toString();case`strict-origin-when-cross-origin`:return I.origin===W.origin?I:isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:H;case`same-origin`:return I.origin===W.origin?I:`no-referrer`;case`origin-when-cross-origin`:return I.origin===W.origin?I:H;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:I;default:throw TypeError(`Invalid referrerPolicy: ${N}`)}}function parseReferrerPolicyFromHeader(t){let n=(t.get(`referrer-policy`)||``).split(/[,\s]+/),S=``;for(let t of n)t&&io.has(t)&&(S=t);return S}Hn(),ut(),hi();const ao=Symbol(`Request internals`);let oo=null;function envPositiveInt(t,n){let S=lt.getenv(t);if(!S)return n;let C=Number.parseInt(S,10);return Number.isFinite(C)&&C>0?C:n}function shouldAcceptAnyCert(t){return t===!1?!0:t===!0?!1:lt.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)===`0`}function getSharedSession(t){if(oo===null){let n=envPositiveInt(`GJSIFY_FETCH_MAX_CONNS_PER_HOST`,16),S=Math.max(envPositiveInt(`GJSIFY_FETCH_MAX_CONNS`,64),n);oo=new t.Session({maxConns:S,maxConnsPerHost:n}),oo.remove_feature_by_type(t.ContentDecoder.$gtype)}return oo}const isRequest=t=>typeof t==`object`&&typeof t.url==`string`;var so=class Request extends Body{cache;credentials;destination;get headers(){return this[ao].headers}integrity;keepalive;get method(){return this[ao].method}mode;get redirect(){return this[ao].redirect}get referrer(){if(this[ao].referrer===`no-referrer`)return``;if(this[ao].referrer===`client`)return`about:client`;if(this[ao].referrer)return this[ao].referrer.toString()}get referrerPolicy(){return this[ao].referrerPolicy}set referrerPolicy(t){this[ao].referrerPolicy=validateReferrerPolicy(t)}get signal(){return this[ao].signal}get url(){return this[ao].parsedURL.toString()}get _uri(){return lt.Uri.parse(this.url,lt.UriFlags.ENCODED)}get _session(){return this[ao].session}get _message(){return this[ao].message}get _inputStream(){return this[ao].inputStream}get[Symbol.toStringTag](){return`Request`}[ao];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;constructor(t,n){let S=t,C=n||{},N,F={};if(isRequest(t)?(N=new Bn(S.url),F=S):N=new Bn(t),N.username!==``||N.password!==``)throw TypeError(`${N} is an url with embedded credentials.`);let I=C.method||F.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(I)&&(I=I.toUpperCase()),(n?.body!=null||isRequest(t)&&S.body!==null)&&(I===`GET`||I===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let H=n?.body?n.body:isRequest(t)&&S.body!==null?clone(t):null;super(H,{size:C.size||0});let W=new wa(n?.headers||S.headers||{});if(H!==null&&!W.has(`Content-Type`)){let t=extractContentType(H,this);t&&W.set(`Content-Type`,t)}let q=isRequest(t)?S.signal:null;if(n&&`signal`in n&&(q=n.signal),q!=null&&!isAbortSignal(q))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let Y=n?.referrer==null?S.referrer:n.referrer;if(Y===``)Y=`no-referrer`;else if(Y){let t=new Bn(Y);Y=/^about:(\/\/)?client$/.test(t.toString())?`client`:t}else Y=void 0;this[ao]={method:I,redirect:n?.redirect||S.redirect||`follow`,headers:W,parsedURL:N,signal:q,referrer:Y,referrerPolicy:``,session:null,message:null},this.follow=C.follow===void 0?S.follow===void 0?20:S.follow:C.follow,this.compress=C.compress===void 0?S.compress===void 0?!0:S.compress:C.compress,this.counter=C.counter||S.counter||0,this.agent=C.agent||S.agent,this.highWaterMark=C.highWaterMark||S.highWaterMark||16384,this.insecureHTTPParser=C.insecureHTTPParser||S.insecureHTTPParser||!1,this.rejectUnauthorized=C.rejectUnauthorized??S.rejectUnauthorized,this.referrerPolicy=n?.referrerPolicy||S.referrerPolicy||``}async _send(t){let{signal:n,parsedURL:S}=this[ao],C=S.protocol;if(C!==`http:`&&C!==`https:`)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);let N=await loadSoup(),F=getSharedSession(N),I=new N.Message({method:this[ao].method,uri:lt.Uri.parse(S.toString(),lt.UriFlags.ENCODED)});this[ao].session=F,this[ao].message=I,t.headers._appendToSoupMessage(N,I);let H=this._rawBodyBuffer;if(H!==null&&H.byteLength>0){let n=t.headers.get(`content-type`)||null;I.set_request_body_from_bytes(n,new lt.Bytes(H))}S.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&I.connect(`accept-certificate`,(t,n,S)=>!0);let W=new mi.Cancellable;return n&&(n.aborted?W.cancel():n.addEventListener(`abort`,()=>W.cancel(),{once:!0})),this[ao].inputStream=await soupSendAsync(F,I,lt.PRIORITY_DEFAULT,W),this[ao].readable=inputStreamToReadable(this[ao].inputStream),{inputStream:this[ao].inputStream,readable:this[ao].readable,cancellable:W}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(so.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=t=>{let{parsedURL:n}=t[ao],S=new wa(t[ao].headers);S.has(`Accept`)||S.set(`Accept`,`*/*`);let C=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(C=`0`),t.body!==null){let n=getTotalBytes(t);typeof n==`number`&&!Number.isNaN(n)&&(C=String(n))}C&&S.set(`Content-Length`,C),t.referrerPolicy===``&&(t.referrerPolicy=`strict-origin-when-cross-origin`),t.referrer&&t.referrer!==`no-referrer`?t[ao].referrer=determineRequestsReferrer(t):t[ao].referrer=`no-referrer`,t[ao].referrer instanceof Bn&&S.set(`Referer`,t.referrer),S.has(`User-Agent`)||S.set(`User-Agent`,`gjsify-fetch`),t.compress&&!S.has(`Accept-Encoding`)&&S.set(`Accept-Encoding`,`gzip, deflate`);let{agent:N}=t;return typeof N==`function`&&(N=N(n)),!S.has(`Connection`)&&!N&&S.set(`Connection`,`close`),{parsedURL:n,options:{headers:S}}};var AbortError=class extends FetchBaseError{constructor(t,n=`aborted`){super(t,n)}};function parseDataUri(t){let n=t.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!n)throw TypeError(`Invalid data URI: ${t.slice(0,50)}...`);let S=n[1]||`text/plain;charset=US-ASCII`,C=!!n[2],N=n[3],F;if(C){let t=atob(N);F=new Uint8Array(t.length);for(let n=0;n<t.length;n++)F[n]=t.charCodeAt(n)}else F=new TextEncoder().encode(decodeURIComponent(N));return{buffer:F,typeFull:S}}ze();function rewriteRootRelativeUrl(t,n){if(!t.startsWith(`/`)||t.startsWith(`//`))return t;let S=lastPathSeparatorIndex(n);return S<=0?t:`${pathToFileUrlHref(n.slice(0,S))}${t}`}function resolveRootRelativeUrl(t){return rewriteRootRelativeUrl(t,C.programPath??C.programInvocationName??``)}_e(),Ta(),Hn(),ta(),ut();const co=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteFetchInput(t){if(typeof t!=`string`)return t;let n=resolveRootRelativeUrl(t);return n!==t&&globalThis.__GJSIFY_DEBUG_FETCH===!0&&ge.log(`[fetch] rewrite ${t} → ${n}`),n}async function fetch$1(t,n={}){t=rewriteFetchInput(t);let S=new so(t,n),{parsedURL:C,options:N}=getSoupRequestOptions(S);if(!co.has(C.protocol))throw TypeError(`@gjsify/fetch cannot load ${t}. URL scheme "${C.protocol.replace(/:$/,``)}" is not supported.`);if(C.protocol===`data:`){let{buffer:t,typeFull:n}=parseDataUri(S.url);return new Va(Buffer.from(t),{headers:{"Content-Type":n}})}if(C.protocol===`file:`){let t=globalThis.__GJSIFY_DEBUG_FETCH===!0;t&&ge.log(`[fetch] file:// ${S.url}`);try{let n=lt.filename_from_uri(S.url)[0];t&&ge.log(`[fetch] file:// path=${n}`);let[C,N]=lt.file_get_contents(n);if(t&&ge.log(`[fetch] file:// ok=${C} bytes=${N?.byteLength??`?`}`),!C)throw new FetchError(`Failed to read file: ${n}`,`system`);let F=N,I=new Uint8Array(F.byteLength);I.set(F);let H=new Va(I);return t&&ge.log(`[fetch] file:// response created`),H}catch(n){let C=n instanceof Error?n:Error(String(n));throw t&&ge.warn(`[fetch] file:// FAIL: ${C.message}`),new FetchError(`request to ${S.url} failed, reason: ${C.message}`,`system`,C)}}let{signal:F}=S;if(F&&F.aborted)throw new AbortError(`The operation was aborted.`);let I,H;try{let t=await S._send(N);I=t.readable,H=t.cancellable}catch(t){if(F&&F.aborted)throw new AbortError(`The operation was aborted.`);let n=t instanceof Error?t:Error(String(t));throw new FetchError(`request to ${S.url} failed, reason: ${n.message}`,`system`,n)}let abortHandler=()=>{H.cancel()};F&&F.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{F&&F.removeEventListener(`abort`,abortHandler)};H.connect(()=>{I.destroy(new AbortError(`The operation was aborted.`))}),I.on(`error`,t=>{finalize()});let W=S._message,q=await loadSoup(),Y=wa._newFromSoupMessage(q,W),X=W.status_code,Z=W.get_reason_phrase();if(isRedirect(X)){let t=Y.get(`Location`),C=null;try{C=t===null?null:new Bn(t,S.url)}catch{if(S.redirect!==`manual`)throw I.destroy(),finalize(),new FetchError(`uri requested responds with an invalid redirect URL: ${t}`,`invalid-redirect`)}switch(S.redirect){case`error`:throw I.destroy(),finalize(),new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${S.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(C===null)break;if(S.counter>=S.follow)throw I.destroy(),finalize(),new FetchError(`maximum redirect reached at: ${S.url}`,`max-redirect`);let t={headers:new wa(S.headers),follow:S.follow,counter:S.counter+1,agent:S.agent,compress:S.compress,method:S.method,body:clone(S),signal:S.signal,size:S.size,referrer:S.referrer,referrerPolicy:S.referrerPolicy};if(!isDomainOrSubdomain(S.url,C)||!isSameProtocol(S.url,C))for(let n of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])t.headers.delete(n);if(X!==303&&S.body&&n.body instanceof ea.Readable)throw I.destroy(),finalize(),new FetchError(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(X===303||(X===301||X===302)&&S.method===`POST`)&&(t.method=`GET`,t.body=void 0,t.headers.delete(`content-length`));let N=parseReferrerPolicyFromHeader(Y);return N&&(t.referrerPolicy=N),await new Promise(t=>{I.once(`close`,()=>t()),I.resume()}),finalize(),fetch$1(new so(C,t))}default:throw I.destroy(),finalize(),TypeError(`Redirect option '${S.redirect}' is not a valid value of RequestRedirect`)}}let ne={url:S.url,status:X,statusText:Z,headers:Y,size:S.size,counter:S.counter,highWaterMark:S.highWaterMark},re=Y.get(`Content-Encoding`);if(!S.compress||S.method===`HEAD`||re===null||X===204||X===304)return finalize(),new Va(I,ne);if(typeof DecompressionStream<`u`){let t=null;if(re===`gzip`||re===`x-gzip`?t=`gzip`:(re===`deflate`||re===`x-deflate`)&&(t=`deflate`),t){let n=new te([await new Va(I,ne).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(t));return finalize(),new Va(n,ne)}}return finalize(),new Va(I,ne)}__name$1(fetch$1,`fetch`);const lo=globalThis;globalThis.fetch===void 0&&(lo.fetch=fetch$1),globalThis.Headers===void 0&&(lo.Headers=wa),globalThis.Request===void 0&&(lo.Request=so),globalThis.Response===void 0&&(lo.Response=Va);const uo=globalThis;globalThis.ByteLengthQueuingStrategy===void 0&&(uo.ByteLengthQueuingStrategy=ii),globalThis.CountQueuingStrategy===void 0&&(uo.CountQueuingStrategy=ai);const fo=globalThis;function isNativeStreamUsable$2(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$2,`isNativeStreamUsable`),isNativeStreamUsable$2(globalThis.ReadableStream,`getReader`)||(fo.ReadableStream=ti),fo.ReadableStreamBYOBReader===void 0&&(fo.ReadableStreamBYOBReader=ReadableStreamBYOBReader),fo.ReadableStreamBYOBRequest===void 0&&(fo.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest),fo.ReadableByteStreamController===void 0&&(fo.ReadableByteStreamController=ReadableByteStreamController),fo.ReadableStreamDefaultController===void 0&&(fo.ReadableStreamDefaultController=ReadableStreamDefaultController),fo.ReadableStreamDefaultReader===void 0&&(fo.ReadableStreamDefaultReader=ReadableStreamDefaultReader);const po=globalThis;globalThis.TextEncoderStream===void 0&&(po.TextEncoderStream=oi),globalThis.TextDecoderStream===void 0&&(po.TextDecoderStream=si);function isNativeStreamUsable$1(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}if(__name$1(isNativeStreamUsable$1,`isNativeStreamUsable`),!isNativeStreamUsable$1(globalThis.TransformStream,`readable`)){let t=globalThis;t.TransformStream=ri}function isNativeStreamUsable(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}if(!isNativeStreamUsable(globalThis.WritableStream,`getWriter`)){let t=globalThis;t.WritableStream=ni}var CryptoKey=class{type;extractable;algorithm;usages;_handle;constructor(t,n,S,C,N){this.type=t,this.extractable=n,this.algorithm=Object.freeze({...S}),this.usages=Object.freeze([...C]),this._handle=N}get[Symbol.toStringTag](){return`CryptoKey`}};const mo=Uint8Array.of(166,166,166,166,166,166,166,166);function xorCounter(t,n){for(let S=0;S<8&&n>0;S++)t[7-S]^=n&255,n=Math.floor(n/256)}function aesKeyWrap(t,n){if(t.length<16||t.length%8!=0)throw new DOMException(`AES-KW: key data must be a multiple of 8 bytes and at least 16 bytes`,`OperationError`);let S=t.length/8,C=mo.slice(),N=[];for(let n=0;n<S;n++)N.push(t.slice(n*8,n*8+8));let F=new Uint8Array(16);for(let t=0;t<=5;t++)for(let I=1;I<=S;I++){F.set(C,0),F.set(N[I-1],8);let H=n(F);C.set(H.subarray(0,8)),xorCounter(C,S*t+I),N[I-1]=H.slice(8,16)}let I=new Uint8Array((S+1)*8);I.set(C,0);for(let t=0;t<S;t++)I.set(N[t],(t+1)*8);return I}function aesKeyUnwrap(t,n){if(t.length<24||t.length%8!=0)throw new DOMException(`AES-KW: wrapped key must be a multiple of 8 bytes and at least 24 bytes`,`OperationError`);let S=t.length/8-1,C=t.slice(0,8),N=[];for(let n=0;n<S;n++)N.push(t.slice((n+1)*8,(n+2)*8));let F=new Uint8Array(16);for(let t=5;t>=0;t--)for(let I=S;I>=1;I--){xorCounter(C,S*t+I),F.set(C,0),F.set(N[I-1],8);let H=n(F);C.set(H.subarray(0,8)),N[I-1]=H.slice(8,16)}let I=!0;for(let t=0;t<8;t++)C[t]!==mo[t]&&(I=!1);if(!I)throw new DOMException(`AES-KW: integrity check failed`,`OperationError`);let H=new Uint8Array(S*8);for(let t=0;t<S;t++)H.set(N[t],t*8);return H}function normalizeAlgorithm$1(t){if(typeof t==`string`)return{name:t};if(!t||typeof t.name!=`string`)throw TypeError(`Algorithm must have a name property`);return t}__name$1(normalizeAlgorithm$1,`normalizeAlgorithm`);const ho={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function toNodeHashName(t){let n=ho[t.toUpperCase()]||ho[t];if(!n)throw new tr(`Unrecognized hash name: ${t}`,`NotSupportedError`);return n}const go={"P-256":`prime256v1`,"P-384":`secp384r1`,"P-521":`secp521r1`};function toNodeCurveName(t){let n=go[t];if(!n)throw new tr(`Unrecognized curve name: ${t}`,`NotSupportedError`);return n}function hashSize$1(t){switch(toNodeHashName(t)){case`sha1`:return 20;case`sha256`:return 32;case`sha384`:return 48;case`sha512`:return 64;default:throw new tr(`Unsupported hash: ${t}`,`NotSupportedError`)}}__name$1(hashSize$1,`hashSize`);function validateUsages(t,n){for(let S of t)if(!n.includes(S))throw new tr(`Invalid key usage: ${S}`,`SyntaxError`);if(t.length===0)throw new tr(`Key usages must not be empty`,`SyntaxError`)}function checkUsage(t,n){if(!t.usages.includes(n))throw new tr(`Key does not support the '${n}' usage`,`InvalidAccessError`)}const _o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,vo=new Uint8Array(128);for(let t=0;t<64;t++)vo[_o.charCodeAt(t)]=t;function bytesToBase64$1(t){let n=``,S=t.length;for(let C=0;C<S;C+=3){let N=t[C],F=C+1<S?t[C+1]:0,I=C+2<S?t[C+2]:0;n+=_o[N>>2&63],n+=_o[(N<<4|F>>4)&63],n+=C+1<S?_o[(F<<2|I>>6)&63]:`=`,n+=C+2<S?_o[I&63]:`=`}return n}__name$1(bytesToBase64$1,`bytesToBase64`);function base64ToBytes(t){let n=t;for(;n.endsWith(`=`);)n=n.slice(0,-1);let S=[],C=0,N=0;for(let t=0;t<n.length;t++)N=N<<6|vo[n.charCodeAt(t)],C+=6,C>=8&&(C-=8,S.push(N>>C&255));return new Uint8Array(S)}function base64urlEncode(t){return bytesToBase64$1(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function base64urlDecode(t){let n=t.replace(/-/g,`+`).replace(/_/g,`/`);for(;n.length%4;)n+=`=`;return base64ToBytes(n)}function toUint8Array(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`Expected BufferSource`)}function checkAlgorithmMatch(t,n){if(t.algorithm.name.toUpperCase()!==n.toUpperCase())throw new tr(`Key algorithm mismatch`,`InvalidAccessError`)}const yo={Ed25519:{public:[`verify`],private:[`sign`]},X25519:{public:[],private:[`deriveKey`,`deriveBits`]}},bo={Ed25519:[48,42,48,5,6,3,43,101,112,3,33,0],X25519:[48,42,48,5,6,3,43,101,110,3,33,0]};function cfrgName(t){let n=t.toUpperCase();if(n===`ED25519`)return`Ed25519`;if(n===`X25519`)return`X25519`}function assertUsages(t,n){for(let S of t)if(!n.includes(S))throw new tr(`Unsupported key usage: ${S}`,`SyntaxError`)}function toArrayBuffer(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function keyObjectOf(t){return t._handle.keyObject}function cfrgGenerateKey(t,n,S,C){assertUsages(C,[...yo[n].public,...yo[n].private]);let N=C.filter(t=>yo[n].private.includes(t));if(N.length===0)throw new tr(`Usages cannot be empty when creating a key.`,`SyntaxError`);let F=C.filter(t=>yo[n].public.includes(t)),{publicKey:I,privateKey:H}=t.generateKeyPairSync(n.toLowerCase());return{publicKey:new CryptoKey(`public`,!0,{name:n},F,{keyObject:I}),privateKey:new CryptoKey(`private`,S,{name:n},N,{keyObject:H})}}function validateJwk(t,n,S,C){if(typeof t!=`object`||!t)throw new tr(`Invalid keyData`,`DataError`);if(t.kty!==`OKP`)throw new tr(`Invalid JWK "kty" Parameter`,`DataError`);if(t.crv!==n)throw new tr(`JWK "crv" Parameter and algorithm name mismatch`,`DataError`);if(n===`Ed25519`&&t.alg!==void 0&&t.alg!==`Ed25519`&&t.alg!==`EdDSA`)throw new tr(`JWK "alg" does not match the requested algorithm`,`DataError`);let N=n===`X25519`?`enc`:`sig`;if(C.length>0&&t.use!==void 0&&t.use!==N)throw new tr(`Invalid JWK "use" Parameter`,`DataError`);if(t.key_ops!==void 0){if(!Array.isArray(t.key_ops))throw new tr(`Invalid JWK "key_ops" Parameter`,`DataError`);for(let n of C)if(!t.key_ops.includes(n))throw new tr(`Key operations and usage mismatch`,`DataError`)}if(t.ext===!1&&S)throw new tr(`JWK "ext" Parameter and extractable mismatch`,`DataError`);if(typeof t.x!=`string`||t.d!==void 0&&typeof t.d!=`string`)throw new tr(`Invalid keyData`,`DataError`)}function cfrgImportKey(t,n,S,C,N,F){let I,H,importOrDataError=t=>{try{return t()}catch(t){throw new tr(`Invalid keyData: ${t.message}`,`DataError`)}};switch(n){case`raw`:{assertUsages(F,yo[C].public);let n=toUint8Array(S);if(n.length!==32)throw new tr(`Invalid keyData`,`DataError`);let N=new Uint8Array(44);N.set(bo[C],0),N.set(n,12),I=importOrDataError(()=>t.createPublicKey({key:N,format:`der`,type:`spki`})),H=`public`;break}case`spki`:{assertUsages(F,yo[C].public);let n=toUint8Array(S);I=importOrDataError(()=>t.createPublicKey({key:n,format:`der`,type:`spki`})),H=`public`;break}case`pkcs8`:{assertUsages(F,yo[C].private);let n=toUint8Array(S);I=importOrDataError(()=>t.createPrivateKey({key:n,format:`der`,type:`pkcs8`})),H=`private`;break}case`jwk`:{let n=S;if(validateJwk(n,C,N,F),H=n.d===void 0?`public`:`private`,assertUsages(F,yo[C][H]),H===`private`){if(I=importOrDataError(()=>t.createPrivateKey({key:n,format:`jwk`})),t.createPublicKey(I).export({format:`jwk`}).x!==n.x)throw new tr(`Invalid JWK: "x" does not match "d"`,`DataError`)}else{if(base64urlDecode(n.x).length!==32)throw new tr(`Invalid keyData`,`DataError`);I=importOrDataError(()=>t.createPublicKey({key:n,format:`jwk`}))}break}default:throw new tr(`Unsupported format: ${n}`,`NotSupportedError`)}if(I.asymmetricKeyType!==C.toLowerCase())throw new tr(`Invalid key type`,`DataError`);if(H===`private`&&F.length===0)throw new tr(`Usages cannot be empty when importing a private key.`,`SyntaxError`);return new CryptoKey(H,N,{name:C},F,{keyObject:I})}function wrongKindForFormat(t,n){return new tr(`Unable to export ${t.algorithm.name} ${t.type} key using ${n} format`,`InvalidAccessError`)}function cfrgExportKey(t,n){let S=keyObjectOf(n);switch(t){case`raw`:{if(n.type!==`public`)throw wrongKindForFormat(n,t);let C=S.export({format:`jwk`}).x;return toArrayBuffer(base64urlDecode(C))}case`spki`:if(n.type!==`public`)throw wrongKindForFormat(n,t);return toArrayBuffer(S.export({format:`der`,type:`spki`}));case`pkcs8`:if(n.type!==`private`)throw wrongKindForFormat(n,t);return toArrayBuffer(S.export({format:`der`,type:`pkcs8`}));case`jwk`:{let t=S.export({format:`jwk`}),C={kty:`OKP`,crv:n.algorithm.name,x:t.x};return n.type===`private`&&(C.d=t.d),n.algorithm.name===`Ed25519`&&(C.alg=`Ed25519`),C.key_ops=[...n.usages],C.ext=n.extractable,C}default:throw new tr(`Unsupported export format: ${t}`,`NotSupportedError`)}}function ed25519Sign$1(t,n,S){if(n.type!==`private`)throw new tr(`Key must be a private key`,`InvalidAccessError`);return toArrayBuffer(t.sign(null,S,keyObjectOf(n)))}__name$1(ed25519Sign$1,`ed25519Sign`);function ed25519Verify$1(t,n,S,C){if(n.type!==`public`)throw new tr(`Key must be a public key`,`InvalidAccessError`);return t.verify(null,C,keyObjectOf(n),S)}__name$1(ed25519Verify$1,`ed25519Verify`);function x25519DeriveBits(t,n,S,C){if(n.type!==`private`)throw new tr(`baseKey must be a private key`,`InvalidAccessError`);if(!(S instanceof CryptoKey)||S.type!==`public`)throw new tr(`algorithm.public must be a public key`,`InvalidAccessError`);if(S.algorithm.name!==n.algorithm.name)throw new tr(`The public and private keys must be of the same type`,`InvalidAccessError`);let N;try{N=new Uint8Array(t.diffieHellman({privateKey:keyObjectOf(n),publicKey:keyObjectOf(S)}))}catch(t){throw new tr(`Deriving bits failed: ${t.message}`,`OperationError`)}if(C==null)return toArrayBuffer(N);if(C>N.length*8)throw new tr(`derived bit length is too small`,`OperationError`);let F=N.slice(0,Math.ceil(C/8));return C%8!=0&&(F[F.length-1]&=255<<8-C%8),toArrayBuffer(F)}var xo,So=__esmMin(()=>{xo={RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_PKCS1_PSS_PADDING:6,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8}});function timingSafeEqual(t,n){if(t.length!==n.length)throw RangeError(`Input buffers must have the same byte length`);let S=0;for(let C=0;C<t.length;C++)S|=t[C]^n[C];return S===0}var Co=__esmMin(()=>{});function gmul(t,n){let S=0;for(let C=0;C<8;C++){n&1&&(S^=t);let C=t&128;t=t<<1&255,C&&(t^=27),n>>=1}return S}function keyExpansion(t){let n=t.length/4,S=n+6,C=4*(S+1),N=Array.from({length:C});for(let S=0;S<n;S++)N[S]=new Uint8Array([t[4*S],t[4*S+1],t[4*S+2],t[4*S+3]]);for(let t=n;t<C;t++){let S=new Uint8Array(N[t-1]);t%n===0?S=new Uint8Array([wo[S[1]]^Eo[t/n-1],wo[S[2]],wo[S[3]],wo[S[0]]]):n>6&&t%n===4&&(S=new Uint8Array([wo[S[0]],wo[S[1]],wo[S[2]],wo[S[3]]])),N[t]=new Uint8Array(4);for(let C=0;C<4;C++)N[t][C]=N[t-n][C]^S[C]}let F=[];for(let t=0;t<=S;t++){let n=new Uint8Array(16);for(let S=0;S<4;S++)n[4*S]=N[4*t+S][0],n[4*S+1]=N[4*t+S][1],n[4*S+2]=N[4*t+S][2],n[4*S+3]=N[4*t+S][3];F.push(n)}return F}function aesEncryptBlock(t,n){let S=new Uint8Array(t),C=n.length-1;for(let t=0;t<16;t++)S[t]^=n[0][t];for(let t=1;t<C;t++){for(let t=0;t<16;t++)S[t]=wo[S[t]];let C=S[1];S[1]=S[5],S[5]=S[9],S[9]=S[13],S[13]=C;let N=S[2],F=S[6];S[2]=S[10],S[6]=S[14],S[10]=N,S[14]=F;let I=S[15];S[15]=S[11],S[11]=S[7],S[7]=S[3],S[3]=I;for(let t=0;t<4;t++){let n=t*4,C=S[n],N=S[n+1],F=S[n+2],I=S[n+3];S[n]=gmul(2,C)^gmul(3,N)^F^I,S[n+1]=C^gmul(2,N)^gmul(3,F)^I,S[n+2]=C^N^gmul(2,F)^gmul(3,I),S[n+3]=gmul(3,C)^N^F^gmul(2,I)}for(let C=0;C<16;C++)S[C]^=n[t][C]}for(let t=0;t<16;t++)S[t]=wo[S[t]];let N=S[1];S[1]=S[5],S[5]=S[9],S[9]=S[13],S[13]=N;let F=S[2],I=S[6];S[2]=S[10],S[6]=S[14],S[10]=F,S[14]=I;let H=S[15];S[15]=S[11],S[11]=S[7],S[7]=S[3],S[3]=H;for(let t=0;t<16;t++)S[t]^=n[C][t];return S}function aesDecryptBlock(t,n){let S=new Uint8Array(t),C=n.length-1;for(let t=0;t<16;t++)S[t]^=n[C][t];for(let t=C-1;t>0;t--){let C=S[13];S[13]=S[9],S[9]=S[5],S[5]=S[1],S[1]=C;let N=S[10],F=S[14];S[10]=S[2],S[14]=S[6],S[2]=N,S[6]=F;let I=S[3];S[3]=S[7],S[7]=S[11],S[11]=S[15],S[15]=I;for(let t=0;t<16;t++)S[t]=To[S[t]];for(let C=0;C<16;C++)S[C]^=n[t][C];for(let t=0;t<4;t++){let n=t*4,C=S[n],N=S[n+1],F=S[n+2],I=S[n+3];S[n]=gmul(14,C)^gmul(11,N)^gmul(13,F)^gmul(9,I),S[n+1]=gmul(9,C)^gmul(14,N)^gmul(11,F)^gmul(13,I),S[n+2]=gmul(13,C)^gmul(9,N)^gmul(14,F)^gmul(11,I),S[n+3]=gmul(11,C)^gmul(13,N)^gmul(9,F)^gmul(14,I)}}let N=S[13];S[13]=S[9],S[9]=S[5],S[5]=S[1],S[1]=N;let F=S[10],I=S[14];S[10]=S[2],S[14]=S[6],S[2]=F,S[6]=I;let H=S[3];S[3]=S[7],S[7]=S[11],S[11]=S[15],S[15]=H;for(let t=0;t<16;t++)S[t]=To[S[t]];for(let t=0;t<16;t++)S[t]^=n[0][t];return S}function incrementCounter(t){for(let n=15;n>=0&&(t[n]=t[n]+1&255,t[n]===0);n--);}function gcmIncrementCounter(t){for(let n=15;n>=12&&(t[n]=t[n]+1&255,t[n]===0);n--);}function gfMul(t,n){let S=new Uint8Array(16),C=new Uint8Array(t);for(let t=0;t<128;t++){if(n[t>>>3]&1<<7-(t&7))for(let t=0;t<16;t++)S[t]^=C[t];let N=C[15]&1;for(let t=15;t>0;t--)C[t]=C[t]>>>1|(C[t-1]&1)<<7;C[0]>>>=1,N&&(C[0]^=225)}return S}function ghash(t,n,S){let C=new Uint8Array(16),N=Math.ceil(n.length/16)||0;for(let S=0;S<N;S++){let N=S*16,F=Math.min(N+16,n.length);for(let t=0;t<16;t++){let S=N+t;S<F&&(C[t]^=n[S])}let I=gfMul(C,t);C.set(I)}let F=Math.ceil(S.length/16)||0;for(let n=0;n<F;n++){let N=n*16,F=Math.min(N+16,S.length);for(let t=0;t<16;t++){let n=N+t;n<F&&(C[t]^=S[n])}let I=gfMul(C,t);C.set(I)}let I=new Uint8Array(16),H=n.length*8,W=S.length*8,q=Math.floor(H/4294967296),Y=H>>>0;I[0]=q>>>24&255,I[1]=q>>>16&255,I[2]=q>>>8&255,I[3]=q&255,I[4]=Y>>>24&255,I[5]=Y>>>16&255,I[6]=Y>>>8&255,I[7]=Y&255;let X=Math.floor(W/4294967296),Z=W>>>0;I[8]=X>>>24&255,I[9]=X>>>16&255,I[10]=X>>>8&255,I[11]=X&255,I[12]=Z>>>24&255,I[13]=Z>>>16&255,I[14]=Z>>>8&255,I[15]=Z&255;for(let t=0;t<16;t++)C[t]^=I[t];let te=gfMul(C,t);return C.set(te),C}var wo,To,Eo,Do=__esmMin(()=>{wo=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),To=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]),Eo=[1,2,4,8,16,32,64,128,27,54]});function parseAlgorithm(t){let n=t.toLowerCase().match(/^aes-(128|192|256)-(cbc|ctr|ecb|cfb|ofb|gcm)$/);if(!n)throw Error(`Unsupported cipher algorithm: ${t}`);let S=parseInt(n[1]),C=n[2];return{keySize:S/8,ivSize:C===`ecb`?0:C===`gcm`?12:16,mode:C}}function toBuffer$2(t,n){return typeof t==`string`?Xe.from(t,n||`utf8`):Xe.from(t)}function encodeOutput(t,n){return n?Xe.from(t).toString(n):Xe.from(t)}function incompleteUtf8Tail(t){if(t.length===0)return 0;let n=t.length;for(let S=1;S<=Math.min(4,n);S++){let C=t[n-S];if(!(C&128))return 0;if((C&192)==128)continue;let N;if((C&224)==192)N=2;else if((C&240)==224)N=3;else if((C&248)==240)N=4;else return 0;return S<N?S:0}return 0}function pkcs7Pad(t){let n=16-t.length%16,S=new Uint8Array(t.length+n);S.set(t);for(let C=t.length;C<S.length;C++)S[C]=n;return S}function pkcs7Unpad(t){if(t.length===0||t.length%16!=0)throw Error(`bad decrypt`);let n=t[t.length-1];if(n===0||n>16)throw Error(`bad decrypt`);for(let S=t.length-n;S<t.length;S++)if(t[S]!==n)throw Error(`bad decrypt`);return new Uint8Array(t.slice(0,t.length-n))}var Oo=__esmMin(()=>{ot(),__name$1(toBuffer$2,`toBuffer`)});function createCipher(t,n){throw Error(`crypto.createCipher() is deprecated. Use createCipheriv() instead.`)}function createCipheriv(t,n,S){return new Cipher(t,typeof n==`string`?Xe.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?Xe.from(S):new Uint8Array(S))}function createDecipher(t,n){throw Error(`crypto.createDecipher() is deprecated. Use createDecipheriv() instead.`)}function createDecipheriv(t,n,S){return new Decipher(t,typeof n==`string`?Xe.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?Xe.from(S):new Uint8Array(S))}function getCiphers(){return[`aes-128-cbc`,`aes-128-ecb`,`aes-192-cbc`,`aes-192-ecb`,`aes-256-cbc`,`aes-256-ecb`,`aes-128-ctr`,`aes-192-ctr`,`aes-256-ctr`,`aes-128-cfb`,`aes-192-cfb`,`aes-256-cfb`,`aes-128-gcm`,`aes-192-gcm`,`aes-256-gcm`]}var CipherBase,Cipher,Decipher,ko=__esmMin(()=>{Do(),Oo(),ot(),CipherBase=class{_roundKeys;_iv;_mode;_buffer=new Uint8Array;_autoPadding=!0;_finalized=!1;constructor(t,n,S){let C=parseAlgorithm(t);if(n.length!==C.keySize)throw Error(`Invalid key length ${n.length}, expected ${C.keySize} for ${t}`);if(C.ivSize>0&&(!S||S.length!==C.ivSize))throw Error(`Invalid IV length ${S?.length??0}, expected ${C.ivSize} for ${t}`);this._roundKeys=keyExpansion(n),this._iv=S?new Uint8Array(S):new Uint8Array(16),this._mode=C.mode}setAutoPadding(t){return this._autoPadding=t,this}},Cipher=class extends CipherBase{_prevBlock;_counter;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmAuthTag=null;_gcmAADSet=!1;constructor(t,n,S){super(t,n,S),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=new Uint8Array(16),this._gcmJ0.set(this._iv.subarray(0,12)),this._gcmJ0[15]=1,this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(t){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(t),this._gcmAADSet=!0,this}getAuthTag(){if(this._mode!==`gcm`)throw Error(`getAuthTag is only supported in GCM mode`);if(!this._gcmAuthTag)throw Error(`getAuthTag must be called after final()`);return Xe.from(this._gcmAuthTag)}update(t,n,S){let C=toBuffer$2(t,n),N=new Uint8Array(this._buffer.length+C.length);if(N.set(this._buffer),N.set(C,this._buffer.length),this._mode===`gcm`){let t=this._processGcmEncrypt(N);return this._buffer=new Uint8Array,encodeOutput(t,S)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let t=this._processStream(N);return this._buffer=new Uint8Array,encodeOutput(t,S)}let F=Math.floor(N.length/16)*16,I=[];for(let t=0;t<F;t+=16){let n=N.slice(t,t+16);I.push(this._encryptBlock(n))}this._buffer=N.slice(F);let H=new Uint8Array(I.length*16);for(let t=0;t<I.length;t++)H.set(I[t],t*16);return encodeOutput(H,S)}final(t){if(this._finalized)throw Error(`Cipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let n=new Uint8Array;this._buffer.length>0&&(n=this._processGcmEncrypt(this._buffer),this._buffer=new Uint8Array);let S=new Uint8Array(this._gcmCiphertextLen),C=0;for(let t of this._gcmCiphertext)S.set(t,C),C+=t.length;let N=ghash(this._gcmH,this._gcmAAD,S),F=aesEncryptBlock(this._gcmJ0,this._roundKeys),I=new Uint8Array(16);for(let t=0;t<16;t++)I[t]=N[t]^F[t];return this._gcmAuthTag=Xe.from(I),encodeOutput(n,t)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let n=this._processStream(this._buffer);return this._buffer=new Uint8Array,encodeOutput(n,t)}return encodeOutput(new Uint8Array,t)}let n=this._buffer;if(this._autoPadding)n=pkcs7Pad(n);else if(n.length%16!=0)throw Error(`data not multiple of block size`);let S=[];for(let t=0;t<n.length;t+=16)S.push(this._encryptBlock(n.slice(t,t+16)));if(this._buffer=new Uint8Array,S.length===0)return encodeOutput(new Uint8Array,t);let C=new Uint8Array(S.length*16);for(let t=0;t<S.length;t++)C.set(S[t],t*16);return encodeOutput(C,t)}_encryptBlock(t){if(this._mode===`cbc`){let n=new Uint8Array(16);for(let S=0;S<16;S++)n[S]=t[S]^this._prevBlock[S];let S=aesEncryptBlock(n,this._roundKeys);return this._prevBlock=S,S}else if(this._mode===`ecb`)return aesEncryptBlock(t,this._roundKeys);throw Error(`Block encryption not supported for mode: ${this._mode}`)}_processStream(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];incrementCounter(this._counter)}return n}_processGcmEncrypt(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];gcmIncrementCounter(this._counter)}return this._gcmCiphertext.push(new Uint8Array(n)),this._gcmCiphertextLen+=n.length,n}},Decipher=class extends CipherBase{_prevBlock;_counter;_pendingUtf8=new Uint8Array;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmExpectedTag=null;_gcmAADSet=!1;constructor(t,n,S){super(t,n,S),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=new Uint8Array(16),this._gcmJ0.set(this._iv.subarray(0,12)),this._gcmJ0[15]=1,this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(t){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(t),this._gcmAADSet=!0,this}setAuthTag(t){if(this._mode!==`gcm`)throw Error(`setAuthTag is only supported in GCM mode`);return this._gcmExpectedTag=Xe.from(t),this}_encodeWithUtf8Handling(t,n,S){if(!n||n!==`utf8`&&n!==`utf-8`)return encodeOutput(t,n);let C;if(this._pendingUtf8.length>0?(C=new Uint8Array(this._pendingUtf8.length+t.length),C.set(this._pendingUtf8),C.set(t,this._pendingUtf8.length),this._pendingUtf8=new Uint8Array):C=t,!S){let t=incompleteUtf8Tail(C);t>0&&(this._pendingUtf8=new Uint8Array(C.slice(C.length-t)),C=new Uint8Array(C.slice(0,C.length-t)))}return Xe.from(C).toString(`utf8`)}update(t,n,S){let C=toBuffer$2(t,n),N=new Uint8Array(this._buffer.length+C.length);if(N.set(this._buffer),N.set(C,this._buffer.length),this._mode===`gcm`){this._gcmCiphertext.push(new Uint8Array(N)),this._gcmCiphertextLen+=N.length;let t=this._processGcmDecrypt(N);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(t,S,!1)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let t=this._processStream(N);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(t,S,!1)}let F=Math.floor(N.length/16);if(F===0)return this._buffer=N,this._encodeWithUtf8Handling(new Uint8Array,S,!1);let I=(this._autoPadding?F-1:F)*16,H=[];for(let t=0;t<I;t+=16){let n=N.slice(t,t+16);H.push(this._decryptBlock(n))}this._buffer=N.slice(I);let W=new Uint8Array(H.length*16);for(let t=0;t<H.length;t++)W.set(H[t],t*16);return this._encodeWithUtf8Handling(W,S,!1)}final(t){if(this._finalized)throw Error(`Decipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let n=new Uint8Array;if(this._buffer.length>0&&(this._gcmCiphertext.push(new Uint8Array(this._buffer)),this._gcmCiphertextLen+=this._buffer.length,n=this._processGcmDecrypt(this._buffer),this._buffer=new Uint8Array),!this._gcmExpectedTag)throw Error(`Unsupported state or unable to authenticate data`);let S=new Uint8Array(this._gcmCiphertextLen),C=0;for(let t of this._gcmCiphertext)S.set(t,C),C+=t.length;let N=ghash(this._gcmH,this._gcmAAD,S),F=aesEncryptBlock(this._gcmJ0,this._roundKeys),I=new Uint8Array(16);for(let t=0;t<16;t++)I[t]=N[t]^F[t];let H=this._gcmExpectedTag,W=Math.min(H.length,16),q=0;for(let t=0;t<W;t++)q|=I[t]^H[t];if(q!==0)throw Error(`Unsupported state or unable to authenticate data`);return this._encodeWithUtf8Handling(n,t,!0)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let n=this._processStream(this._buffer);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(n,t,!0)}return this._encodeWithUtf8Handling(new Uint8Array,t,!0)}if(this._buffer.length===0)return this._encodeWithUtf8Handling(new Uint8Array,t,!0);if(this._buffer.length%16!=0)throw Error(`bad decrypt`);let n=[];for(let t=0;t<this._buffer.length;t+=16)n.push(this._decryptBlock(this._buffer.slice(t,t+16)));let S=new Uint8Array(n.length*16);for(let t=0;t<n.length;t++)S.set(n[t],t*16);let C=this._autoPadding?pkcs7Unpad(S):S;return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(C,t,!0)}_decryptBlock(t){if(this._mode===`cbc`){let n=aesDecryptBlock(t,this._roundKeys),S=new Uint8Array(16);for(let t=0;t<16;t++)S[t]=n[t]^this._prevBlock[t];return this._prevBlock=new Uint8Array(t),S}else if(this._mode===`ecb`)return aesDecryptBlock(t,this._roundKeys);throw Error(`Block decryption not supported for mode: ${this._mode}`)}_processStream(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];incrementCounter(this._counter)}return n}_processGcmDecrypt(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];gcmIncrementCounter(this._counter)}return n}}});function pemToDer(t){let n=t.trim().split(/\r?\n/),S=n.findIndex(t=>t.startsWith(`-----BEGIN `));if(S===-1)throw Error(`Invalid PEM: no BEGIN line found`);let C=n[S].match(/^-----BEGIN (.+)-----$/);if(!C)throw Error(`Invalid PEM header format`);let N=C[1],F=n.findIndex((t,n)=>n>S&&t.startsWith(`-----END `));if(F===-1)throw Error(`Invalid PEM: no END line found`);let I=n.slice(S+1,F).join(``),H=Xe.from(I,`base64`);return{type:N,der:new Uint8Array(H.buffer,H.byteOffset,H.byteLength)}}function parseTlv(t,n){if(n>=t.length)throw Error(`ASN.1 parse error: unexpected end of data`);let S=t[n++],C,N=t[n++];if(N<128)C=N;else{let S=N&127;if(S===0)throw Error(`ASN.1 parse error: indefinite length not supported`);C=0;for(let N=0;N<S;N++)C=C<<8|t[n++]}let F=t.slice(n,n+C),I=n+C,H={tag:S,data:F};return S===48&&(H.children=parseSequenceChildren(F)),{value:H,next:I}}function parseSequenceChildren(t){let n=[],S=0;for(;S<t.length;){let{value:C,next:N}=parseTlv(t,S);n.push(C),S=N}return n}function parseDer(t){let{value:n}=parseTlv(t,0);return n}function integerToBigInt(t){let n=0;for(;n<t.length-1&&t[n]===0;)n++;let S=0n;for(let C=n;C<t.length;C++)S=S<<8n|BigInt(t[C]);return S}function okpCurveForOid(t){if(oidsEqual(t,Mo))return`ed25519`;if(oidsEqual(t,jo))return`x25519`}function oidForOkpCurve(t){return t===`ed25519`?Mo:jo}function oidsEqual(t,n){if(t.length!==n.length)return!1;for(let S=0;S<t.length;S++)if(t[S]!==n[S])return!1;return!0}function parseRsaPublicKeyPkcs1(t){let n=t.children;if(!n||n.length<2)throw Error(`Invalid PKCS#1 RSAPublicKey structure`);return{n:integerToBigInt(n[0].data),e:integerToBigInt(n[1].data)}}function parseRsaPrivateKeyPkcs1(t){let n=t.children;if(!n||n.length<6)throw Error(`Invalid PKCS#1 RSAPrivateKey structure`);return{n:integerToBigInt(n[1].data),e:integerToBigInt(n[2].data),d:integerToBigInt(n[3].data),p:integerToBigInt(n[4].data),q:integerToBigInt(n[5].data)}}function algorithmOid(t){let n=t?.children?.[0];if(!n||n.tag!==6)throw Error(`Invalid AlgorithmIdentifier`);if(okpCurveForOid(n.data)&&(t?.children?.length??0)!==1)throw Error(`Invalid AlgorithmIdentifier: parameters must be absent (RFC 8410)`);return n.data}function parseSubjectPublicKeyInfo(t){let n=t.children;if(!n||n.length<2)throw Error(`Invalid SubjectPublicKeyInfo structure`);let S=algorithmOid(n[0]),C=n[1];if(C.tag!==3||C.data[0]!==0)throw Error(`Expected BIT STRING for public key data`);let N=C.data.slice(1),F=okpCurveForOid(S);if(F){if(N.length!==32)throw Error(`Invalid ${F} public key length: ${N.length}`);return{type:`okp-public`,curve:F,pub:N}}if(!oidsEqual(S,Ao))throw Error(`Unsupported key algorithm`);return{type:`rsa-public`,components:parseRsaPublicKeyPkcs1(parseDer(N))}}function parsePrivateKeyInfo(t){let n=t.children;if(!n||n.length<3)throw Error(`Invalid PrivateKeyInfo structure`);let S=algorithmOid(n[1]),C=n[2];if(C.tag!==4)throw Error(`Expected OCTET STRING for private key data`);let N=okpCurveForOid(S);if(N){let t=parseDer(C.data);if(t.tag!==4||t.data.length!==32)throw Error(`Invalid ${N} private key`);return{type:`okp-private`,curve:N,priv:t.data}}if(!oidsEqual(S,Ao))throw Error(`Unsupported key algorithm`);return{type:`rsa-private`,components:parseRsaPrivateKeyPkcs1(parseDer(C.data))}}function encodeLength(t){if(t<128)return new Uint8Array([t]);let n=[],S=t;for(;S>0;)n.unshift(S&255),S>>=8;return new Uint8Array([128|n.length,...n])}function encodeTlv(t,n){let S=encodeLength(n.length),C=new Uint8Array(1+S.length+n.length);return C[0]=t,C.set(S,1),C.set(n,1+S.length),C}function bigintToAsn1Integer(t){if(t===0n)return encodeTlv(2,new Uint8Array([0]));let n=t.toString(16),S=n.length%2?`0`+n:n,C=[];for(let t=0;t<S.length;t+=2)C.push(parseInt(S.substring(t,t+2),16));return C[0]&128&&C.unshift(0),encodeTlv(2,new Uint8Array(C))}function encodeSequence(t){let n=0;for(let S of t)n+=S.length;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return encodeTlv(48,S)}function encodeBitString(t){let n=new Uint8Array(1+t.length);return n[0]=0,n.set(t,1),encodeTlv(3,n)}function encodeOctetString(t){return encodeTlv(4,t)}function encodeOid(t){return encodeTlv(6,t)}function encodeNull(){return new Uint8Array([5,0])}function encodeRsaPublicKeyPkcs1(t){return encodeSequence([bigintToAsn1Integer(t.n),bigintToAsn1Integer(t.e)])}function encodeSubjectPublicKeyInfo(t){return encodeSequence([encodeSequence([encodeOid(Ao),encodeNull()]),encodeBitString(encodeRsaPublicKeyPkcs1(t))])}function encodeRsaPrivateKeyPkcs1(t){let n=t.d%(t.p-1n),S=t.d%(t.q-1n),C=modInverse$2(t.q,t.p);return encodeSequence([bigintToAsn1Integer(0n),bigintToAsn1Integer(t.n),bigintToAsn1Integer(t.e),bigintToAsn1Integer(t.d),bigintToAsn1Integer(t.p),bigintToAsn1Integer(t.q),bigintToAsn1Integer(n),bigintToAsn1Integer(S),bigintToAsn1Integer(C)])}function encodePrivateKeyInfo(t){let n=encodeSequence([encodeOid(Ao),encodeNull()]),S=encodeOctetString(encodeRsaPrivateKeyPkcs1(t));return encodeSequence([bigintToAsn1Integer(0n),n,S])}function encodeOkpSubjectPublicKeyInfo(t,n){return encodeSequence([encodeSequence([encodeOid(oidForOkpCurve(t))]),encodeBitString(n)])}function encodeOkpPrivateKeyInfo(t,n){return encodeSequence([bigintToAsn1Integer(0n),encodeSequence([encodeOid(oidForOkpCurve(t))]),encodeOctetString(encodeOctetString(n))])}function derToPem(t,n){let S=Xe.from(t).toString(`base64`),C=[`-----BEGIN ${n}-----`];for(let t=0;t<S.length;t+=64)C.push(S.substring(t,t+64));return C.push(`-----END ${n}-----`),C.join(`
14
+ --`+t;let n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S),this.boundaryChars[n[S]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(t){let n=0,S=t.length,C=this.index,{lookbehind:N,boundary:F,boundaryChars:I,index:H,state:W,flags:q}=this,Y=this.boundary.length,X=Y-1,Z=t.length,te,ne,mark=t=>{this[t+`Mark`]=n},clear=t=>{delete this[t+`Mark`]},callback=(t,n,S,C)=>{(n===void 0||n!==S)&&this[t](C&&C.subarray(n,S))},dataCallback=(S,C=!1)=>{let N=S+`Mark`;N in this&&(C?(callback(S,this[N],n,t),delete this[N]):(callback(S,this[N],t.length,t),this[N]=0))};for(n=0;n<S;n++)switch(te=t[n],W){case 0:if(H===F.length-2){if(te===45)q|=Ia.LAST_BOUNDARY;else if(te!==13)return;H++;break}else if(H-1==F.length-2){if(q&Ia.LAST_BOUNDARY&&te===45)W=9,q=0;else if(!(q&Ia.LAST_BOUNDARY)&&te===10)H=0,callback(`onPartBegin`),W=1;else return;break}te!==F[H+2]&&(H=-2),te===F[H+2]&&H++;break;case 1:W=2,mark(`onHeaderField`),H=0;case 2:if(te===13){clear(`onHeaderField`),W=6;break}if(H++,te===45)break;if(te===58){if(H===1)return;dataCallback(`onHeaderField`,!0),W=3;break}if(ne=lower(te),ne<97||ne>122)return;break;case 3:if(te===32)break;mark(`onHeaderValue`),W=4;case 4:te===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),W=5);break;case 5:if(te!==10)return;W=1;break;case 6:if(te!==10)return;callback(`onHeadersEnd`),W=7;break;case 7:W=8,mark(`onPartData`);case 8:if(C=H,H===0){for(n+=X;n<Z&&!(t[n]in I);)n+=Y;n-=X,te=t[n]}if(H<F.length)F[H]===te?(H===0&&dataCallback(`onPartData`,!0),H++):H=0;else if(H===F.length)H++,te===13?q|=Ia.PART_BOUNDARY:te===45?q|=Ia.LAST_BOUNDARY:H=0;else if(H-1===F.length)if(q&Ia.PART_BOUNDARY){if(H=0,te===10){q&=~Ia.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),W=1;break}}else q&Ia.LAST_BOUNDARY&&te===45?(callback(`onPartEnd`),W=9,q=0):H=0;if(H>0)N[H-1]=te;else if(C>0){let t=new Uint8Array(N.buffer,N.byteOffset,N.byteLength);callback(`onPartData`,0,C,t),C=0,mark(`onPartData`),n--}break;case 9:break;default:throw Error(`Unexpected state entered: ${W}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=H,this.state=W,this.flags=q}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}});_e(),Sa(),Ta(),Hn(),ot(),ta(),Na(),__name((t,n)=>new Promise((S,C)=>{pipeline$1(t,n,t=>{t?C(t):S()})}),`pipeline`);const Ra=Symbol(`Body internals`);function isAnyArrayBuffer$2(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer}__name$1(isAnyArrayBuffer$2,`isAnyArrayBuffer`);var Body=class{[Ra]={body:null,stream:null,webStream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(t,n={size:0}){if(this.size=n.size||0,t==null)this[Ra].body=null;else if(isURLSearchParameters(t))this[Ra].body=Xe.from(t.toString());else if(isBlob(t))this[Ra].body=t;else if(Xe.isBuffer(t))this[Ra].body=t;else if(isAnyArrayBuffer$2(t))this[Ra].body=Xe.from(t);else if(ArrayBuffer.isView(t))this[Ra].body=Xe.from(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof Yi)this[Ra].body=t;else if(typeof ReadableStream<`u`&&t instanceof ReadableStream)this[Ra].body=readableStreamToReadable(t);else if(t instanceof FormData){let n=formDataToBlob(t);this[Ra].body=n,this[Ra].boundary=n.type?.split(`boundary=`)?.[1]??``}else typeof t==`string`?this[Ra].body=Xe.from(t):t instanceof Fn?this[Ra].body=Xe.from(t.toString()):(ge.warn(`Unknown body type "${typeof t}", try to parse the body to string!`),this[Ra].body=Xe.from(String(t)));let S=this[Ra].body;Xe.isBuffer(S)?this[Ra].stream=Yi.from(S):isBlob(S)?this[Ra].stream=Yi.from(blobToAsyncIterable(S)):S instanceof Yi&&(this[Ra].stream=S),S instanceof Ji&&S.on(`error`,t=>{let n=t instanceof FetchBaseError?t:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${t.message}`,`system`,t);this[Ra].error=n})}get body(){let t=this[Ra].stream;if(!t)return null;let n=this[Ra].webStream;if(n)return n;if(typeof ReadableStream<`u`){let n=!1,S=new ReadableStream({start(S){t.on(`data`,t=>{if(!n)try{S.enqueue(t instanceof Uint8Array?t:new Uint8Array(t))}catch{}}),t.on(`end`,()=>{if(!n){n=!0;try{S.close()}catch{}}}),t.on(`error`,t=>{if(!n){n=!0;try{S.error(t)}catch{}}})},cancel(){n=!0,t.destroy()}});return this[Ra].webStream=S,S}return null}get _stream(){return this[Ra].stream}get _rawBodyBuffer(){let t=this[Ra].body;return t===null?null:Xe.isBuffer(t)?t:t instanceof Uint8Array?Xe.from(t.buffer,t.byteOffset,t.byteLength):null}get bodyUsed(){return this[Ra].disturbed}async arrayBuffer(){let{buffer:t,byteOffset:n,byteLength:S}=await consumeBody(this);return t.slice(n,n+S)}async formData(){let t=this.headers?.get(`content-type`);if(t?.startsWith(`application/x-www-form-urlencoded`)){let t=new FormData,n=new Fn(await this.text());for(let[S,C]of n)t.append(S,C);return t}let{toFormData:n}=await Promise.resolve().then(()=>(La(),Pa));return n(this.body,t)}async blob(){let t=this.headers?.get(`content-type`)||this[Ra].body&&this[Ra].body.type||``;return new te([await this.arrayBuffer()],{type:t})}async json(){let t=await this.text();return JSON.parse(t)}async text(){let t=await consumeBody(this);return new TextDecoder().decode(t)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(t){if(t[Ra].disturbed)throw TypeError(`body used already for: ${t.url}`);if(t[Ra].disturbed=!0,t[Ra].error)throw t[Ra].error;let{_stream:n}=t;if(n===null||!(n instanceof Ji))return Xe.alloc(0);let S=[],C=0;try{for await(let N of n){if(t.size>0&&C+N.length>t.size){let S=new FetchError(`content size at ${t.url} over limit: ${t.size}`,`max-size`);throw n.destroy(S),S}C+=N.length,S.push(N)}}catch(n){let S=n instanceof Error?n:Error(String(n));throw n instanceof FetchBaseError?n:new FetchError(`Invalid response body while trying to fetch ${t.url}: ${S.message}`,`system`,S)}try{return S.every(t=>typeof t==`string`)?Xe.from(S.join(``)):Xe.concat(S,C)}catch(n){let S=n instanceof Error?n:Error(String(n));throw new FetchError(`Could not create Buffer from response body for ${t.url}: ${S.message}`,`system`,S)}}const clone=(t,n)=>{let S,C,{body:N}=t[Ra];if(t.bodyUsed)throw Error(`cannot clone body after it is used`);return N instanceof Ji&&typeof N.getBoundary!=`function`&&(S=new $i({highWaterMark:n}),C=new $i({highWaterMark:n}),N.pipe(S),N.pipe(C),t[Ra].stream=S,N=C),N},extractContentType=(t,n)=>t===null?null:typeof t==`string`?`text/plain;charset=UTF-8`:isURLSearchParameters(t)?`application/x-www-form-urlencoded;charset=UTF-8`:isBlob(t)?t.type||null:Xe.isBuffer(t)||isAnyArrayBuffer$2(t)||ArrayBuffer.isView(t)?null:t instanceof FormData?`multipart/form-data; boundary=${n[Ra].boundary}`:t instanceof Ji?null:`text/plain;charset=UTF-8`,getTotalBytes=t=>{let{body:n}=t[Ra];if(n===null)return 0;if(isBlob(n))return n.size;if(Xe.isBuffer(n))return n.length;if(n&&typeof n.getLengthSync==`function`){let t=n;return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null}return null};function readableStreamToReadable(t){let n=t.getReader();return new Yi({async read(){try{let{done:t,value:S}=await n.read();t?this.push(null):this.push(Xe.from(S))}catch(t){this.destroy(t)}},destroy(t,S){n.cancel().then(()=>S(null),S)}})}async function*blobToAsyncIterable(t){if(typeof t.stream==`function`){let n=t.stream().getReader();for(;;){let{done:t,value:S}=await n.read();if(t)break;yield S}}else yield new Uint8Array(await t.arrayBuffer())}const za=new Set([301,302,303,307,308]),isRedirect=t=>za.has(t);Hn(),ut(),hi();const Ba=Symbol(`Response internals`);var Va=class Response extends Body{[Ba];_inputStream=null;constructor(t=null,n={}){super(t,n);let S=n.status==null?200:n.status,C=new wa(n.headers);if(t!==null&&!C.has(`Content-Type`)){let n=extractContentType(t,this);n&&C.append(`Content-Type`,n)}this[Ba]={type:`default`,url:n.url,status:S,statusText:n.statusText||``,headers:C,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ba].type}get url(){return this[Ba].url||``}get status(){return this[Ba].status}get ok(){return this[Ba].status>=200&&this[Ba].status<300}get redirected(){return this[Ba].counter>0}get statusText(){return this[Ba].statusText}get headers(){return this[Ba].headers}get highWaterMark(){return this[Ba].highWaterMark}clone(){return new Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!isRedirect(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new Bn(t).toString()},status:n})}static error(){let t=new Response(null,{status:0,statusText:``});return t[Ba].type=`error`,t}static json(t,n){let S=JSON.stringify(t),C={...n},N=new wa(C.headers);return N.has(`content-type`)||N.set(`content-type`,`application/json`),C.headers=N,new Response(S,C)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let t=mi.MemoryOutputStream.new_resizable();await new Promise((n,S)=>{t.splice_async(this._inputStream,mi.OutputStreamSpliceFlags.CLOSE_TARGET|mi.OutputStreamSpliceFlags.CLOSE_SOURCE,lt.PRIORITY_DEFAULT,null,(C,N)=>{try{n(t.splice_finish(N))}catch(t){S(t)}})});let n=t.steal_as_bytes();return new TextDecoder().decode(n.toArray())}};Object.defineProperties(Va.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function gbytesToUint8Array(t){return t.toArray()}var Ha=__esmMin(()=>{}),Ua,cli,Wa=__esmMin(()=>{ut(),Ua=new TextDecoder,cli=t=>{let[n,S,C,N]=lt.spawn_command_line_sync(t);if(C.byteLength)throw Error(Ua.decode(C));return Ua.decode(S)}}),Ga,readJSON,Ka=__esmMin(()=>{ut(),Ga=new TextDecoder,readJSON=t=>{let[n,S]=lt.file_get_contents(t);if(n)return JSON.parse(Ga.decode(S));throw Error(`Error on require "${t}"`)}}),qa,Ja=__esmMin(()=>{qa=S}),Ya,Xa=__esmMin(()=>{Ja(),Ya=qa});function existsSync(t){return typeof t!=`string`||t===``?!1:mi.File.new_for_path(t).query_exists(null)}var Za=__esmMin(()=>{hi(),Xa()});async function readBytesAsync(t,n=4096,S=lt.PRIORITY_DEFAULT,C=null){return new Promise((N,F)=>{t.read_bytes_async(n,S,C,(n,S)=>{try{let n=t.read_bytes_finish(S);return n.get_size()===0?N(null):N(gbytesToUint8Array(n))}catch(t){let n=t;if(typeof n.matches==`function`&&(n.matches(mi.IOErrorEnum,mi.IOErrorEnum.PARTIAL_INPUT)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.CONNECTION_CLOSED)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.BROKEN_PIPE)||n.matches(mi.IOErrorEnum,mi.IOErrorEnum.CLOSED)))return N(null);F(t)}})})}async function*inputStreamAsyncIterator(t,n=4096,S=lt.PRIORITY_DEFAULT,C=null){let N;for(;(N=await readBytesAsync(t,n,S,C))!==null;)yield N}var Qa=__esmMin(()=>{Ha(),ut(),hi()}),$a,eo,getPathSeparator,to=__esmMin(()=>{ut(),hi(),{File:$a}=mi,eo=__name$1((t,...n)=>{let S=$a.new_for_path(t);for(let t of n)S=S.resolve_relative_path(t);return S},`resolve`),getPathSeparator=()=>lt.get_current_dir().startsWith(`/`)?`/`:`\\`}),no=__esmMin(()=>{Ha(),Wa(),ae(),Me(),Ka(),Za(),Qa(),to()});ta(),ut(),hi(),no();async function soupSendAsync(t,n,S=lt.PRIORITY_DEFAULT,C=null){return new Promise((N,F)=>{let I=!1,onCancel=()=>{I||(I=!0,F(new mi.IOErrorEnum({code:mi.IOErrorEnum.CANCELLED,message:`Operation was cancelled`})))},H=C?C.connect(onCancel):0;I||t.send_async(n,S,C,(n,S)=>{H&&C.disconnect(H);let W;try{W=t.send_finish(S)}catch(t){I||(I=!0,F(t));return}if(I){closeInputStream(W);return}I=!0,N(W)})})}function closeInputStream(t){return new Promise(n=>{t.close_async(lt.PRIORITY_DEFAULT,null,(S,C)=>{try{t.close_finish(C)}catch{}n()})})}function inputStreamToReadable(t,n={}){let S=new mi.Cancellable,C=null,close=()=>C||(t.has_pending()?Promise.resolve():(C=closeInputStream(t),C));async function*chunks(){try{yield*inputStreamAsyncIterator(t,4096,lt.PRIORITY_DEFAULT,S)}finally{await close()}}let N=Yi.from(chunks(),n);return N.once(`close`,()=>{t.has_pending()?S.cancel():close()}),N}let ro=null;async function loadSoup(){return ro??=(await import(`gi://Soup?version=3.0`)).default}function isIP(t){if(typeof t!=`string`)return 0;let n=t.includes(`%`)?t.slice(0,t.indexOf(`%`)):t,S=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(n);if(S)return S.slice(1).every(t=>(t.length===1||t[0]!==`0`)&&Number(t)<=255)?4:0;if(n.length===0||!n.includes(`:`))return 0;let C=/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(n),N=C?n.slice(0,n.length-C[0].length):n;if(C&&isIP(C[1])!==4)return 0;let F=N.split(`::`);if(F.length>2)return 0;let I=0;for(let t of F)if(t!==``)for(let n of t.split(`:`)){if(!/^[0-9a-fA-F]{1,4}$/.test(n))return 0;I++}let H=C?6:8;return F.length===2?I<H?6:0:I===H?6:0}hi(),ut(),ta(),hi(),qt(),Hn();function stripURLForUseAsAReferrer(t,n=!1){if(t==null||t===`no-referrer`)return`no-referrer`;let S=new Bn(t);return/^(about|blob|data):$/.test(S.protocol)?`no-referrer`:(S.username=``,S.password=``,S.hash=``,n&&(S.pathname=``,S.search=``),S)}const io=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]);function validateReferrerPolicy(t){if(!io.has(t))throw TypeError(`Invalid referrerPolicy: ${t}`);return t}function isOriginPotentiallyTrustworthy(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let n=t.host.replace(/(^\[)|(]$)/g,``),S=isIP(n);return S===4&&n.startsWith(`127.`)||S===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(n)?!0:t.host===`localhost`||t.host.endsWith(`.localhost`)?!1:t.protocol===`file:`}function isUrlPotentiallyTrustworthy(t){return/^about:(blank|srcdoc)$/.test(t.toString())||(typeof t==`string`&&(t=new Bn(t)),t.protocol===`data:`)||/^(blob|filesystem):$/.test(t.protocol)?!0:isOriginPotentiallyTrustworthy(t)}function determineRequestsReferrer(t,n={}){let{referrerURLCallback:S,referrerOriginCallback:C}=n;if(t.referrer===`no-referrer`||t.referrerPolicy===``)return null;let N=t.referrerPolicy;if(t.referrer===`about:client`)return`no-referrer`;let F=new Bn(t.referrer),I=stripURLForUseAsAReferrer(F),H=stripURLForUseAsAReferrer(F,!0);I.toString().length>4096&&(I=H),S&&(I=S(I)),C&&(H=C(H));let W=new Bn(t.url);switch(N){case`no-referrer`:return`no-referrer`;case`origin`:return H;case`unsafe-url`:return I;case`strict-origin`:return isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:H.toString();case`strict-origin-when-cross-origin`:return I.origin===W.origin?I:isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:H;case`same-origin`:return I.origin===W.origin?I:`no-referrer`;case`origin-when-cross-origin`:return I.origin===W.origin?I:H;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(I)&&!isUrlPotentiallyTrustworthy(W)?`no-referrer`:I;default:throw TypeError(`Invalid referrerPolicy: ${N}`)}}function parseReferrerPolicyFromHeader(t){let n=(t.get(`referrer-policy`)||``).split(/[,\s]+/),S=``;for(let t of n)t&&io.has(t)&&(S=t);return S}Hn(),ut(),hi();const ao=Symbol(`Request internals`);let oo=null;function envPositiveInt(t,n){let S=lt.getenv(t);if(!S)return n;let C=Number.parseInt(S,10);return Number.isFinite(C)&&C>0?C:n}function shouldAcceptAnyCert(t){return t===!1?!0:t===!0?!1:lt.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)===`0`}function getSharedSession(t){if(oo===null){let n=envPositiveInt(`GJSIFY_FETCH_MAX_CONNS_PER_HOST`,16),S=Math.max(envPositiveInt(`GJSIFY_FETCH_MAX_CONNS`,64),n);oo=new t.Session({maxConns:S,maxConnsPerHost:n}),oo.remove_feature_by_type(t.ContentDecoder.$gtype)}return oo}const isRequest=t=>typeof t==`object`&&typeof t.url==`string`;var so=class Request extends Body{cache;credentials;destination;get headers(){return this[ao].headers}integrity;keepalive;get method(){return this[ao].method}mode;get redirect(){return this[ao].redirect}get referrer(){if(this[ao].referrer===`no-referrer`)return``;if(this[ao].referrer===`client`)return`about:client`;if(this[ao].referrer)return this[ao].referrer.toString()}get referrerPolicy(){return this[ao].referrerPolicy}set referrerPolicy(t){this[ao].referrerPolicy=validateReferrerPolicy(t)}get signal(){return this[ao].signal}get url(){return this[ao].parsedURL.toString()}get _uri(){return lt.Uri.parse(this.url,lt.UriFlags.ENCODED)}get _session(){return this[ao].session}get _message(){return this[ao].message}get _inputStream(){return this[ao].inputStream}get[Symbol.toStringTag](){return`Request`}[ao];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;constructor(t,n){let S=t,C=n||{},N,F={};if(isRequest(t)?(N=new Bn(S.url),F=S):N=new Bn(t),N.username!==``||N.password!==``)throw TypeError(`${N} is an url with embedded credentials.`);let I=C.method||F.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(I)&&(I=I.toUpperCase()),(n?.body!=null||isRequest(t)&&S.body!==null)&&(I===`GET`||I===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let H=n?.body?n.body:isRequest(t)&&S.body!==null?clone(t):null;super(H,{size:C.size||0});let W=new wa(n?.headers||S.headers||{});if(H!==null&&!W.has(`Content-Type`)){let t=extractContentType(H,this);t&&W.set(`Content-Type`,t)}let q=isRequest(t)?S.signal:null;if(n&&`signal`in n&&(q=n.signal),q!=null&&!isAbortSignal(q))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let Y=n?.referrer==null?S.referrer:n.referrer;if(Y===``)Y=`no-referrer`;else if(Y){let t=new Bn(Y);Y=/^about:(\/\/)?client$/.test(t.toString())?`client`:t}else Y=void 0;this[ao]={method:I,redirect:n?.redirect||S.redirect||`follow`,headers:W,parsedURL:N,signal:q,referrer:Y,referrerPolicy:``,session:null,message:null},this.follow=C.follow===void 0?S.follow===void 0?20:S.follow:C.follow,this.compress=C.compress===void 0?S.compress===void 0?!0:S.compress:C.compress,this.counter=C.counter||S.counter||0,this.agent=C.agent||S.agent,this.highWaterMark=C.highWaterMark||S.highWaterMark||16384,this.insecureHTTPParser=C.insecureHTTPParser||S.insecureHTTPParser||!1,this.rejectUnauthorized=C.rejectUnauthorized??S.rejectUnauthorized,this.referrerPolicy=n?.referrerPolicy||S.referrerPolicy||``}async _send(t){let{signal:n,parsedURL:S}=this[ao],C=S.protocol;if(C!==`http:`&&C!==`https:`)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);let N=await loadSoup(),F=getSharedSession(N),I=new N.Message({method:this[ao].method,uri:lt.Uri.parse(S.toString(),lt.UriFlags.ENCODED)});this[ao].session=F,this[ao].message=I,t.headers._appendToSoupMessage(N,I);let H=this._rawBodyBuffer;if(H!==null&&H.byteLength>0){let n=t.headers.get(`content-type`)||null;I.set_request_body_from_bytes(n,new lt.Bytes(H))}S.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&I.connect(`accept-certificate`,(t,n,S)=>!0);let W=new mi.Cancellable;return n&&(n.aborted?W.cancel():n.addEventListener(`abort`,()=>W.cancel(),{once:!0})),this[ao].inputStream=await soupSendAsync(F,I,lt.PRIORITY_DEFAULT,W),this[ao].readable=inputStreamToReadable(this[ao].inputStream),{inputStream:this[ao].inputStream,readable:this[ao].readable,cancellable:W}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(so.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=t=>{let{parsedURL:n}=t[ao],S=new wa(t[ao].headers);S.has(`Accept`)||S.set(`Accept`,`*/*`);let C=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(C=`0`),t.body!==null){let n=getTotalBytes(t);typeof n==`number`&&!Number.isNaN(n)&&(C=String(n))}C&&S.set(`Content-Length`,C),t.referrerPolicy===``&&(t.referrerPolicy=`strict-origin-when-cross-origin`),t.referrer&&t.referrer!==`no-referrer`?t[ao].referrer=determineRequestsReferrer(t):t[ao].referrer=`no-referrer`,t[ao].referrer instanceof Bn&&S.set(`Referer`,t.referrer),S.has(`User-Agent`)||S.set(`User-Agent`,`gjsify-fetch`),t.compress&&!S.has(`Accept-Encoding`)&&S.set(`Accept-Encoding`,`gzip, deflate`);let{agent:N}=t;return typeof N==`function`&&(N=N(n)),!S.has(`Connection`)&&!N&&S.set(`Connection`,`close`),{parsedURL:n,options:{headers:S}}};var AbortError=class extends FetchBaseError{constructor(t,n=`aborted`){super(t,n)}};function parseDataUri(t){let n=t.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!n)throw TypeError(`Invalid data URI: ${t.slice(0,50)}...`);let S=n[1]||`text/plain;charset=US-ASCII`,C=!!n[2],N=n[3],F;if(C){let t=atob(N);F=new Uint8Array(t.length);for(let n=0;n<t.length;n++)F[n]=t.charCodeAt(n)}else F=new TextEncoder().encode(decodeURIComponent(N));return{buffer:F,typeFull:S}}ze();function rewriteRootRelativeUrl(t,n){if(!t.startsWith(`/`)||t.startsWith(`//`))return t;let S=lastPathSeparatorIndex(n);return S<=0?t:`${pathToFileUrlHref(n.slice(0,S))}${t}`}function resolveRootRelativeUrl(t){return rewriteRootRelativeUrl(t,C.programPath??C.programInvocationName??``)}_e(),Ta(),Hn(),ta(),ut();const co=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteFetchInput(t){if(typeof t!=`string`)return t;let n=resolveRootRelativeUrl(t);return n!==t&&globalThis.__GJSIFY_DEBUG_FETCH===!0&&ge.log(`[fetch] rewrite ${t} → ${n}`),n}async function fetch$1(t,n={}){t=rewriteFetchInput(t);let S=new so(t,n),{parsedURL:C,options:N}=getSoupRequestOptions(S);if(!co.has(C.protocol))throw TypeError(`@gjsify/fetch cannot load ${t}. URL scheme "${C.protocol.replace(/:$/,``)}" is not supported.`);if(C.protocol===`data:`){let{buffer:t,typeFull:n}=parseDataUri(S.url);return new Va(Buffer.from(t),{headers:{"Content-Type":n}})}if(C.protocol===`file:`){let t=globalThis.__GJSIFY_DEBUG_FETCH===!0;t&&ge.log(`[fetch] file:// ${S.url}`);try{let n=lt.filename_from_uri(S.url)[0];t&&ge.log(`[fetch] file:// path=${n}`);let[C,N]=lt.file_get_contents(n);if(t&&ge.log(`[fetch] file:// ok=${C} bytes=${N?.byteLength??`?`}`),!C)throw new FetchError(`Failed to read file: ${n}`,`system`);let F=N,I=new Uint8Array(F.byteLength);I.set(F);let H=new Va(I);return t&&ge.log(`[fetch] file:// response created`),H}catch(n){let C=n instanceof Error?n:Error(String(n));throw t&&ge.warn(`[fetch] file:// FAIL: ${C.message}`),new FetchError(`request to ${S.url} failed, reason: ${C.message}`,`system`,C)}}let{signal:F}=S;if(F&&F.aborted)throw new AbortError(`The operation was aborted.`);let I,H;try{let t=await S._send(N);I=t.readable,H=t.cancellable}catch(t){if(F&&F.aborted)throw new AbortError(`The operation was aborted.`);let n=t instanceof Error?t:Error(String(t));throw new FetchError(`request to ${S.url} failed, reason: ${n.message}`,`system`,n)}let abortHandler=()=>{H.cancel()};F&&F.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{F&&F.removeEventListener(`abort`,abortHandler)};H.connect(()=>{I.destroy(new AbortError(`The operation was aborted.`))}),I.on(`error`,t=>{finalize()});let W=S._message,q=await loadSoup(),Y=wa._newFromSoupMessage(q,W),X=W.status_code,Z=W.get_reason_phrase();if(isRedirect(X)){let t=Y.get(`Location`),C=null;try{C=t===null?null:new Bn(t,S.url)}catch{if(S.redirect!==`manual`)throw I.destroy(),finalize(),new FetchError(`uri requested responds with an invalid redirect URL: ${t}`,`invalid-redirect`)}switch(S.redirect){case`error`:throw I.destroy(),finalize(),new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${S.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(C===null)break;if(S.counter>=S.follow)throw I.destroy(),finalize(),new FetchError(`maximum redirect reached at: ${S.url}`,`max-redirect`);let t={headers:new wa(S.headers),follow:S.follow,counter:S.counter+1,agent:S.agent,compress:S.compress,method:S.method,body:clone(S),signal:S.signal,size:S.size,referrer:S.referrer,referrerPolicy:S.referrerPolicy};if(!isDomainOrSubdomain(S.url,C)||!isSameProtocol(S.url,C))for(let n of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])t.headers.delete(n);if(X!==303&&S.body&&n.body instanceof ea.Readable)throw I.destroy(),finalize(),new FetchError(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(X===303||(X===301||X===302)&&S.method===`POST`)&&(t.method=`GET`,t.body=void 0,t.headers.delete(`content-length`));let N=parseReferrerPolicyFromHeader(Y);return N&&(t.referrerPolicy=N),await new Promise(t=>{I.once(`close`,()=>t()),I.resume()}),finalize(),fetch$1(new so(C,t))}default:throw I.destroy(),finalize(),TypeError(`Redirect option '${S.redirect}' is not a valid value of RequestRedirect`)}}let ne={url:S.url,status:X,statusText:Z,headers:Y,size:S.size,counter:S.counter,highWaterMark:S.highWaterMark},re=Y.get(`Content-Encoding`);if(!S.compress||S.method===`HEAD`||re===null||X===204||X===304)return finalize(),new Va(I,ne);if(typeof DecompressionStream<`u`){let t=null;if(re===`gzip`||re===`x-gzip`?t=`gzip`:(re===`deflate`||re===`x-deflate`)&&(t=`deflate`),t){let n=new te([await new Va(I,ne).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(t));return finalize(),new Va(n,ne)}}return finalize(),new Va(I,ne)}__name$1(fetch$1,`fetch`);const lo=globalThis;globalThis.fetch===void 0&&(lo.fetch=fetch$1),globalThis.Headers===void 0&&(lo.Headers=wa),globalThis.Request===void 0&&(lo.Request=so),globalThis.Response===void 0&&(lo.Response=Va);const uo=globalThis;globalThis.ByteLengthQueuingStrategy===void 0&&(uo.ByteLengthQueuingStrategy=ii),globalThis.CountQueuingStrategy===void 0&&(uo.CountQueuingStrategy=ai);const fo=globalThis;function isNativeStreamUsable$2(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$2,`isNativeStreamUsable`),isNativeStreamUsable$2(globalThis.ReadableStream,`getReader`)||(fo.ReadableStream=ti),fo.ReadableStreamBYOBReader===void 0&&(fo.ReadableStreamBYOBReader=ReadableStreamBYOBReader),fo.ReadableStreamBYOBRequest===void 0&&(fo.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest),fo.ReadableByteStreamController===void 0&&(fo.ReadableByteStreamController=ReadableByteStreamController),fo.ReadableStreamDefaultController===void 0&&(fo.ReadableStreamDefaultController=ReadableStreamDefaultController),fo.ReadableStreamDefaultReader===void 0&&(fo.ReadableStreamDefaultReader=ReadableStreamDefaultReader);const po=globalThis;globalThis.TextEncoderStream===void 0&&(po.TextEncoderStream=oi),globalThis.TextDecoderStream===void 0&&(po.TextDecoderStream=si);function isNativeStreamUsable$1(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}if(__name$1(isNativeStreamUsable$1,`isNativeStreamUsable`),!isNativeStreamUsable$1(globalThis.TransformStream,`readable`)){let t=globalThis;t.TransformStream=ri}function isNativeStreamUsable(t,n){try{return typeof t==`function`?typeof t.prototype?.[n]==`function`:!1}catch{return!1}}if(!isNativeStreamUsable(globalThis.WritableStream,`getWriter`)){let t=globalThis;t.WritableStream=ni}var CryptoKey=class{type;extractable;algorithm;usages;_handle;constructor(t,n,S,C,N){this.type=t,this.extractable=n,this.algorithm=Object.freeze({...S}),this.usages=Object.freeze([...C]),this._handle=N}get[Symbol.toStringTag](){return`CryptoKey`}};const mo=Uint8Array.of(166,166,166,166,166,166,166,166);function xorCounter(t,n){for(let S=0;S<8&&n>0;S++)t[7-S]^=n&255,n=Math.floor(n/256)}function aesKeyWrap(t,n){if(t.length<16||t.length%8!=0)throw new DOMException(`AES-KW: key data must be a multiple of 8 bytes and at least 16 bytes`,`OperationError`);let S=t.length/8,C=mo.slice(),N=[];for(let n=0;n<S;n++)N.push(t.slice(n*8,n*8+8));let F=new Uint8Array(16);for(let t=0;t<=5;t++)for(let I=1;I<=S;I++){F.set(C,0),F.set(N[I-1],8);let H=n(F);C.set(H.subarray(0,8)),xorCounter(C,S*t+I),N[I-1]=H.slice(8,16)}let I=new Uint8Array((S+1)*8);I.set(C,0);for(let t=0;t<S;t++)I.set(N[t],(t+1)*8);return I}function aesKeyUnwrap(t,n){if(t.length<24||t.length%8!=0)throw new DOMException(`AES-KW: wrapped key must be a multiple of 8 bytes and at least 24 bytes`,`OperationError`);let S=t.length/8-1,C=t.slice(0,8),N=[];for(let n=0;n<S;n++)N.push(t.slice((n+1)*8,(n+2)*8));let F=new Uint8Array(16);for(let t=5;t>=0;t--)for(let I=S;I>=1;I--){xorCounter(C,S*t+I),F.set(C,0),F.set(N[I-1],8);let H=n(F);C.set(H.subarray(0,8)),N[I-1]=H.slice(8,16)}let I=!0;for(let t=0;t<8;t++)C[t]!==mo[t]&&(I=!1);if(!I)throw new DOMException(`AES-KW: integrity check failed`,`OperationError`);let H=new Uint8Array(S*8);for(let t=0;t<S;t++)H.set(N[t],t*8);return H}function normalizeAlgorithm$1(t){if(typeof t==`string`)return{name:t};if(!t||typeof t.name!=`string`)throw TypeError(`Algorithm must have a name property`);return t}__name$1(normalizeAlgorithm$1,`normalizeAlgorithm`);const ho={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function toNodeHashName(t){let n=ho[t.toUpperCase()]||ho[t];if(!n)throw new tr(`Unrecognized hash name: ${t}`,`NotSupportedError`);return n}const go={"P-256":`prime256v1`,"P-384":`secp384r1`,"P-521":`secp521r1`};function toNodeCurveName(t){let n=go[t];if(!n)throw new tr(`Unrecognized curve name: ${t}`,`NotSupportedError`);return n}function hashSize$1(t){switch(toNodeHashName(t)){case`sha1`:return 20;case`sha256`:return 32;case`sha384`:return 48;case`sha512`:return 64;default:throw new tr(`Unsupported hash: ${t}`,`NotSupportedError`)}}__name$1(hashSize$1,`hashSize`);function validateUsages(t,n){for(let S of t)if(!n.includes(S))throw new tr(`Invalid key usage: ${S}`,`SyntaxError`);if(t.length===0)throw new tr(`Key usages must not be empty`,`SyntaxError`)}function checkUsage(t,n){if(!t.usages.includes(n))throw new tr(`Key does not support the '${n}' usage`,`InvalidAccessError`)}const _o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,vo=new Uint8Array(128);for(let t=0;t<64;t++)vo[_o.charCodeAt(t)]=t;function bytesToBase64$1(t){let n=``,S=t.length;for(let C=0;C<S;C+=3){let N=t[C],F=C+1<S?t[C+1]:0,I=C+2<S?t[C+2]:0;n+=_o[N>>2&63],n+=_o[(N<<4|F>>4)&63],n+=C+1<S?_o[(F<<2|I>>6)&63]:`=`,n+=C+2<S?_o[I&63]:`=`}return n}__name$1(bytesToBase64$1,`bytesToBase64`);function base64ToBytes(t){let n=t;for(;n.endsWith(`=`);)n=n.slice(0,-1);let S=[],C=0,N=0;for(let t=0;t<n.length;t++)N=N<<6|vo[n.charCodeAt(t)],C+=6,C>=8&&(C-=8,S.push(N>>C&255));return new Uint8Array(S)}function base64urlEncode(t){return bytesToBase64$1(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function base64urlDecode(t){let n=t.replace(/-/g,`+`).replace(/_/g,`/`);for(;n.length%4;)n+=`=`;return base64ToBytes(n)}function toUint8Array(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`Expected BufferSource`)}function checkAlgorithmMatch(t,n){if(t.algorithm.name.toUpperCase()!==n.toUpperCase())throw new tr(`Key algorithm mismatch`,`InvalidAccessError`)}const yo={Ed25519:{public:[`verify`],private:[`sign`]},X25519:{public:[],private:[`deriveKey`,`deriveBits`]}},bo={Ed25519:[48,42,48,5,6,3,43,101,112,3,33,0],X25519:[48,42,48,5,6,3,43,101,110,3,33,0]};function cfrgName(t){let n=t.toUpperCase();if(n===`ED25519`)return`Ed25519`;if(n===`X25519`)return`X25519`}function assertUsages(t,n){for(let S of t)if(!n.includes(S))throw new tr(`Unsupported key usage: ${S}`,`SyntaxError`)}function toArrayBuffer(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function keyObjectOf(t){return t._handle.keyObject}function cfrgGenerateKey(t,n,S,C){assertUsages(C,[...yo[n].public,...yo[n].private]);let N=C.filter(t=>yo[n].private.includes(t));if(N.length===0)throw new tr(`Usages cannot be empty when creating a key.`,`SyntaxError`);let F=C.filter(t=>yo[n].public.includes(t)),{publicKey:I,privateKey:H}=t.generateKeyPairSync(n.toLowerCase());return{publicKey:new CryptoKey(`public`,!0,{name:n},F,{keyObject:I}),privateKey:new CryptoKey(`private`,S,{name:n},N,{keyObject:H})}}function validateJwk(t,n,S,C){if(typeof t!=`object`||!t)throw new tr(`Invalid keyData`,`DataError`);if(t.kty!==`OKP`)throw new tr(`Invalid JWK "kty" Parameter`,`DataError`);if(t.crv!==n)throw new tr(`JWK "crv" Parameter and algorithm name mismatch`,`DataError`);if(n===`Ed25519`&&t.alg!==void 0&&t.alg!==`Ed25519`&&t.alg!==`EdDSA`)throw new tr(`JWK "alg" does not match the requested algorithm`,`DataError`);let N=n===`X25519`?`enc`:`sig`;if(C.length>0&&t.use!==void 0&&t.use!==N)throw new tr(`Invalid JWK "use" Parameter`,`DataError`);if(t.key_ops!==void 0){if(!Array.isArray(t.key_ops))throw new tr(`Invalid JWK "key_ops" Parameter`,`DataError`);for(let n of C)if(!t.key_ops.includes(n))throw new tr(`Key operations and usage mismatch`,`DataError`)}if(t.ext===!1&&S)throw new tr(`JWK "ext" Parameter and extractable mismatch`,`DataError`);if(typeof t.x!=`string`||t.d!==void 0&&typeof t.d!=`string`)throw new tr(`Invalid keyData`,`DataError`)}function cfrgImportKey(t,n,S,C,N,F){let I,H,importOrDataError=t=>{try{return t()}catch(t){throw new tr(`Invalid keyData: ${t.message}`,`DataError`)}};switch(n){case`raw`:{assertUsages(F,yo[C].public);let n=toUint8Array(S);if(n.length!==32)throw new tr(`Invalid keyData`,`DataError`);let N=new Uint8Array(44);N.set(bo[C],0),N.set(n,12),I=importOrDataError(()=>t.createPublicKey({key:N,format:`der`,type:`spki`})),H=`public`;break}case`spki`:{assertUsages(F,yo[C].public);let n=toUint8Array(S);I=importOrDataError(()=>t.createPublicKey({key:n,format:`der`,type:`spki`})),H=`public`;break}case`pkcs8`:{assertUsages(F,yo[C].private);let n=toUint8Array(S);I=importOrDataError(()=>t.createPrivateKey({key:n,format:`der`,type:`pkcs8`})),H=`private`;break}case`jwk`:{let n=S;if(validateJwk(n,C,N,F),H=n.d===void 0?`public`:`private`,assertUsages(F,yo[C][H]),H===`private`){if(I=importOrDataError(()=>t.createPrivateKey({key:n,format:`jwk`})),t.createPublicKey(I).export({format:`jwk`}).x!==n.x)throw new tr(`Invalid JWK: "x" does not match "d"`,`DataError`)}else{if(base64urlDecode(n.x).length!==32)throw new tr(`Invalid keyData`,`DataError`);I=importOrDataError(()=>t.createPublicKey({key:n,format:`jwk`}))}break}default:throw new tr(`Unsupported format: ${n}`,`NotSupportedError`)}if(I.asymmetricKeyType!==C.toLowerCase())throw new tr(`Invalid key type`,`DataError`);if(H===`private`&&F.length===0)throw new tr(`Usages cannot be empty when importing a private key.`,`SyntaxError`);return new CryptoKey(H,N,{name:C},F,{keyObject:I})}function wrongKindForFormat(t,n){return new tr(`Unable to export ${t.algorithm.name} ${t.type} key using ${n} format`,`InvalidAccessError`)}function cfrgExportKey(t,n){let S=keyObjectOf(n);switch(t){case`raw`:{if(n.type!==`public`)throw wrongKindForFormat(n,t);let C=S.export({format:`jwk`}).x;return toArrayBuffer(base64urlDecode(C))}case`spki`:if(n.type!==`public`)throw wrongKindForFormat(n,t);return toArrayBuffer(S.export({format:`der`,type:`spki`}));case`pkcs8`:if(n.type!==`private`)throw wrongKindForFormat(n,t);return toArrayBuffer(S.export({format:`der`,type:`pkcs8`}));case`jwk`:{let t=S.export({format:`jwk`}),C={kty:`OKP`,crv:n.algorithm.name,x:t.x};return n.type===`private`&&(C.d=t.d),n.algorithm.name===`Ed25519`&&(C.alg=`Ed25519`),C.key_ops=[...n.usages],C.ext=n.extractable,C}default:throw new tr(`Unsupported export format: ${t}`,`NotSupportedError`)}}function ed25519Sign$1(t,n,S){if(n.type!==`private`)throw new tr(`Key must be a private key`,`InvalidAccessError`);return toArrayBuffer(t.sign(null,S,keyObjectOf(n)))}__name$1(ed25519Sign$1,`ed25519Sign`);function ed25519Verify$1(t,n,S,C){if(n.type!==`public`)throw new tr(`Key must be a public key`,`InvalidAccessError`);return t.verify(null,C,keyObjectOf(n),S)}__name$1(ed25519Verify$1,`ed25519Verify`);function x25519DeriveBits(t,n,S,C){if(n.type!==`private`)throw new tr(`baseKey must be a private key`,`InvalidAccessError`);if(!(S instanceof CryptoKey)||S.type!==`public`)throw new tr(`algorithm.public must be a public key`,`InvalidAccessError`);if(S.algorithm.name!==n.algorithm.name)throw new tr(`The public and private keys must be of the same type`,`InvalidAccessError`);let N;try{N=new Uint8Array(t.diffieHellman({privateKey:keyObjectOf(n),publicKey:keyObjectOf(S)}))}catch(t){throw new tr(`Deriving bits failed: ${t.message}`,`OperationError`)}if(C==null)return toArrayBuffer(N);if(C>N.length*8)throw new tr(`derived bit length is too small`,`OperationError`);let F=N.slice(0,Math.ceil(C/8));return C%8!=0&&(F[F.length-1]&=255<<8-C%8),toArrayBuffer(F)}var xo,So=__esmMin(()=>{xo={RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_PKCS1_PSS_PADDING:6,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8}});function timingSafeEqual(t,n){if(t.length!==n.length)throw RangeError(`Input buffers must have the same byte length`);let S=0;for(let C=0;C<t.length;C++)S|=t[C]^n[C];return S===0}var Co=__esmMin(()=>{});function gmul(t,n){let S=0;for(let C=0;C<8;C++){n&1&&(S^=t);let C=t&128;t=t<<1&255,C&&(t^=27),n>>=1}return S}function keyExpansion(t){let n=t.length/4,S=n+6,C=4*(S+1),N=Array.from({length:C});for(let S=0;S<n;S++)N[S]=new Uint8Array([t[4*S],t[4*S+1],t[4*S+2],t[4*S+3]]);for(let t=n;t<C;t++){let S=new Uint8Array(N[t-1]);t%n===0?S=new Uint8Array([wo[S[1]]^Eo[t/n-1],wo[S[2]],wo[S[3]],wo[S[0]]]):n>6&&t%n===4&&(S=new Uint8Array([wo[S[0]],wo[S[1]],wo[S[2]],wo[S[3]]])),N[t]=new Uint8Array(4);for(let C=0;C<4;C++)N[t][C]=N[t-n][C]^S[C]}let F=[];for(let t=0;t<=S;t++){let n=new Uint8Array(16);for(let S=0;S<4;S++)n[4*S]=N[4*t+S][0],n[4*S+1]=N[4*t+S][1],n[4*S+2]=N[4*t+S][2],n[4*S+3]=N[4*t+S][3];F.push(n)}return F}function aesEncryptBlock(t,n){let S=new Uint8Array(t),C=n.length-1;for(let t=0;t<16;t++)S[t]^=n[0][t];for(let t=1;t<C;t++){for(let t=0;t<16;t++)S[t]=wo[S[t]];let C=S[1];S[1]=S[5],S[5]=S[9],S[9]=S[13],S[13]=C;let N=S[2],F=S[6];S[2]=S[10],S[6]=S[14],S[10]=N,S[14]=F;let I=S[15];S[15]=S[11],S[11]=S[7],S[7]=S[3],S[3]=I;for(let t=0;t<4;t++){let n=t*4,C=S[n],N=S[n+1],F=S[n+2],I=S[n+3];S[n]=gmul(2,C)^gmul(3,N)^F^I,S[n+1]=C^gmul(2,N)^gmul(3,F)^I,S[n+2]=C^N^gmul(2,F)^gmul(3,I),S[n+3]=gmul(3,C)^N^F^gmul(2,I)}for(let C=0;C<16;C++)S[C]^=n[t][C]}for(let t=0;t<16;t++)S[t]=wo[S[t]];let N=S[1];S[1]=S[5],S[5]=S[9],S[9]=S[13],S[13]=N;let F=S[2],I=S[6];S[2]=S[10],S[6]=S[14],S[10]=F,S[14]=I;let H=S[15];S[15]=S[11],S[11]=S[7],S[7]=S[3],S[3]=H;for(let t=0;t<16;t++)S[t]^=n[C][t];return S}function aesDecryptBlock(t,n){let S=new Uint8Array(t),C=n.length-1;for(let t=0;t<16;t++)S[t]^=n[C][t];for(let t=C-1;t>0;t--){let C=S[13];S[13]=S[9],S[9]=S[5],S[5]=S[1],S[1]=C;let N=S[10],F=S[14];S[10]=S[2],S[14]=S[6],S[2]=N,S[6]=F;let I=S[3];S[3]=S[7],S[7]=S[11],S[11]=S[15],S[15]=I;for(let t=0;t<16;t++)S[t]=To[S[t]];for(let C=0;C<16;C++)S[C]^=n[t][C];for(let t=0;t<4;t++){let n=t*4,C=S[n],N=S[n+1],F=S[n+2],I=S[n+3];S[n]=gmul(14,C)^gmul(11,N)^gmul(13,F)^gmul(9,I),S[n+1]=gmul(9,C)^gmul(14,N)^gmul(11,F)^gmul(13,I),S[n+2]=gmul(13,C)^gmul(9,N)^gmul(14,F)^gmul(11,I),S[n+3]=gmul(11,C)^gmul(13,N)^gmul(9,F)^gmul(14,I)}}let N=S[13];S[13]=S[9],S[9]=S[5],S[5]=S[1],S[1]=N;let F=S[10],I=S[14];S[10]=S[2],S[14]=S[6],S[2]=F,S[6]=I;let H=S[3];S[3]=S[7],S[7]=S[11],S[11]=S[15],S[15]=H;for(let t=0;t<16;t++)S[t]=To[S[t]];for(let t=0;t<16;t++)S[t]^=n[0][t];return S}function incrementCounter(t){for(let n=15;n>=0&&(t[n]=t[n]+1&255,t[n]===0);n--);}function gcmJ0(t,n){if(n.length===12){let t=new Uint8Array(16);return t.set(n),t[15]=1,t}return ghash(t,new Uint8Array,n)}function gcmIncrementCounter(t){for(let n=15;n>=12&&(t[n]=t[n]+1&255,t[n]===0);n--);}function gfMul(t,n){let S=new Uint8Array(16),C=new Uint8Array(t);for(let t=0;t<128;t++){if(n[t>>>3]&1<<7-(t&7))for(let t=0;t<16;t++)S[t]^=C[t];let N=C[15]&1;for(let t=15;t>0;t--)C[t]=C[t]>>>1|(C[t-1]&1)<<7;C[0]>>>=1,N&&(C[0]^=225)}return S}function ghash(t,n,S){let C=new Uint8Array(16),N=Math.ceil(n.length/16)||0;for(let S=0;S<N;S++){let N=S*16,F=Math.min(N+16,n.length);for(let t=0;t<16;t++){let S=N+t;S<F&&(C[t]^=n[S])}let I=gfMul(C,t);C.set(I)}let F=Math.ceil(S.length/16)||0;for(let n=0;n<F;n++){let N=n*16,F=Math.min(N+16,S.length);for(let t=0;t<16;t++){let n=N+t;n<F&&(C[t]^=S[n])}let I=gfMul(C,t);C.set(I)}let I=new Uint8Array(16),H=n.length*8,W=S.length*8,q=Math.floor(H/4294967296),Y=H>>>0;I[0]=q>>>24&255,I[1]=q>>>16&255,I[2]=q>>>8&255,I[3]=q&255,I[4]=Y>>>24&255,I[5]=Y>>>16&255,I[6]=Y>>>8&255,I[7]=Y&255;let X=Math.floor(W/4294967296),Z=W>>>0;I[8]=X>>>24&255,I[9]=X>>>16&255,I[10]=X>>>8&255,I[11]=X&255,I[12]=Z>>>24&255,I[13]=Z>>>16&255,I[14]=Z>>>8&255,I[15]=Z&255;for(let t=0;t<16;t++)C[t]^=I[t];let te=gfMul(C,t);return C.set(te),C}var wo,To,Eo,Do=__esmMin(()=>{wo=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),To=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]),Eo=[1,2,4,8,16,32,64,128,27,54]});function parseAlgorithm(t){let n=t.toLowerCase().match(/^aes-(128|192|256)-(cbc|ctr|ecb|cfb|ofb|gcm)$/);if(!n)throw Error(`Unsupported cipher algorithm: ${t}`);let S=parseInt(n[1]),C=n[2];return{keySize:S/8,ivSize:C===`ecb`?0:C===`gcm`?12:16,mode:C}}function toBuffer$2(t,n){return typeof t==`string`?Xe.from(t,n||`utf8`):Xe.from(t)}function encodeOutput(t,n){return n?Xe.from(t).toString(n):Xe.from(t)}function incompleteUtf8Tail(t){if(t.length===0)return 0;let n=t.length;for(let S=1;S<=Math.min(4,n);S++){let C=t[n-S];if(!(C&128))return 0;if((C&192)==128)continue;let N;if((C&224)==192)N=2;else if((C&240)==224)N=3;else if((C&248)==240)N=4;else return 0;return S<N?S:0}return 0}function pkcs7Pad(t){let n=16-t.length%16,S=new Uint8Array(t.length+n);S.set(t);for(let C=t.length;C<S.length;C++)S[C]=n;return S}function pkcs7Unpad(t){if(t.length===0||t.length%16!=0)throw Error(`bad decrypt`);let n=t[t.length-1];if(n===0||n>16)throw Error(`bad decrypt`);for(let S=t.length-n;S<t.length;S++)if(t[S]!==n)throw Error(`bad decrypt`);return new Uint8Array(t.slice(0,t.length-n))}var Oo=__esmMin(()=>{ot(),__name$1(toBuffer$2,`toBuffer`)});function createCipher(t,n){throw Error(`crypto.createCipher() is deprecated. Use createCipheriv() instead.`)}function createCipheriv(t,n,S){return new Cipher(t,typeof n==`string`?Xe.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?Xe.from(S):new Uint8Array(S))}function createDecipher(t,n){throw Error(`crypto.createDecipher() is deprecated. Use createDecipheriv() instead.`)}function createDecipheriv(t,n,S){return new Decipher(t,typeof n==`string`?Xe.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?Xe.from(S):new Uint8Array(S))}function getCiphers(){return[`aes-128-cbc`,`aes-128-ecb`,`aes-192-cbc`,`aes-192-ecb`,`aes-256-cbc`,`aes-256-ecb`,`aes-128-ctr`,`aes-192-ctr`,`aes-256-ctr`,`aes-128-cfb`,`aes-192-cfb`,`aes-256-cfb`,`aes-128-gcm`,`aes-192-gcm`,`aes-256-gcm`]}var CipherBase,Cipher,Decipher,ko=__esmMin(()=>{Do(),Oo(),ot(),CipherBase=class{_roundKeys;_iv;_mode;_buffer=new Uint8Array;_autoPadding=!0;_finalized=!1;constructor(t,n,S){let C=parseAlgorithm(t);if(n.length!==C.keySize)throw Error(`Invalid key length ${n.length}, expected ${C.keySize} for ${t}`);if(C.mode===`gcm`){if(!S||S.length===0)throw Error(`Invalid IV length 0 for ${t}`)}else if(C.ivSize>0&&(!S||S.length!==C.ivSize))throw Error(`Invalid IV length ${S?.length??0}, expected ${C.ivSize} for ${t}`);this._roundKeys=keyExpansion(n),this._iv=S?new Uint8Array(S):new Uint8Array(16),this._mode=C.mode}setAutoPadding(t){return this._autoPadding=t,this}},Cipher=class extends CipherBase{_prevBlock;_counter;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmAuthTag=null;_gcmAADSet=!1;constructor(t,n,S){super(t,n,S),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=gcmJ0(this._gcmH,this._iv),this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(t){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(t),this._gcmAADSet=!0,this}getAuthTag(){if(this._mode!==`gcm`)throw Error(`getAuthTag is only supported in GCM mode`);if(!this._gcmAuthTag)throw Error(`getAuthTag must be called after final()`);return Xe.from(this._gcmAuthTag)}update(t,n,S){let C=toBuffer$2(t,n),N=new Uint8Array(this._buffer.length+C.length);if(N.set(this._buffer),N.set(C,this._buffer.length),this._mode===`gcm`){let t=this._processGcmEncrypt(N);return this._buffer=new Uint8Array,encodeOutput(t,S)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let t=this._processStream(N);return this._buffer=new Uint8Array,encodeOutput(t,S)}let F=Math.floor(N.length/16)*16,I=[];for(let t=0;t<F;t+=16){let n=N.slice(t,t+16);I.push(this._encryptBlock(n))}this._buffer=N.slice(F);let H=new Uint8Array(I.length*16);for(let t=0;t<I.length;t++)H.set(I[t],t*16);return encodeOutput(H,S)}final(t){if(this._finalized)throw Error(`Cipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let n=new Uint8Array;this._buffer.length>0&&(n=this._processGcmEncrypt(this._buffer),this._buffer=new Uint8Array);let S=new Uint8Array(this._gcmCiphertextLen),C=0;for(let t of this._gcmCiphertext)S.set(t,C),C+=t.length;let N=ghash(this._gcmH,this._gcmAAD,S),F=aesEncryptBlock(this._gcmJ0,this._roundKeys),I=new Uint8Array(16);for(let t=0;t<16;t++)I[t]=N[t]^F[t];return this._gcmAuthTag=Xe.from(I),encodeOutput(n,t)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let n=this._processStream(this._buffer);return this._buffer=new Uint8Array,encodeOutput(n,t)}return encodeOutput(new Uint8Array,t)}let n=this._buffer;if(this._autoPadding)n=pkcs7Pad(n);else if(n.length%16!=0)throw Error(`data not multiple of block size`);let S=[];for(let t=0;t<n.length;t+=16)S.push(this._encryptBlock(n.slice(t,t+16)));if(this._buffer=new Uint8Array,S.length===0)return encodeOutput(new Uint8Array,t);let C=new Uint8Array(S.length*16);for(let t=0;t<S.length;t++)C.set(S[t],t*16);return encodeOutput(C,t)}_encryptBlock(t){if(this._mode===`cbc`){let n=new Uint8Array(16);for(let S=0;S<16;S++)n[S]=t[S]^this._prevBlock[S];let S=aesEncryptBlock(n,this._roundKeys);return this._prevBlock=S,S}else if(this._mode===`ecb`)return aesEncryptBlock(t,this._roundKeys);throw Error(`Block encryption not supported for mode: ${this._mode}`)}_processStream(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];incrementCounter(this._counter)}return n}_processGcmEncrypt(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];gcmIncrementCounter(this._counter)}return this._gcmCiphertext.push(new Uint8Array(n)),this._gcmCiphertextLen+=n.length,n}},Decipher=class extends CipherBase{_prevBlock;_counter;_pendingUtf8=new Uint8Array;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmExpectedTag=null;_gcmAADSet=!1;constructor(t,n,S){super(t,n,S),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=gcmJ0(this._gcmH,this._iv),this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(t){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(t),this._gcmAADSet=!0,this}setAuthTag(t){if(this._mode!==`gcm`)throw Error(`setAuthTag is only supported in GCM mode`);return this._gcmExpectedTag=Xe.from(t),this}_encodeWithUtf8Handling(t,n,S){if(!n||n!==`utf8`&&n!==`utf-8`)return encodeOutput(t,n);let C;if(this._pendingUtf8.length>0?(C=new Uint8Array(this._pendingUtf8.length+t.length),C.set(this._pendingUtf8),C.set(t,this._pendingUtf8.length),this._pendingUtf8=new Uint8Array):C=t,!S){let t=incompleteUtf8Tail(C);t>0&&(this._pendingUtf8=new Uint8Array(C.slice(C.length-t)),C=new Uint8Array(C.slice(0,C.length-t)))}return Xe.from(C).toString(`utf8`)}update(t,n,S){let C=toBuffer$2(t,n),N=new Uint8Array(this._buffer.length+C.length);if(N.set(this._buffer),N.set(C,this._buffer.length),this._mode===`gcm`){this._gcmCiphertext.push(new Uint8Array(N)),this._gcmCiphertextLen+=N.length;let t=this._processGcmDecrypt(N);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(t,S,!1)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let t=this._processStream(N);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(t,S,!1)}let F=Math.floor(N.length/16);if(F===0)return this._buffer=N,this._encodeWithUtf8Handling(new Uint8Array,S,!1);let I=(this._autoPadding?F-1:F)*16,H=[];for(let t=0;t<I;t+=16){let n=N.slice(t,t+16);H.push(this._decryptBlock(n))}this._buffer=N.slice(I);let W=new Uint8Array(H.length*16);for(let t=0;t<H.length;t++)W.set(H[t],t*16);return this._encodeWithUtf8Handling(W,S,!1)}final(t){if(this._finalized)throw Error(`Decipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let n=new Uint8Array;if(this._buffer.length>0&&(this._gcmCiphertext.push(new Uint8Array(this._buffer)),this._gcmCiphertextLen+=this._buffer.length,n=this._processGcmDecrypt(this._buffer),this._buffer=new Uint8Array),!this._gcmExpectedTag)throw Error(`Unsupported state or unable to authenticate data`);let S=new Uint8Array(this._gcmCiphertextLen),C=0;for(let t of this._gcmCiphertext)S.set(t,C),C+=t.length;let N=ghash(this._gcmH,this._gcmAAD,S),F=aesEncryptBlock(this._gcmJ0,this._roundKeys),I=new Uint8Array(16);for(let t=0;t<16;t++)I[t]=N[t]^F[t];let H=this._gcmExpectedTag,W=Math.min(H.length,16),q=0;for(let t=0;t<W;t++)q|=I[t]^H[t];if(q!==0)throw Error(`Unsupported state or unable to authenticate data`);return this._encodeWithUtf8Handling(n,t,!0)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let n=this._processStream(this._buffer);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(n,t,!0)}return this._encodeWithUtf8Handling(new Uint8Array,t,!0)}if(this._buffer.length===0)return this._encodeWithUtf8Handling(new Uint8Array,t,!0);if(this._buffer.length%16!=0)throw Error(`bad decrypt`);let n=[];for(let t=0;t<this._buffer.length;t+=16)n.push(this._decryptBlock(this._buffer.slice(t,t+16)));let S=new Uint8Array(n.length*16);for(let t=0;t<n.length;t++)S.set(n[t],t*16);let C=this._autoPadding?pkcs7Unpad(S):S;return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(C,t,!0)}_decryptBlock(t){if(this._mode===`cbc`){let n=aesDecryptBlock(t,this._roundKeys),S=new Uint8Array(16);for(let t=0;t<16;t++)S[t]=n[t]^this._prevBlock[t];return this._prevBlock=new Uint8Array(t),S}else if(this._mode===`ecb`)return aesDecryptBlock(t,this._roundKeys);throw Error(`Block decryption not supported for mode: ${this._mode}`)}_processStream(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];incrementCounter(this._counter)}return n}_processGcmDecrypt(t){let n=new Uint8Array(t.length);for(let S=0;S<t.length;S+=16){let C=aesEncryptBlock(this._counter,this._roundKeys),N=Math.min(16,t.length-S);for(let F=0;F<N;F++)n[S+F]=t[S+F]^C[F];gcmIncrementCounter(this._counter)}return n}}});function pemToDer(t){let n=t.trim().split(/\r?\n/),S=n.findIndex(t=>t.startsWith(`-----BEGIN `));if(S===-1)throw Error(`Invalid PEM: no BEGIN line found`);let C=n[S].match(/^-----BEGIN (.+)-----$/);if(!C)throw Error(`Invalid PEM header format`);let N=C[1],F=n.findIndex((t,n)=>n>S&&t.startsWith(`-----END `));if(F===-1)throw Error(`Invalid PEM: no END line found`);let I=n.slice(S+1,F).join(``),H=Xe.from(I,`base64`);return{type:N,der:new Uint8Array(H.buffer,H.byteOffset,H.byteLength)}}function parseTlv(t,n){if(n>=t.length)throw Error(`ASN.1 parse error: unexpected end of data`);let S=t[n++],C,N=t[n++];if(N<128)C=N;else{let S=N&127;if(S===0)throw Error(`ASN.1 parse error: indefinite length not supported`);C=0;for(let N=0;N<S;N++)C=C<<8|t[n++]}let F=t.slice(n,n+C),I=n+C,H={tag:S,data:F};return S===48&&(H.children=parseSequenceChildren(F)),{value:H,next:I}}function parseSequenceChildren(t){let n=[],S=0;for(;S<t.length;){let{value:C,next:N}=parseTlv(t,S);n.push(C),S=N}return n}function parseDer(t){let{value:n}=parseTlv(t,0);return n}function integerToBigInt(t){let n=0;for(;n<t.length-1&&t[n]===0;)n++;let S=0n;for(let C=n;C<t.length;C++)S=S<<8n|BigInt(t[C]);return S}function okpCurveForOid(t){if(oidsEqual(t,Mo))return`ed25519`;if(oidsEqual(t,jo))return`x25519`}function oidForOkpCurve(t){return t===`ed25519`?Mo:jo}function oidsEqual(t,n){if(t.length!==n.length)return!1;for(let S=0;S<t.length;S++)if(t[S]!==n[S])return!1;return!0}function parseRsaPublicKeyPkcs1(t){let n=t.children;if(!n||n.length<2)throw Error(`Invalid PKCS#1 RSAPublicKey structure`);return{n:integerToBigInt(n[0].data),e:integerToBigInt(n[1].data)}}function parseRsaPrivateKeyPkcs1(t){let n=t.children;if(!n||n.length<6)throw Error(`Invalid PKCS#1 RSAPrivateKey structure`);return{n:integerToBigInt(n[1].data),e:integerToBigInt(n[2].data),d:integerToBigInt(n[3].data),p:integerToBigInt(n[4].data),q:integerToBigInt(n[5].data)}}function algorithmOid(t){let n=t?.children?.[0];if(!n||n.tag!==6)throw Error(`Invalid AlgorithmIdentifier`);if(okpCurveForOid(n.data)&&(t?.children?.length??0)!==1)throw Error(`Invalid AlgorithmIdentifier: parameters must be absent (RFC 8410)`);return n.data}function parseSubjectPublicKeyInfo(t){let n=t.children;if(!n||n.length<2)throw Error(`Invalid SubjectPublicKeyInfo structure`);let S=algorithmOid(n[0]),C=n[1];if(C.tag!==3||C.data[0]!==0)throw Error(`Expected BIT STRING for public key data`);let N=C.data.slice(1),F=okpCurveForOid(S);if(F){if(N.length!==32)throw Error(`Invalid ${F} public key length: ${N.length}`);return{type:`okp-public`,curve:F,pub:N}}if(!oidsEqual(S,Ao))throw Error(`Unsupported key algorithm`);return{type:`rsa-public`,components:parseRsaPublicKeyPkcs1(parseDer(N))}}function parsePrivateKeyInfo(t){let n=t.children;if(!n||n.length<3)throw Error(`Invalid PrivateKeyInfo structure`);let S=algorithmOid(n[1]),C=n[2];if(C.tag!==4)throw Error(`Expected OCTET STRING for private key data`);let N=okpCurveForOid(S);if(N){let t=parseDer(C.data);if(t.tag!==4||t.data.length!==32)throw Error(`Invalid ${N} private key`);return{type:`okp-private`,curve:N,priv:t.data}}if(!oidsEqual(S,Ao))throw Error(`Unsupported key algorithm`);return{type:`rsa-private`,components:parseRsaPrivateKeyPkcs1(parseDer(C.data))}}function encodeLength(t){if(t<128)return new Uint8Array([t]);let n=[],S=t;for(;S>0;)n.unshift(S&255),S>>=8;return new Uint8Array([128|n.length,...n])}function encodeTlv(t,n){let S=encodeLength(n.length),C=new Uint8Array(1+S.length+n.length);return C[0]=t,C.set(S,1),C.set(n,1+S.length),C}function bigintToAsn1Integer(t){if(t===0n)return encodeTlv(2,new Uint8Array([0]));let n=t.toString(16),S=n.length%2?`0`+n:n,C=[];for(let t=0;t<S.length;t+=2)C.push(parseInt(S.substring(t,t+2),16));return C[0]&128&&C.unshift(0),encodeTlv(2,new Uint8Array(C))}function encodeSequence(t){let n=0;for(let S of t)n+=S.length;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.length;return encodeTlv(48,S)}function encodeBitString(t){let n=new Uint8Array(1+t.length);return n[0]=0,n.set(t,1),encodeTlv(3,n)}function encodeOctetString(t){return encodeTlv(4,t)}function encodeOid(t){return encodeTlv(6,t)}function encodeNull(){return new Uint8Array([5,0])}function encodeRsaPublicKeyPkcs1(t){return encodeSequence([bigintToAsn1Integer(t.n),bigintToAsn1Integer(t.e)])}function encodeSubjectPublicKeyInfo(t){return encodeSequence([encodeSequence([encodeOid(Ao),encodeNull()]),encodeBitString(encodeRsaPublicKeyPkcs1(t))])}function encodeRsaPrivateKeyPkcs1(t){let n=t.d%(t.p-1n),S=t.d%(t.q-1n),C=modInverse$2(t.q,t.p);return encodeSequence([bigintToAsn1Integer(0n),bigintToAsn1Integer(t.n),bigintToAsn1Integer(t.e),bigintToAsn1Integer(t.d),bigintToAsn1Integer(t.p),bigintToAsn1Integer(t.q),bigintToAsn1Integer(n),bigintToAsn1Integer(S),bigintToAsn1Integer(C)])}function encodePrivateKeyInfo(t){let n=encodeSequence([encodeOid(Ao),encodeNull()]),S=encodeOctetString(encodeRsaPrivateKeyPkcs1(t));return encodeSequence([bigintToAsn1Integer(0n),n,S])}function encodeOkpSubjectPublicKeyInfo(t,n){return encodeSequence([encodeSequence([encodeOid(oidForOkpCurve(t))]),encodeBitString(n)])}function encodeOkpPrivateKeyInfo(t,n){return encodeSequence([bigintToAsn1Integer(0n),encodeSequence([encodeOid(oidForOkpCurve(t))]),encodeOctetString(encodeOctetString(n))])}function derToPem(t,n){let S=Xe.from(t).toString(`base64`),C=[`-----BEGIN ${n}-----`];for(let t=0;t<S.length;t+=64)C.push(S.substring(t,t+64));return C.push(`-----END ${n}-----`),C.join(`
15
15
  `)}function modInverse$2(t,n){let[S,C]=[t%n,n],[N,F]=[1n,0n];for(;C!==0n;){let t=S/C;[S,C]=[C,S-t*C],[N,F]=[F,N-t*F]}return(N%n+n)%n}function parseX509(t){let{der:n}=pemToDer(t);return parseX509Der(n)}function parseX509Der(t){let n=parseDer(t);if(n.tag!==48||!n.children||n.children.length<3)throw Error(`Invalid X.509 certificate structure`);let S=n.children[0],C=n.children[1],N=n.children[2];if(!S.children||S.children.length<6)throw Error(`Invalid TBSCertificate structure`);let F=0;S.children[0].tag===160&&F++;let I=integerToBigInt(S.children[F].data);F++,F++;let H=parseDN(S.children[F]);F++;let W=S.children[F],q=parseAsn1Time(W.children[0]),Y=parseAsn1Time(W.children[1]);F++;let X=parseDN(S.children[F]);F++;let Z=null,te=`unknown`;if(F<S.children.length){let t=S.children[F];try{if(t.children&&t.children.length>=2){let n=t.children[0];if(n.children&&n.children.length>=1){let S=n.children[0];S.tag===6&&oidsEqual(S.data,Ao)&&(te=`rsa`,Z=parseSubjectPublicKeyInfo(t).components)}}}catch{}F++}let ne,re;for(let t=F;t<S.children.length;t++){let n=S.children[t];if(n.tag===163&&n.data.length>0){let t=parseDer(n.data);if(t.children){re=t.children;let n=new Uint8Array([85,29,17]);for(let S of t.children)if(S.children&&S.children.length>=2){let t=S.children[0];if(t.tag===6&&oidsEqual(t.data,n)){let t=S.children[S.children.length-1];ne=parseSAN(t.data)}}}}}let ie=`unknown`;C.children&&C.children.length>=1&&(ie=oidToName(C.children[0].data));let ae=N.tag===3?N.data.slice(1):N.data;return{raw:t,tbsCertificate:S.data,serialNumber:I,issuer:H,subject:X,validFrom:q,validTo:Y,publicKey:Z,publicKeyAlgorithm:te,signatureAlgorithm:ie,signature:ae,subjectAltName:ne,extensions:re}}function decodeOidString(t){if(t.length===0)return``;let n=[];n.push(Math.floor(t[0]/40)),n.push(t[0]%40);let S=0;for(let C=1;C<t.length;C++)S=S<<7|t[C]&127,t[C]&128||(n.push(S),S=0);return n.join(`.`)}function oidToName(t){let n=decodeOidString(t);return Po[n]||n}function parseDN(t){if(!t.children)return``;let n=[];for(let S of t.children){let t=S.tag===49?parseSequenceChildren(S.data):S.children||[];for(let S of t)if(S.children&&S.children.length>=2){let t=S.children[0].data,C=decodeOidString(t),N=No[C]||C,F=S.children[1].data,I=new TextDecoder().decode(F);n.push(`${N}=${I}`)}}return n.join(`, `)}function parseAsn1Time(t){let n=new TextDecoder().decode(t.data);if(t.tag===23){let t=parseInt(n.substring(0,2),10);t=t>=50?1900+t:2e3+t;let S=parseInt(n.substring(2,4),10)-1,C=parseInt(n.substring(4,6),10),N=parseInt(n.substring(6,8),10),F=parseInt(n.substring(8,10),10),I=parseInt(n.substring(10,12),10);return new Date(Date.UTC(t,S,C,N,F,I))}if(t.tag===24){let t=parseInt(n.substring(0,4),10),S=parseInt(n.substring(4,6),10)-1,C=parseInt(n.substring(6,8),10),N=parseInt(n.substring(8,10),10),F=parseInt(n.substring(10,12),10),I=parseInt(n.substring(12,14),10);return new Date(Date.UTC(t,S,C,N,F,I))}throw Error(`Unsupported time tag: 0x${t.tag.toString(16)}`)}function parseSAN(t){let n=[];try{let S=parseDer(t);if(S.tag===48&&S.children){for(let t of S.children)if(t.tag===130)n.push(`DNS:`+new TextDecoder().decode(t.data));else if(t.tag===135){if(t.data.length===4)n.push(`IP Address:`+t.data.join(`.`));else if(t.data.length===16){let S=[];for(let n=0;n<16;n+=2)S.push((t.data[n]<<8|t.data[n+1]).toString(16));n.push(`IP Address:`+S.join(`:`))}}}}catch{}return n}function parsePemKey(t){let{type:n,der:S}=pemToDer(t);switch(n){case`RSA PUBLIC KEY`:return parseDerKey(S,`pkcs1`,`public`);case`PUBLIC KEY`:return parseDerKey(S,`spki`);case`RSA PRIVATE KEY`:return parseDerKey(S,`pkcs1`,`private`);case`PRIVATE KEY`:return parseDerKey(S,`pkcs8`);default:throw Error(`Unsupported PEM type: ${n}`)}}function parseDerKey(t,n,S){let C=parseDer(t);if(C.tag!==48)throw Error(`Invalid key format: expected top-level SEQUENCE`);switch(n){case`spki`:return parseSubjectPublicKeyInfo(C);case`pkcs8`:return parsePrivateKeyInfo(C);case`pkcs1`:return S===`public`?{type:`rsa-public`,components:parseRsaPublicKeyPkcs1(C)}:{type:`rsa-private`,components:parseRsaPrivateKeyPkcs1(C)}}}function rsaKeySize(t){let n=0,S=t;for(;S>0n;)n++,S>>=1n;return Math.ceil(n/8)}var Ao,jo,Mo,No,Po,Fo=__esmMin(()=>{ot(),Ao=new Uint8Array([42,134,72,134,247,13,1,1,1]),jo=new Uint8Array([43,101,110]),Mo=new Uint8Array([43,101,112]),__name$1(modInverse$2,`modInverse`),No={"2.5.4.3":`CN`,"2.5.4.6":`C`,"2.5.4.7":`L`,"2.5.4.8":`ST`,"2.5.4.10":`O`,"2.5.4.11":`OU`,"1.2.840.113549.1.9.1":`emailAddress`},Po={"1.2.840.113549.1.1.1":`rsaEncryption`,"1.2.840.113549.1.1.5":`sha1WithRSAEncryption`,"1.2.840.113549.1.1.11":`sha256WithRSAEncryption`,"1.2.840.113549.1.1.12":`sha384WithRSAEncryption`,"1.2.840.113549.1.1.13":`sha512WithRSAEncryption`}});function normalizeAlgorithm(t){return t.toLowerCase().replace(/-/g,``)}function hashSize(t){let n=normalizeAlgorithm(t),S=Io[n];if(S===void 0)throw Error(`Unknown hash algorithm: ${t}`);return S}function toBuffer$1(t,n){return typeof t==`string`?Xe.from(t,n||`utf8`):t instanceof DataView?Xe.from(t.buffer,t.byteOffset,t.byteLength):(t instanceof ArrayBuffer,Xe.from(t))}function codedError(t,n,S=Error){let C=new S(n);return C.code=t,C}var Io,Lo,Ro,zo=__esmMin(()=>{ot(),Io={md5:16,sha1:20,sha256:32,sha384:48,sha512:64},Lo={md5:64,sha1:64,sha256:64,sha384:128,sha512:128},Ro=new Set([`md5`,`sha1`,`sha256`,`sha384`,`sha512`]),__name$1(toBuffer$1,`toBuffer`)});function fromBig(t,n=!1){return n?{h:Number(t&Bo),l:Number(t>>Vo&Bo)}:{h:Number(t>>Vo&Bo)|0,l:Number(t&Bo)|0}}function split(t,n=!1){let S=t.length,C=new Uint32Array(S),N=new Uint32Array(S);for(let F=0;F<S;F++){let{h:S,l:I}=fromBig(t[F],n);[C[F],N[F]]=[S,I]}return[C,N]}function setU64FromNum(t,n,S,C){let N=fromNumH(S),F=fromNumL(S);t.setUint32(n,C?F:N,C),t.setUint32(n+4,C?N:F,C)}function add(t,n,S,C){let N=(n>>>0)+(C>>>0);return{h:t+S+(N/2**32|0)|0,l:N|0}}var Bo,Vo,fromNumH,fromNumL,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,add3L,add3H,add4L,add4H,add5L,add5H,Ho=__esmMin(()=>{Bo=BigInt(2**32-1),Vo=BigInt(32),fromNumH=t=>t/2**32|0,fromNumL=t=>t>>>0,shrSH=(t,n,S)=>t>>>S,shrSL=(t,n,S)=>t<<32-S|n>>>S,rotrSH=(t,n,S)=>t>>>S|n<<32-S,rotrSL=(t,n,S)=>t<<32-S|n>>>S,rotrBH=(t,n,S)=>t<<64-S|n>>>S-32,rotrBL=(t,n,S)=>t>>>S-32|n<<64-S,add3L=(t,n,S)=>(t>>>0)+(n>>>0)+(S>>>0),add3H=(t,n,S,C)=>n+S+C+(t/2**32|0)|0,add4L=(t,n,S,C)=>(t>>>0)+(n>>>0)+(S>>>0)+(C>>>0),add4H=(t,n,S,C,N)=>n+S+C+N+(t/2**32|0)|0,add5L=(t,n,S,C,N)=>(t>>>0)+(n>>>0)+(S>>>0)+(C>>>0)+(N>>>0),add5H=(t,n,S,C,N,F)=>n+S+C+N+F+(t/2**32|0)|0});function isBytes$1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in t&&t.BYTES_PER_ELEMENT===1}function anumber$1(t,n=``){if(typeof t!=`number`)throw TypeError(Uo(n)+`expected number, got `+typeof t);if(!Number.isSafeInteger(t)||t<0)throw RangeError(Uo(n)+`expected integer >= 0, got `+t);return t}function abytes$1(t,n,S=``){if(isBytes$1(t)&&(n===void 0||t.length===n))return t;n!==void 0&&anumber$1(n,`length`);let C=isBytes$1(t),N=n===void 0?``:` of length ${n}`,F=C?`length=${t.length}`:`type=${typeof t}`,I=Uo(S)+`expected Uint8Array`+N+`, got `+F;throw C?RangeError(I):TypeError(I)}function aexists(t,n=!0){if(t.destroyed)throw Error(`hash was destroyed`);if(n&&t.finished)throw Error(`digest() was already called`)}function aoutput(t,n){abytes$1(t,void 0,`output`);let S=n.outputLen;if(!(t.length>=S))throw RangeError(`"output" expected length >= `+S)}function clean(...t){for(let n=0;n<t.length;n++)t[n].fill(0)}function createView(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function bytesToHex$1(t){if(abytes$1(t),Go)return t.toHex();let n=``;for(let S=0;S<t.length;S++)n+=Ko[t[S]];return n}function asciiToBase16(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function hexToBytes$1(t){if(typeof t!=`string`)throw TypeError(`hex string expected, got `+typeof t);if(Go)try{return Uint8Array.fromHex(t)}catch(t){throw t instanceof SyntaxError?RangeError(t.message):t}let n=t.length,S=n/2;if(n%2)throw RangeError(`hex string expected, got unpadded hex of length `+n);let C=new Uint8Array(S);for(let n=0,N=0;n<S;n++,N+=2){let S=asciiToBase16(t.charCodeAt(N)),F=asciiToBase16(t.charCodeAt(N+1));if(S===void 0||F===void 0){let n=t[N]+t[N+1];throw RangeError(`hex string expected, got non-hex character "`+n+`" at index `+N)}C[n]=S*16+F}return C}function concatBytes$2(...t){let n=0;for(let S=0;S<t.length;S++){let C=t[S];abytes$1(C),n+=C.length}let S=new Uint8Array(n);for(let n=0,C=0;n<t.length;n++){let N=t[n];S.set(N,C),C+=N.length}return S}function checkOpts(t,n,S=`opts`){return aopts(t,`defaults`),n!==void 0&&aopts(n,S),Object.assign(Object.create(null),t,n)}function createHasher(t,n={}){if(typeof t!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof t);n=checkOpts({},n,`info`);let hashC=(n,S)=>t(S).update(n).digest(),S=t(void 0);return hashC.outputLen=S.outputLen,hashC.blockLen=S.blockLen,hashC.canXOF=S.canXOF,hashC.create=n=>t(n),Object.assign(hashC,n),Object.freeze(hashC)}function randomBytes$2(t=32){anumber$1(t,`bytesLength`);let n=typeof globalThis==`object`?globalThis.crypto:null;if(typeof n?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(t>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${t}`);return n.getRandomValues(new Uint8Array(t))}var Uo,Wo,aopts,Go,Ko,oidNist,qo=__esmMin(()=>{__name$1(isBytes$1,`isBytes`),Uo=__name$1(t=>t?`"${t}" `:``,`atitle`),__name$1(anumber$1,`anumber`),__name$1(abytes$1,`abytes`),Wo=__name$1((t,n)=>{if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError((n===`object`?``:`"${n}" `)+`expected object, got type=`+typeof t)},`aobject`),aopts=(t,n)=>{Wo(t,n);let S=Object.getPrototypeOf(t);if(S!==Object.prototype&&S!==null)throw TypeError(`"${n}" expected plain object`);if(Object.hasOwn(t,`__proto__`))throw TypeError(`"${n}.__proto__" is not allowed`)},Go=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Ko=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,`0`)),__name$1(bytesToHex$1,`bytesToHex`),__name$1(hexToBytes$1,`hexToBytes`),__name$1(concatBytes$2,`concatBytes`),__name$1(randomBytes$2,`randomBytes`),oidNist=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})}),HashMD,Jo,Yo=__esmMin(()=>{Ho(),qo(),HashMD=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,S,C){this.blockLen=t,this.outputLen=n,this.padOffset=S,this.isLE=C,this.buffer=new Uint8Array(t),this.view=createView(this.buffer)}update(t){aexists(this),abytes$1(t);let{view:n,buffer:S,blockLen:C}=this,N=t.length,F=!1;for(let I=0;I<N;){let H=Math.min(C-this.pos,N-I);if(H===C){let n=createView(t);for(;C<=N-I;I+=C)this.process(n,I);F=!0;continue}S.set(I===0&&H===N?t:t.subarray(I,I+H),this.pos),this.pos+=H,I+=H,this.pos===C&&(this.process(n,0),this.pos=0,F=!0)}return this.length+=t.length,F&&this.roundClean(),this}digestInto(t){aexists(this),aoutput(t,this),this.finished=!0;let{buffer:n,view:S,blockLen:C,isLE:N}=this,{pos:F}=this;n[F++]=128,n.fill(0,F),this.padOffset>C-F&&(this.process(S,0),n.fill(0)),setU64FromNum(S,C-8,this.length*8,N),this.process(S,0),this.roundClean();let I=t===n?S:createView(t),H=this.outputLen,W=H/4,q=this.get();if(H%4||W>q.length)throw Error(`invalid outputLen`);for(let t=0;t<W;t++)I.setUint32(4*t,q[t],N)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let S=t.slice(0,n);return this.destroy(),S}_cloneIntoMeta(t){let{buffer:n,length:S,finished:C,destroyed:N,pos:F}=this;return t.destroyed=N,t.finished=C,t.length=S,t.pos=F,F&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Jo=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])}),Xo,Zo,Qo,$o,es,SHA2_64B,_SHA512,ts,ns=__esmMin(()=>{Yo(),Ho(),qo(),Xo=split(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(t=>BigInt(t))),Zo=Xo[0],Qo=Xo[1],$o=new Uint32Array(80),es=new Uint32Array(80),SHA2_64B=class extends HashMD{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,n){super(128,t,16,!1),this.Ah=n[0]|0,this.Al=n[1]|0,this.Bh=n[2]|0,this.Bl=n[3]|0,this.Ch=n[4]|0,this.Cl=n[5]|0,this.Dh=n[6]|0,this.Dl=n[7]|0,this.Eh=n[8]|0,this.El=n[9]|0,this.Fh=n[10]|0,this.Fl=n[11]|0,this.Gh=n[12]|0,this.Gl=n[13]|0,this.Hh=n[14]|0,this.Hl=n[15]|0}get(){let{Ah:t,Al:n,Bh:S,Bl:C,Ch:N,Cl:F,Dh:I,Dl:H,Eh:W,El:q,Fh:Y,Fl:X,Gh:Z,Gl:te,Hh:ne,Hl:re}=this;return[t,n,S,C,N,F,I,H,W,q,Y,X,Z,te,ne,re]}set(t,n,S,C,N,F,I,H,W,q,Y,X,Z,te,ne,re){this.Ah=t|0,this.Al=n|0,this.Bh=S|0,this.Bl=C|0,this.Ch=N|0,this.Cl=F|0,this.Dh=I|0,this.Dl=H|0,this.Eh=W|0,this.El=q|0,this.Fh=Y|0,this.Fl=X|0,this.Gh=Z|0,this.Gl=te|0,this.Hh=ne|0,this.Hl=re|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let S=0;S<16;S++,n+=4)$o[S]=t.getUint32(n),es[S]=t.getUint32(n+=4);for(let t=16;t<80;t++){let n=$o[t-15]|0,S=es[t-15]|0,C=rotrSH(n,S,1)^rotrSH(n,S,8)^shrSH(n,S,7),N=rotrSL(n,S,1)^rotrSL(n,S,8)^shrSL(n,S,7),F=$o[t-2]|0,I=es[t-2]|0,H=rotrSH(F,I,19)^rotrBH(F,I,61)^shrSH(F,I,6),W=rotrSL(F,I,19)^rotrBL(F,I,61)^shrSL(F,I,6),q=add4L(N,W,es[t-7],es[t-16]),Y=add4H(q,C,H,$o[t-7],$o[t-16]);$o[t]=Y|0,es[t]=q|0}let{Ah:S,Al:C,Bh:N,Bl:F,Ch:I,Cl:H,Dh:W,Dl:q,Eh:Y,El:X,Fh:Z,Fl:te,Gh:ne,Gl:re,Hh:ie,Hl:ae}=this;for(let t=0;t<80;t++){let n=rotrSH(Y,X,14)^rotrSH(Y,X,18)^rotrBH(Y,X,41),oe=rotrSL(Y,X,14)^rotrSL(Y,X,18)^rotrBL(Y,X,41),Q=Y&Z^~Y&ne,se=X&te^~X&re,ce=add5L(ae,oe,se,Qo[t],es[t]),le=add5H(ce,ie,n,Q,Zo[t],$o[t]),ue=ce|0,de=rotrSH(S,C,28)^rotrBH(S,C,34)^rotrBH(S,C,39),fe=rotrSL(S,C,28)^rotrBL(S,C,34)^rotrBL(S,C,39),pe=S&N^S&I^N&I,me=C&F^C&H^F&H;ie=ne|0,ae=re|0,ne=Z|0,re=te|0,Z=Y|0,te=X|0,{h:Y,l:X}=add(W|0,q|0,le|0,ue|0),W=I|0,q=H|0,I=N|0,H=F|0,N=S|0,F=C|0;let he=add3L(ue,fe,me);S=add3H(he,le,de,pe),C=he|0}({h:S,l:C}=add(this.Ah|0,this.Al|0,S|0,C|0)),{h:N,l:F}=add(this.Bh|0,this.Bl|0,N|0,F|0),{h:I,l:H}=add(this.Ch|0,this.Cl|0,I|0,H|0),{h:W,l:q}=add(this.Dh|0,this.Dl|0,W|0,q|0),{h:Y,l:X}=add(this.Eh|0,this.El|0,Y|0,X|0),{h:Z,l:te}=add(this.Fh|0,this.Fl|0,Z|0,te|0),{h:ne,l:re}=add(this.Gh|0,this.Gl|0,ne|0,re|0),{h:ie,l:ae}=add(this.Hh|0,this.Hl|0,ie|0,ae|0),this.set(S,C,N,F,I,H,W,q,Y,X,Z,te,ne,re,ie,ae)}roundClean(){clean($o,es)}destroy(){this.destroyed=!0,clean(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_SHA512=class extends SHA2_64B{constructor(){super(64,Jo)}},ts=createHasher(()=>new _SHA512,oidNist(3))});
16
16
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
17
17
  function aarray(t,n,S=()=>{}){if(!Array.isArray(t))throw TypeError(`"${n}" expected array, got type=${typeof t}`);for(let C=0;C<t.length;C++)S(t[C],`${n}[${C}]`);return t}function aobject(t,n=`object`){if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(n===`object`?`expected valid options object`:`"${n}" expected object, got type=${typeof t}`);return t}function afunction(t,n){if(typeof t!=`function`)throw TypeError(`"${n}" is invalid: expected function, got ${typeof t}`);return t}function abool(t,n=``){if(typeof t!=`boolean`)throw TypeError(atitle(n)+`expected boolean, got type=`+typeof t);return t}function abignumber(t){if(typeof t==`bigint`){if(!isPosBig(t))throw RangeError(`positive bigint expected, got `+t)}else rs(t);return t}function asafenumber(t,n=``){if(typeof t!=`number`){let S=n&&`"${n}" `;throw TypeError(S+`expected number, got type=`+typeof t)}if(!Number.isSafeInteger(t)){let S=n&&`"${n}" `;throw RangeError(S+`expected safe integer, got `+t)}}function hexToNumber(t){if(typeof t!=`string`)throw TypeError(`hex string expected, got `+typeof t);return t===``?cs:BigInt(`0x`+t)}function bytesToNumberBE(t){return hexToNumber(bytesToHex$1(t))}function bytesToNumberLE(t){return hexToNumber(bytesToHex$1(copyBytes(abytes$1(t)).reverse()))}function numberToBytesBE(t,n){if(anumber$1(n),n===0)throw Error(`zero output length is invalid`);t=abignumber(t);let S=n*2,C=t.toString(16);if(C.length>S)throw RangeError(`number is too large`);return hexToBytes$1(C.padStart(S,`0`))}function numberToBytesLE(t,n){return numberToBytesBE(t,n).reverse()}function copyBytes(t){return Uint8Array.from(abytes(t))}function asciiToBytes(t){if(typeof t!=`string`)throw TypeError(`ascii string expected, got `+typeof t);return Uint8Array.from(t,(n,S)=>{let C=n.charCodeAt(0);if(n.length!==1||C>127)throw RangeError(`string contains non-ASCII character "${t[S]}" with code ${C} at position ${S}`);return C})}function isPosBig(t){return typeof t==`bigint`&&cs<=t}function inRange(t,n,S){return isPosBig(t)&&isPosBig(n)&&isPosBig(S)&&n<=t&&t<S}function aInRange(t,n,S,C){if(!inRange(n,S,C))throw RangeError(`expected valid `+t+`: `+S+` <= n < `+C+`, got `+n)}function bitLen(t){if(t<cs)throw Error(`expected non-negative bigint, got `+t);return t===cs?0:t.toString(2).length}function validateObject(t,n={},S={},C=`object`){aobject(t,C),aobject(n,`fields`),aobject(S,`optFields`);function checkField(n,S,N){let F=C===`object`?`param "${String(n)}"`:`"${C}.${String(n)}"`,I=t[n];if(!Object.hasOwn(t,n)&&(N?I!==void 0:S!==`function`))throw TypeError(`${F} is invalid: expected own property`);if(N&&I===void 0)return;let H=typeof I;if(H!==S||I===null)throw TypeError(`${F} is invalid: expected ${S}, got ${H}`)}let iter=(t,n)=>Object.entries(t).forEach(([t,S])=>checkField(t,S,n));iter(n,!1),iter(S,!0)}var abytes,rs,is,as,hexToBytes,os,ss,cs,ls,atitle,bitMask,us=__esmMin(()=>{qo(),abytes=(t,n,S)=>abytes$1(t,n,S),rs=anumber$1,is=bytesToHex$1,as=__name$1((...t)=>concatBytes$2(...t),`concatBytes`),hexToBytes=t=>hexToBytes$1(t),os=isBytes$1,ss=__name$1(t=>randomBytes$2(t),`randomBytes`),cs=BigInt(0),ls=BigInt(1),atitle=t=>t?`"${t}" `:``,bitMask=t=>(asafenumber(t,`n`),(ls<<BigInt(t))-ls)});
@@ -145,7 +145,7 @@ fi
145
145
  `)}`:``;n.fail(N(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(C).length,Object.keys(C).join(`, `)+S))}},F.unknownArguments=function unknownArguments(S,C,I,H,W=!0){let q=t.getInternalMethods().getCommandInstance().getCommands(),Y=[],X=t.getInternalMethods().getContext();if(Object.keys(S).forEach(n=>{!gp.includes(n)&&!Object.prototype.hasOwnProperty.call(I,n)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),n)&&!F.isValidAndSomeAliasIsNotNew(n,C)&&Y.push(n)}),W&&(X.commands.length>0||q.length>0||H)&&S._.slice(X.commands.length).forEach(t=>{q.includes(``+t)||Y.push(``+t)}),W){let n=t.getDemandedCommands()._?.max||0,C=X.commands.length+n;C<S._.length&&S._.slice(C).forEach(t=>{t=String(t),!X.commands.includes(t)&&!Y.includes(t)&&Y.push(t)})}Y.length&&n.fail(N(`Unknown argument: %s`,`Unknown arguments: %s`,Y.length,Y.map(t=>t.trim()?t:`"${t}"`).join(`, `)))},F.unknownCommands=function unknownCommands(S){let C=t.getInternalMethods().getCommandInstance().getCommands(),F=[],I=t.getInternalMethods().getContext();return(I.commands.length>0||C.length>0)&&S._.slice(I.commands.length).forEach(t=>{C.includes(``+t)||F.push(``+t)}),F.length>0?(n.fail(N(`Unknown command: %s`,`Unknown commands: %s`,F.length,F.join(`, `))),!0):!1},F.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(n,S){if(!Object.prototype.hasOwnProperty.call(S,n))return!1;let C=t.parsed.newAliases;return[n,...S[n]].some(t=>!Object.prototype.hasOwnProperty.call(C,t)||!C[n])},F.limitedChoices=function limitedChoices(S){let N=t.getOptions(),F={};if(!Object.keys(N.choices).length)return;Object.keys(S).forEach(t=>{gp.indexOf(t)===-1&&Object.prototype.hasOwnProperty.call(N.choices,t)&&[].concat(S[t]).forEach(n=>{N.choices[t].indexOf(n)===-1&&n!==void 0&&(F[t]=(F[t]||[]).concat(n))})});let I=Object.keys(F);if(!I.length)return;let H=C(`Invalid values:`);I.forEach(t=>{H+=`\n ${C(`Argument: %s, Given: %s, Choices: %s`,t,n.stringifiedValues(F[t]),n.stringifiedValues(N.choices[t]))}`}),n.fail(H)};let I={};F.implies=function implies(n,C){argsert(`<string|object> [array|number|string]`,[n,C],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.implies(t,n[t])}):(t.global(n),I[n]||(I[n]=[]),Array.isArray(C)?C.forEach(t=>F.implies(n,t)):(assertNotStrictEqual(C,void 0,S),I[n].push(C)))},F.getImplied=function getImplied(){return I};function keyExists(t,n){let S=Number(n);return n=isNaN(S)?n:S,typeof n==`number`?n=t._.length>=n:n.match(/^--no-.+/)?(n=n.match(/^--no-(.+)/)[1],n=!Object.prototype.hasOwnProperty.call(t,n)):n=Object.prototype.hasOwnProperty.call(t,n),n}F.implications=function implications(t){let S=[];if(Object.keys(I).forEach(n=>{let C=n;(I[n]||[]).forEach(n=>{let N=C,F=n;N=keyExists(t,N),n=keyExists(t,n),N&&!n&&S.push(` ${C} -> ${F}`)})}),S.length){let t=`${C(`Implications failed:`)}\n`;S.forEach(n=>{t+=n}),n.fail(t)}};let H={};F.conflicts=function conflicts(n,S){argsert(`<string|object> [array|string]`,[n,S],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.conflicts(t,n[t])}):(t.global(n),H[n]||(H[n]=[]),Array.isArray(S)?S.forEach(t=>F.conflicts(n,t)):H[n].push(S))},F.getConflicting=()=>H,F.conflicting=function conflictingFn(N){Object.keys(N).forEach(t=>{H[t]&&H[t].forEach(S=>{S&&N[t]!==void 0&&N[S]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,S))})}),t.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(H).forEach(t=>{H[t].forEach(F=>{F&&N[S.Parser.camelCase(t)]!==void 0&&N[S.Parser.camelCase(F)]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,F))})})},F.recommendCommands=function recommendCommands(t,S){S=S.sort((t,n)=>n.length-t.length);let N=null,F=1/0;for(let n=0,C;(C=S[n])!==void 0;n++){let n=levenshtein(t,C);n<=3&&n<F&&(F=n,N=C)}N&&n.fail(C(`Did you mean %s?`,N))},F.reset=function reset(t){return I=objFilter(I,n=>!t[n]),H=objFilter(H,n=>!t[n]),F};let W=[];return F.freeze=function freeze(){W.push({implied:I,conflicting:H})},F.unfreeze=function unfreeze(){let t=W.pop();assertNotStrictEqual(t,void 0,S),{implied:I,conflicting:H}=t},F}var gp,vp=__esmMin(()=>{np(),Qf(),hp(),sp(),gp=[`$0`,`--`,`_`]});function YargsFactory(t){return(n=[],S=t.process.cwd(),C)=>{let N=new YargsInstance(n,S,C,t);return Object.defineProperty(N,"argv",{get:()=>N.parse(),enumerable:!0}),N.help(),N.version(),N}}function isYargsInstance(t){return!!t&&typeof t.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,YargsInstance,Rm=__esmMin(()=>{_e(),op(),Qf(),bl(),up(),np(),mp(),vp(),sp(),Cl(),rp(),$f(),ip(),lp(),__classPrivateFieldSet=function(t,n,S,C,N){if(C===`m`)throw TypeError(`Private method is not writable`);if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a setter`);if(typeof n==`function`?t!==n||!N:!n.has(t))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return C===`a`?N.call(t,S):N?N.value=S:n.set(t,S),S},__classPrivateFieldGet=function(t,n,S,C){if(S===`a`&&!C)throw TypeError(`Private accessor was defined without a getter`);if(typeof n==`function`?t!==n||!C:!n.has(t))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return S===`m`?C:S===`a`?C.call(t):C?C.value:n.get(t)},em=Symbol(`copyDoubleDash`),tm=Symbol(`copyDoubleDash`),nm=Symbol(`deleteFromParserHintObject`),im=Symbol(`emitWarning`),am=Symbol(`freeze`),om=Symbol(`getDollarZero`),sm=Symbol(`getParserConfiguration`),cm=Symbol(`getUsageConfiguration`),lm=Symbol(`guessLocale`),um=Symbol(`guessVersion`),dm=Symbol(`parsePositionalNumbers`),fm=Symbol(`pkgUp`),pm=Symbol(`populateParserHintArray`),mm=Symbol(`populateParserHintSingleValueDictionary`),hm=Symbol(`populateParserHintArrayDictionary`),gm=Symbol(`populateParserHintDictionary`),_m=Symbol(`sanitizeKey`),vm=Symbol(`setKey`),ym=Symbol(`unfreeze`),bm=Symbol(`validateAsync`),xm=Symbol(`getCommandInstance`),Sm=Symbol(`getContext`),Cm=Symbol(`getHasOutput`),wm=Symbol(`getLoggerInstance`),Tm=Symbol(`getParseContext`),Em=Symbol(`getUsageInstance`),Dm=Symbol(`getValidationInstance`),Om=Symbol(`hasParseCallback`),km=Symbol(`isGlobalContext`),Am=Symbol(`postProcess`),jm=Symbol(`rebase`),Mm=Symbol(`reset`),Nm=Symbol(`runYargsParserAndExecuteCommands`),Pm=Symbol(`runValidation`),Fm=Symbol(`setHasOutput`),Im=Symbol(`kTrackManuallySetKeys`),Lm=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,yp.set(this,void 0),bp.set(this,void 0),xp.set(this,{commands:[],fullCommands:[]}),Sp.set(this,null),Cp.set(this,null),wp.set(this,`show-hidden`),Tp.set(this,null),Ep.set(this,!0),Dp.set(this,{}),Op.set(this,!0),kp.set(this,[]),Ap.set(this,void 0),jp.set(this,{}),Mp.set(this,!1),Np.set(this,null),Pp.set(this,!0),Fp.set(this,void 0),Ip.set(this,``),Lp.set(this,void 0),Rp.set(this,void 0),zp.set(this,{}),Bp.set(this,null),Vp.set(this,null),Hp.set(this,{}),Up.set(this,{}),Wp.set(this,void 0),Gp.set(this,!1),Kp.set(this,void 0),qp.set(this,!1),Jp.set(this,!1),Yp.set(this,!1),Xp.set(this,void 0),Zp.set(this,{}),Qp.set(this,null),$p.set(this,void 0),__classPrivateFieldSet(this,Kp,C,`f`),__classPrivateFieldSet(this,Wp,t,`f`),__classPrivateFieldSet(this,bp,n,`f`),__classPrivateFieldSet(this,Rp,S,`f`),__classPrivateFieldSet(this,Ap,new GlobalMiddleware(this),`f`),this.$0=this[om](),this[Mm](),__classPrivateFieldSet(this,yp,__classPrivateFieldGet(this,yp,`f`),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`),`f`),__classPrivateFieldSet(this,$p,__classPrivateFieldGet(this,$p,`f`),`f`),__classPrivateFieldSet(this,Lp,__classPrivateFieldGet(this,Lp,`f`),`f`),__classPrivateFieldGet(this,Lp,`f`).showHiddenOpt=__classPrivateFieldGet(this,wp,`f`),__classPrivateFieldSet(this,Fp,this[tm](),`f`),__classPrivateFieldGet(this,Kp,`f`).y18n.setLocale(Lm)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,Np,`f`)&&(this[nm](__classPrivateFieldGet(this,Np,`f`)),__classPrivateFieldSet(this,Np,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,Np,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,Np,`f`)),this.describe(__classPrivateFieldGet(this,Np,`f`),n||__classPrivateFieldGet(this,Xp,`f`).deferY18nLookup(`Show help`)),this)}help(t,n){return this.addHelpOpt(t,n)}addShowHiddenOpt(t,n){if(argsert(`[string|boolean] [string]`,[t,n],arguments.length),t===!1&&n===void 0)return this;let S=typeof t==`string`?t:__classPrivateFieldGet(this,wp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,Xp,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,Lp,`f`).showHiddenOpt=S,this}showHidden(t,n){return this.addShowHiddenOpt(t,n)}alias(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[hm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`array`,t),this[Im](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`boolean`,t),this[Im](t),this}check(t,n){return argsert(`<function> [boolean]`,[t,n],arguments.length),this.middleware((n,S)=>maybeAsyncResult(()=>t(n,S.getOptions()),S=>(S?(typeof S==`string`||S instanceof Error)&&__classPrivateFieldGet(this,Xp,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,Xp,`f`).fail(__classPrivateFieldGet(this,Kp,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,Xp,`f`).fail(t.message?t.message:t.toString(),t),n)),!1,n),this}choices(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[hm](this.choices.bind(this),`choices`,t,n),this}coerce(t,n){if(argsert(`<object|string|array> [function]`,[t,n],arguments.length),Array.isArray(t)){if(!n)throw new yl(`coerce callback must be provided`);for(let S of t)this.coerce(S,n);return this}else if(typeof t==`object`){for(let n of Object.keys(t))this.coerce(n,t[n]);return this}if(!n)throw new yl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,Lp,`f`).key[S]=!0,__classPrivateFieldGet(this,Ap,`f`).addCoerceMiddleware((t,C)=>{let N=C.getAliases()[S]??[],F=[S,...N].filter(n=>Object.prototype.hasOwnProperty.call(t,n));return F.length===0?t:maybeAsyncResult(()=>n(t[F[0]]),n=>(F.forEach(S=>{t[S]=n}),t),t=>{throw new yl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,$p,`f`).conflicts(t,n),this}config(t=`config`,n,S){return argsert(`[object|string] [string|function] [function]`,[t,n,S],arguments.length),typeof t==`object`&&!Array.isArray(t)?(t=applyExtends(t,__classPrivateFieldGet(this,bp,`f`),this[sm]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Kp,`f`)),__classPrivateFieldGet(this,Lp,`f`).configObjects=(__classPrivateFieldGet(this,Lp,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,Xp,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,Lp,`f`).config[t]=S||!0}),this)}completion(t,n,S){return argsert(`[string] [string|boolean|function] [function]`,[t,n,S],arguments.length),typeof n==`function`&&(S=n,n=void 0),__classPrivateFieldSet(this,Cp,t||__classPrivateFieldGet(this,Cp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,Cp,`f`),n),S&&__classPrivateFieldGet(this,Sp,`f`).registerFunction(S),this}command(t,n,S,C,N,F){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[t,n,S,C,N,F],arguments.length),__classPrivateFieldGet(this,yp,`f`).addHandler(t,n,S,C,N,F),this}commands(t,n,S,C,N,F){return this.command(t,n,S,C,N,F)}commandDir(t,n){argsert(`<string> [object]`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,Rp,`f`)||__classPrivateFieldGet(this,Kp,`f`).require;return __classPrivateFieldGet(this,yp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,Kp,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`count`,t),this[Im](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,Kp,`f`)),__classPrivateFieldGet(this,Lp,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,Kp,`f`)),__classPrivateFieldGet(this,Lp,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,Lp,`f`).defaultDescription[t]=__classPrivateFieldGet(this,Xp,`f`).functionDescription(n)),n=n.call()),this[mm](this.default.bind(this),`default`,t,n),this}defaults(t,n,S){return this.default(t,n,S)}demandCommand(t=1,n,S,C){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[t,n,S,C],arguments.length),typeof n!=`number`&&(S=n,n=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,Lp,`f`).demandedCommands._={min:t,max:n,minMsg:S,maxMsg:C},this}demand(t,n,S){return Array.isArray(n)?(n.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Kp,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Kp,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Kp,`f`)),this.demandOption(t,S)}):typeof S==`string`?this.demandOption(t,S):(S===!0||S===void 0)&&this.demandOption(t),this}demandOption(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[mm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,Lp,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[vm](t,!0),__classPrivateFieldGet(this,Xp,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Ep,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,Lp,`f`).envPrefix:__classPrivateFieldGet(this,Lp,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,Xp,`f`).epilog(t),this}epilog(t){return this.epilogue(t)}example(t,n){return argsert(`<string|array> [string]`,[t,n],arguments.length),Array.isArray(t)?t.forEach(t=>this.example(...t)):__classPrivateFieldGet(this,Xp,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,Mp,!0,`f`),__classPrivateFieldSet(this,Tp,n,`f`),__classPrivateFieldGet(this,Op,`f`)&&__classPrivateFieldGet(this,Kp,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Op,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new yl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,Xp,`f`).failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,n){return argsert(`<array> [function]`,[t,n],arguments.length),n?__classPrivateFieldGet(this,Sp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,Sp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,Lp,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,Lp,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,Lp,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Ep,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Op,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,jp,`f`),__classPrivateFieldGet(this,Up,`f`))}getHelp(){if(__classPrivateFieldSet(this,Mp,!0,`f`),!__classPrivateFieldGet(this,Xp,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[Nm](__classPrivateFieldGet(this,Wp,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,Xp,`f`).help())}let t=__classPrivateFieldGet(this,yp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,Xp,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,Xp,`f`).help())}getOptions(){return __classPrivateFieldGet(this,Lp,`f`)}getStrict(){return __classPrivateFieldGet(this,qp,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,Jp,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,Yp,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,Lp,`f`).local.includes(t)||__classPrivateFieldGet(this,Lp,`f`).local.push(t)}):__classPrivateFieldGet(this,Lp,`f`).local=__classPrivateFieldGet(this,Lp,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,Up,`f`)[n]||__classPrivateFieldGet(this,jp,`f`)[n];__classPrivateFieldGet(this,Up,`f`)[n]&&delete __classPrivateFieldGet(this,Up,`f`)[n];let C={};return __classPrivateFieldGet(this,jp,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,Lp,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,$p,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[lm](),__classPrivateFieldGet(this,Kp,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Ep,!1,`f`),__classPrivateFieldGet(this,Kp,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,Ap,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[mm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`number`,t),this[Im](t),this}option(t,n){if(argsert(`<string|object> [object]`,[t,n],arguments.length),typeof t==`object`)Object.keys(t).forEach(n=>{this.options(n,t[n])});else{typeof n!=`object`&&(n={}),this[Im](t),__classPrivateFieldGet(this,Qp,`f`)&&(t===`version`||n?.alias===`version`)&&this[im]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
146
146
  `),void 0,`versionWarning`),__classPrivateFieldGet(this,Lp,`f`).key[t]=!0,n.alias&&this.alias(t,n.alias);let S=n.deprecate||n.deprecated;S&&this.deprecateOption(t,S);let C=n.demand||n.required||n.require;C&&this.demand(t,C),n.demandOption&&this.demandOption(t,typeof n.demandOption==`string`?n.demandOption:void 0),n.conflicts&&this.conflicts(t,n.conflicts),`default`in n&&this.default(t,n.default),n.implies!==void 0&&this.implies(t,n.implies),n.nargs!==void 0&&this.nargs(t,n.nargs),n.config&&this.config(t,n.configParser),n.normalize&&this.normalize(t),n.choices&&this.choices(t,n.choices),n.coerce&&this.coerce(t,n.coerce),n.group&&this.group(t,n.group),(n.boolean||n.type===`boolean`)&&(this.boolean(t),n.alias&&this.boolean(n.alias)),(n.array||n.type===`array`)&&(this.array(t),n.alias&&this.array(n.alias)),(n.number||n.type===`number`)&&(this.number(t),n.alias&&this.number(n.alias)),(n.string||n.type===`string`)&&(this.string(t),n.alias&&this.string(n.alias)),(n.count||n.type===`count`)&&this.count(t),typeof n.global==`boolean`&&this.global(t,n.global),n.defaultDescription&&(__classPrivateFieldGet(this,Lp,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,Xp,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(F,t)||typeof N==`string`)&&this.describe(t,N),n.hidden&&this.hide(t),n.requiresArg&&this.requiresArg(t)}return this}options(t,n){return this.option(t,n)}parse(t,n,S){argsert(`[string|array] [function|boolean|object] [function]`,[t,n,S],arguments.length),this[am](),t===void 0&&(t=__classPrivateFieldGet(this,Wp,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,Vp,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,Bp,n,`f`),n=!1),n||__classPrivateFieldSet(this,Wp,t,`f`),__classPrivateFieldGet(this,Bp,`f`)&&__classPrivateFieldSet(this,Op,!1,`f`);let C=this[Nm](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,Sp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,Bp,`f`)&&__classPrivateFieldGet(this,Bp,`f`).call(this,__classPrivateFieldGet(this,Tp,`f`),t,__classPrivateFieldGet(this,Ip,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,Bp,`f`)&&__classPrivateFieldGet(this,Bp,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,Ip,`f`)),t}).finally(()=>{this[ym](),this.parsed=N}):(__classPrivateFieldGet(this,Bp,`f`)&&__classPrivateFieldGet(this,Bp,`f`).call(this,__classPrivateFieldGet(this,Tp,`f`),C,__classPrivateFieldGet(this,Ip,`f`)),this[ym](),this.parsed=N,C)}parseAsync(t,n,S){let C=this.parse(t,n,S);return isPromise(C)?C:Promise.resolve(C)}parseSync(t,n,S){let C=this.parse(t,n,S);if(isPromise(C))throw new yl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,zp,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[fm](n||__classPrivateFieldGet(this,bp,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,bp,`f`),this[sm]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Kp,`f`)),__classPrivateFieldGet(this,Lp,`f`).configObjects=(__classPrivateFieldGet(this,Lp,`f`).configObjects||[]).concat(S)),this}positional(t,n){argsert(`<string> <object>`,[t,n],arguments.length);let S=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];n=objFilter(n,(t,n)=>t===`type`&&![`string`,`number`,`boolean`].includes(n)?!1:S.includes(t));let C=__classPrivateFieldGet(this,xp,`f`).fullCommands[__classPrivateFieldGet(this,xp,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,yp,`f`).cmdToParseOptions(C):{array:[],alias:{},default:{},demand:{}};return objectKeys(N).forEach(S=>{let C=N[S];Array.isArray(C)?C.indexOf(t)!==-1&&(n[S]=!0):C[t]&&!(S in n)&&(n[S]=C[t])}),this.group(t,__classPrivateFieldGet(this,Xp,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Gp,t,`f`),this}required(t,n,S){return this.demand(t,n,S)}require(t,n,S){return this.demand(t,n,S)}requiresArg(t){return argsert(`<array|string|object> [number]`,[t],arguments.length),typeof t==`string`&&__classPrivateFieldGet(this,Lp,`f`).narg[t]||this[mm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,Fp,`f`).log(__classPrivateFieldGet(this,Sp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,Cp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,Mp,!0,`f`),!__classPrivateFieldGet(this,Xp,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[Nm](__classPrivateFieldGet(this,Wp,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,Xp,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,yp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,Xp,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,Xp,`f`).showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,n){return argsert(`[boolean|string] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,Xp,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,Xp,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,qp,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Jp,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Yp,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[pm](`string`,t),this[Im](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,Kp,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Ep,!1,`f`),__classPrivateFieldGet(this,Kp,`f`).y18n.updateLocale(t),this}usage(t,n,S,C){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[t,n,S,C],arguments.length),n!==void 0){if(assertNotStrictEqual(t,null,__classPrivateFieldGet(this,Kp,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new yl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,Xp,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Zp,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Qp,`f`)&&(this[nm](__classPrivateFieldGet(this,Qp,`f`)),__classPrivateFieldGet(this,Xp,`f`).version(void 0),__classPrivateFieldSet(this,Qp,null,`f`)),arguments.length===0)S=this[um](),t=C;else if(arguments.length===1){if(t===!1)return this;S=t,t=C}else arguments.length===2&&(S=n,n=void 0);return __classPrivateFieldSet(this,Qp,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,Xp,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,Xp,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Qp,`f`)),this.describe(__classPrivateFieldGet(this,Qp,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,Xp,`f`).wrap(t),this}[(yp=new WeakMap,bp=new WeakMap,xp=new WeakMap,Sp=new WeakMap,Cp=new WeakMap,wp=new WeakMap,Tp=new WeakMap,Ep=new WeakMap,Dp=new WeakMap,Op=new WeakMap,kp=new WeakMap,Ap=new WeakMap,jp=new WeakMap,Mp=new WeakMap,Np=new WeakMap,Pp=new WeakMap,Fp=new WeakMap,Ip=new WeakMap,Lp=new WeakMap,Rp=new WeakMap,zp=new WeakMap,Bp=new WeakMap,Vp=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap,Xp=new WeakMap,Zp=new WeakMap,Qp=new WeakMap,$p=new WeakMap,em)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[tm](){return{log:(...t)=>{this[Om]()||ge.log(...t),__classPrivateFieldSet(this,Mp,!0,`f`),__classPrivateFieldGet(this,Ip,`f`).length&&__classPrivateFieldSet(this,Ip,__classPrivateFieldGet(this,Ip,`f`)+`
147
147
  `,`f`),__classPrivateFieldSet(this,Ip,__classPrivateFieldGet(this,Ip,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Om]()||ge.error(...t),__classPrivateFieldSet(this,Mp,!0,`f`),__classPrivateFieldGet(this,Ip,`f`).length&&__classPrivateFieldSet(this,Ip,__classPrivateFieldGet(this,Ip,`f`)+`
148
- `,`f`),__classPrivateFieldSet(this,Ip,__classPrivateFieldGet(this,Ip,`f`)+t.join(` `),`f`)}}}[nm](t){objectKeys(__classPrivateFieldGet(this,Lp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Lp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,Xp,`f`).getDescriptions()[t]}[im](t,n,S){__classPrivateFieldGet(this,Dp,`f`)[S]||(__classPrivateFieldGet(this,Kp,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Dp,`f`)[S]=!0)}[am](){__classPrivateFieldGet(this,kp,`f`).push({options:__classPrivateFieldGet(this,Lp,`f`),configObjects:__classPrivateFieldGet(this,Lp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Op,`f`),groups:__classPrivateFieldGet(this,jp,`f`),strict:__classPrivateFieldGet(this,qp,`f`),strictCommands:__classPrivateFieldGet(this,Jp,`f`),strictOptions:__classPrivateFieldGet(this,Yp,`f`),completionCommand:__classPrivateFieldGet(this,Cp,`f`),output:__classPrivateFieldGet(this,Ip,`f`),exitError:__classPrivateFieldGet(this,Tp,`f`),hasOutput:__classPrivateFieldGet(this,Mp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Bp,`f`),parseContext:__classPrivateFieldGet(this,Vp,`f`)}),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze(),__classPrivateFieldGet(this,yp,`f`).freeze(),__classPrivateFieldGet(this,Ap,`f`).freeze()}[om](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Kp,`f`).process.argv()[0])?__classPrivateFieldGet(this,Kp,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Kp,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[jm](__classPrivateFieldGet(this,bp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Kp,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Kp,`f`).path.dirname(__classPrivateFieldGet(this,Kp,`f`).process.execPath())}/`,``)),t}[sm](){return __classPrivateFieldGet(this,zp,`f`)}[cm](){return __classPrivateFieldGet(this,Zp,`f`)}[lm](){if(!__classPrivateFieldGet(this,Ep,`f`))return;let t=__classPrivateFieldGet(this,Kp,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[um](){return this[fm]().version||`unknown`}[dm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Kp,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,Hp,`f`)[n])return __classPrivateFieldGet(this,Hp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Kp,`f`).mainFilename;__classPrivateFieldGet(this,Kp,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Kp,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Kp,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Kp,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Kp,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,Hp,`f`)[n]=S||{},__classPrivateFieldGet(this,Hp,`f`)[n]}[pm](t,n){n=[].concat(n),n.forEach(n=>{n=this[_m](n),__classPrivateFieldGet(this,Lp,`f`)[t].push(n)})}[mm](t,n,S,C){this[gm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Lp,`f`)[t][n]=S})}[hm](t,n,S,C){this[gm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Lp,`f`)[t][n]=(__classPrivateFieldGet(this,Lp,`f`)[t][n]||[]).concat(S)})}[gm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[_m](S),C)}[_m](t){return t===`__proto__`?`___proto___`:t}[vm](t,n){return this[mm](this[vm].bind(this),`key`,t,n),this}[ym](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,kp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Kp,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,Lp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Op,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,jp,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Ip,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Tp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,Mp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,qp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Jp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Yp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Cp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Bp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Vp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Lp,`f`).configObjects=te,__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze(),__classPrivateFieldGet(this,yp,`f`).unfreeze(),__classPrivateFieldGet(this,Ap,`f`).unfreeze()}[bm](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[xm].bind(this),getContext:this[Sm].bind(this),getHasOutput:this[Cm].bind(this),getLoggerInstance:this[wm].bind(this),getParseContext:this[Tm].bind(this),getParserConfiguration:this[sm].bind(this),getUsageConfiguration:this[cm].bind(this),getUsageInstance:this[Em].bind(this),getValidationInstance:this[Dm].bind(this),hasParseCallback:this[Om].bind(this),isGlobalContext:this[km].bind(this),postProcess:this[Am].bind(this),reset:this[Mm].bind(this),runValidation:this[Pm].bind(this),runYargsParserAndExecuteCommands:this[Nm].bind(this),setHasOutput:this[Fm].bind(this)}}[xm](){return __classPrivateFieldGet(this,yp,`f`)}[Sm](){return __classPrivateFieldGet(this,xp,`f`)}[Cm](){return __classPrivateFieldGet(this,Mp,`f`)}[wm](){return __classPrivateFieldGet(this,Fp,`f`)}[Tm](){return __classPrivateFieldGet(this,Vp,`f`)||{}}[Em](){return __classPrivateFieldGet(this,Xp,`f`)}[Dm](){return __classPrivateFieldGet(this,$p,`f`)}[Om](){return!!__classPrivateFieldGet(this,Bp,`f`)}[km](){return __classPrivateFieldGet(this,Pp,`f`)}[Am](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[em](t)),(this[sm]()[`parse-positional-numbers`]||this[sm]()[`parse-positional-numbers`]===void 0)&&(t=this[dm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!1)),t)}[Mm](t={}){__classPrivateFieldSet(this,Lp,__classPrivateFieldGet(this,Lp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Lp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Lp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Up,`f`),Object.keys(__classPrivateFieldGet(this,jp,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,jp,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,jp,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Lp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Lp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Lp,`f`).envPrefix,__classPrivateFieldSet(this,Lp,n,`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldSet(this,$p,__classPrivateFieldGet(this,$p,`f`)?__classPrivateFieldGet(this,$p,`f`).reset(S):validation(this,__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldSet(this,yp,__classPrivateFieldGet(this,yp,`f`)?__classPrivateFieldGet(this,yp,`f`).reset():command(__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,Ap,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldGet(this,Sp,`f`)||__classPrivateFieldSet(this,Sp,completion(this,__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,yp,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldGet(this,Ap,`f`).reset(),__classPrivateFieldSet(this,Cp,null,`f`),__classPrivateFieldSet(this,Ip,``,`f`),__classPrivateFieldSet(this,Tp,null,`f`),__classPrivateFieldSet(this,Mp,!1,`f`),this.parsed=!1,this}[jm](t,n){return __classPrivateFieldGet(this,Kp,`f`).path.relative(t,n)}[Nm](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Wp,`f`),__classPrivateFieldGet(this,Lp,`f`).__=__classPrivateFieldGet(this,Kp,`f`).y18n.__,__classPrivateFieldGet(this,Lp,`f`).configuration=this[sm]();let I=!!__classPrivateFieldGet(this,Lp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Lp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Kp,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Lp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Vp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Np,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Qp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,Xp,`f`).clearCachedHelpMessage();try{if(this[lm](),n)return this[Am](q,I,!!S,!1);__classPrivateFieldGet(this,Np,`f`)&&[__classPrivateFieldGet(this,Np,`f`)].concat(X[__classPrivateFieldGet(this,Np,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,Pp,!1,`f`);let H=__classPrivateFieldGet(this,yp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Sp,`f`)?.completionKey?[__classPrivateFieldGet(this,Sp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Sp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Cp,`f`)){let t=__classPrivateFieldGet(this,yp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Am](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Cp,`f`)){t=F;break}!__classPrivateFieldGet(this,yp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Gp,`f`)&&t&&!re&&__classPrivateFieldGet(this,$p,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Cp,`f`)&&q._.includes(__classPrivateFieldGet(this,Cp,`f`))&&!ne&&(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,yp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,yp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Am](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Sp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Sp,`f`).getCompletion(n,(t,n)=>{if(t)throw new yl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Fp,`f`).log(t)}),this.exit(0)}),this[Am](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,Mp,`f`)||(Z?(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Fp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,Xp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Lp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Lp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new yl(W.error.message);if(!ne){let t=this[Pm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!0)),Y=this[bm](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof yl)__classPrivateFieldGet(this,Xp,`f`).fail(t.message,t);else throw t}return this[Am](Y??q,I,!!S,!0)}[Pm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new yl(S.message);__classPrivateFieldGet(this,$p,`f`).nonOptionCount(F),__classPrivateFieldGet(this,$p,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Jp,`f`)&&(I=__classPrivateFieldGet(this,$p,`f`).unknownCommands(F)),__classPrivateFieldGet(this,qp,`f`)&&!I?__classPrivateFieldGet(this,$p,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Yp,`f`)&&__classPrivateFieldGet(this,$p,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,$p,`f`).limitedChoices(F),__classPrivateFieldGet(this,$p,`f`).implications(F),__classPrivateFieldGet(this,$p,`f`).conflicting(F)}}[Fm](){__classPrivateFieldSet(this,Mp,!0,`f`)}[Im](t){if(typeof t==`string`)__classPrivateFieldGet(this,Lp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Lp,`f`).key[n]=!0}}}),zm,Bm=__esmMin(()=>{Zf(),Rm(),zm=YargsFactory(Xf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Vm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.62.0`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var Hm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Um=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):Wm}function parseNpmrc(t){let n={registry:Wm,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var Wm,Gm=__esmMin(()=>{Wm=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var Km=__esmMin(()=>{Um(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var qm=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var Jm=__esmMin(()=>{Hm(),Um(),Gm(),Km()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var Ym=__esmMin(()=>{Hm(),Um(),Km(),qm()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var Xm=__esmMin(()=>{Hm(),Gm()}),Zm=__esmMin(()=>{Hm(),Gm(),qm(),Jm(),Ym(),Xm()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Qm===void 0&&(Qm=`0.62.0`),Qm}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Qm,$m=__esmMin(()=>{Fd(),jn(),Hn(),Zm()}),eh,th=__esmMin(()=>{eh=`gjsify`}),nh=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Nl(),__toCommonJS(kl)),N=(Fd(),__toCommonJS(Nd)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),rh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),ih=__commonJSMin(((t,n)=>{let S=rh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),ah=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Ll(),__toCommonJS(Pl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=nh(),W=ih();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),oh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),sh=__commonJSMin(((t,n)=>{var S=(Su(),__toCommonJS(vu)),C=oh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
148
+ `,`f`),__classPrivateFieldSet(this,Ip,__classPrivateFieldGet(this,Ip,`f`)+t.join(` `),`f`)}}}[nm](t){objectKeys(__classPrivateFieldGet(this,Lp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Lp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,Xp,`f`).getDescriptions()[t]}[im](t,n,S){__classPrivateFieldGet(this,Dp,`f`)[S]||(__classPrivateFieldGet(this,Kp,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Dp,`f`)[S]=!0)}[am](){__classPrivateFieldGet(this,kp,`f`).push({options:__classPrivateFieldGet(this,Lp,`f`),configObjects:__classPrivateFieldGet(this,Lp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Op,`f`),groups:__classPrivateFieldGet(this,jp,`f`),strict:__classPrivateFieldGet(this,qp,`f`),strictCommands:__classPrivateFieldGet(this,Jp,`f`),strictOptions:__classPrivateFieldGet(this,Yp,`f`),completionCommand:__classPrivateFieldGet(this,Cp,`f`),output:__classPrivateFieldGet(this,Ip,`f`),exitError:__classPrivateFieldGet(this,Tp,`f`),hasOutput:__classPrivateFieldGet(this,Mp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Bp,`f`),parseContext:__classPrivateFieldGet(this,Vp,`f`)}),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze(),__classPrivateFieldGet(this,yp,`f`).freeze(),__classPrivateFieldGet(this,Ap,`f`).freeze()}[om](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Kp,`f`).process.argv()[0])?__classPrivateFieldGet(this,Kp,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Kp,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[jm](__classPrivateFieldGet(this,bp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Kp,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Kp,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Kp,`f`).path.dirname(__classPrivateFieldGet(this,Kp,`f`).process.execPath())}/`,``)),t}[sm](){return __classPrivateFieldGet(this,zp,`f`)}[cm](){return __classPrivateFieldGet(this,Zp,`f`)}[lm](){if(!__classPrivateFieldGet(this,Ep,`f`))return;let t=__classPrivateFieldGet(this,Kp,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Kp,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[um](){return this[fm]().version||`unknown`}[dm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Kp,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,Hp,`f`)[n])return __classPrivateFieldGet(this,Hp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Kp,`f`).mainFilename;__classPrivateFieldGet(this,Kp,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Kp,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Kp,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Kp,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Kp,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,Hp,`f`)[n]=S||{},__classPrivateFieldGet(this,Hp,`f`)[n]}[pm](t,n){n=[].concat(n),n.forEach(n=>{n=this[_m](n),__classPrivateFieldGet(this,Lp,`f`)[t].push(n)})}[mm](t,n,S,C){this[gm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Lp,`f`)[t][n]=S})}[hm](t,n,S,C){this[gm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Lp,`f`)[t][n]=(__classPrivateFieldGet(this,Lp,`f`)[t][n]||[]).concat(S)})}[gm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[_m](S),C)}[_m](t){return t===`__proto__`?`___proto___`:t}[vm](t,n){return this[mm](this[vm].bind(this),`key`,t,n),this}[ym](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,kp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Kp,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,Lp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Op,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,jp,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Ip,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Tp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,Mp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,qp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Jp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Yp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Cp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Bp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Vp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Lp,`f`).configObjects=te,__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze(),__classPrivateFieldGet(this,yp,`f`).unfreeze(),__classPrivateFieldGet(this,Ap,`f`).unfreeze()}[bm](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[xm].bind(this),getContext:this[Sm].bind(this),getHasOutput:this[Cm].bind(this),getLoggerInstance:this[wm].bind(this),getParseContext:this[Tm].bind(this),getParserConfiguration:this[sm].bind(this),getUsageConfiguration:this[cm].bind(this),getUsageInstance:this[Em].bind(this),getValidationInstance:this[Dm].bind(this),hasParseCallback:this[Om].bind(this),isGlobalContext:this[km].bind(this),postProcess:this[Am].bind(this),reset:this[Mm].bind(this),runValidation:this[Pm].bind(this),runYargsParserAndExecuteCommands:this[Nm].bind(this),setHasOutput:this[Fm].bind(this)}}[xm](){return __classPrivateFieldGet(this,yp,`f`)}[Sm](){return __classPrivateFieldGet(this,xp,`f`)}[Cm](){return __classPrivateFieldGet(this,Mp,`f`)}[wm](){return __classPrivateFieldGet(this,Fp,`f`)}[Tm](){return __classPrivateFieldGet(this,Vp,`f`)||{}}[Em](){return __classPrivateFieldGet(this,Xp,`f`)}[Dm](){return __classPrivateFieldGet(this,$p,`f`)}[Om](){return!!__classPrivateFieldGet(this,Bp,`f`)}[km](){return __classPrivateFieldGet(this,Pp,`f`)}[Am](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[em](t)),(this[sm]()[`parse-positional-numbers`]||this[sm]()[`parse-positional-numbers`]===void 0)&&(t=this[dm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!1)),t)}[Mm](t={}){__classPrivateFieldSet(this,Lp,__classPrivateFieldGet(this,Lp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Lp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Lp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Up,`f`),Object.keys(__classPrivateFieldGet(this,jp,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,jp,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,jp,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Lp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Lp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Lp,`f`).envPrefix,__classPrivateFieldSet(this,Lp,n,`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldSet(this,$p,__classPrivateFieldGet(this,$p,`f`)?__classPrivateFieldGet(this,$p,`f`).reset(S):validation(this,__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldSet(this,yp,__classPrivateFieldGet(this,yp,`f`)?__classPrivateFieldGet(this,yp,`f`).reset():command(__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,Ap,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldGet(this,Sp,`f`)||__classPrivateFieldSet(this,Sp,completion(this,__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,yp,`f`),__classPrivateFieldGet(this,Kp,`f`)),`f`),__classPrivateFieldGet(this,Ap,`f`).reset(),__classPrivateFieldSet(this,Cp,null,`f`),__classPrivateFieldSet(this,Ip,``,`f`),__classPrivateFieldSet(this,Tp,null,`f`),__classPrivateFieldSet(this,Mp,!1,`f`),this.parsed=!1,this}[jm](t,n){return __classPrivateFieldGet(this,Kp,`f`).path.relative(t,n)}[Nm](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Wp,`f`),__classPrivateFieldGet(this,Lp,`f`).__=__classPrivateFieldGet(this,Kp,`f`).y18n.__,__classPrivateFieldGet(this,Lp,`f`).configuration=this[sm]();let I=!!__classPrivateFieldGet(this,Lp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Lp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Kp,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Lp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Vp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Np,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Qp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,Xp,`f`).clearCachedHelpMessage();try{if(this[lm](),n)return this[Am](q,I,!!S,!1);__classPrivateFieldGet(this,Np,`f`)&&[__classPrivateFieldGet(this,Np,`f`)].concat(X[__classPrivateFieldGet(this,Np,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,Pp,!1,`f`);let H=__classPrivateFieldGet(this,yp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Sp,`f`)?.completionKey?[__classPrivateFieldGet(this,Sp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Sp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Cp,`f`)){let t=__classPrivateFieldGet(this,yp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Am](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Cp,`f`)){t=F;break}!__classPrivateFieldGet(this,yp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Gp,`f`)&&t&&!re&&__classPrivateFieldGet(this,$p,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Cp,`f`)&&q._.includes(__classPrivateFieldGet(this,Cp,`f`))&&!ne&&(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,yp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,yp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Am](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Sp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Sp,`f`).getCompletion(n,(t,n)=>{if(t)throw new yl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Fp,`f`).log(t)}),this.exit(0)}),this[Am](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,Mp,`f`)||(Z?(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Fp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Op,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,Xp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Lp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Lp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new yl(W.error.message);if(!ne){let t=this[Pm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!0)),Y=this[bm](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Ap,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof yl)__classPrivateFieldGet(this,Xp,`f`).fail(t.message,t);else throw t}return this[Am](Y??q,I,!!S,!0)}[Pm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new yl(S.message);__classPrivateFieldGet(this,$p,`f`).nonOptionCount(F),__classPrivateFieldGet(this,$p,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Jp,`f`)&&(I=__classPrivateFieldGet(this,$p,`f`).unknownCommands(F)),__classPrivateFieldGet(this,qp,`f`)&&!I?__classPrivateFieldGet(this,$p,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Yp,`f`)&&__classPrivateFieldGet(this,$p,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,$p,`f`).limitedChoices(F),__classPrivateFieldGet(this,$p,`f`).implications(F),__classPrivateFieldGet(this,$p,`f`).conflicting(F)}}[Fm](){__classPrivateFieldSet(this,Mp,!0,`f`)}[Im](t){if(typeof t==`string`)__classPrivateFieldGet(this,Lp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Lp,`f`).key[n]=!0}}}),zm,Bm=__esmMin(()=>{Zf(),Rm(),zm=YargsFactory(Xf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Vm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.63.1-next.235`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var Hm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Um=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):Wm}function parseNpmrc(t){let n={registry:Wm,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var Wm,Gm=__esmMin(()=>{Wm=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var Km=__esmMin(()=>{Um(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var qm=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var Jm=__esmMin(()=>{Hm(),Um(),Gm(),Km()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var Ym=__esmMin(()=>{Hm(),Um(),Km(),qm()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var Xm=__esmMin(()=>{Hm(),Gm()}),Zm=__esmMin(()=>{Hm(),Um(),Gm(),qm(),Jm(),Ym(),Xm()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Qm===void 0&&(Qm=`0.63.1-next.235`),Qm}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Qm,$m=__esmMin(()=>{Fd(),jn(),Hn(),Zm()}),eh,th=__esmMin(()=>{eh=`gjsify`}),nh=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Nl(),__toCommonJS(kl)),N=(Fd(),__toCommonJS(Nd)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),rh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),ih=__commonJSMin(((t,n)=>{let S=rh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),ah=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Ll(),__toCommonJS(Pl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=nh(),W=ih();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),oh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),sh=__commonJSMin(((t,n)=>{var S=(Su(),__toCommonJS(vu)),C=oh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
149
149
  `)},set:function(t){S=t}});var F=null,I=Object.getOwnPropertyDescriptor(this,`stack`),H=I.get,W=I.value;delete I.value,delete I.writable,I.set=function(t){F=t},I.get=function(){var t=(F||(H?H.call(this):W)).split(/\r?\n+/g);F||(t[0]=this.name+`: `+this.message);var S=1;for(var C in n)if(n.hasOwnProperty(C)){var N=n[C];if(`line`in N){var I=N.line(this[C]);I&&t.splice(S++,0,` `+I)}`stack`in N&&N.stack(this[C],t)}return t.join(`
150
150
  `)},Object.defineProperty(this,"stack",I)};return Object.setPrototypeOf?(Object.setPrototypeOf(N.prototype,Error.prototype),Object.setPrototypeOf(N,Error)):S.inherits(N,Error),N};N.append=function(t,n){return{message:function(S,C){return S||=n,S&&(C[0]+=` `+t.replace(`%s`,S.toString())),C}}},N.line=function(t,n){return{line:function(S){return S||=n,S?t.replace(`%s`,S.toString()):null}}},n.exports=N})),ch=__commonJSMin(((t,n)=>{let hexify=t=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return`0x`+(n.length%2?`0`:``)+n},parseError=(t,n,S)=>{if(!n)return{message:t.message+` while parsing empty string`,position:0};let C=t.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),N=C?+C[2]:t.message.match(/^Unexpected end of JSON.*/i)?n.length-1:null,F=C?t.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(C[1])} (${hexify(C[1])})`):t.message;if(N!=null){let t=N<=S?0:N-S,C=N+S>=n.length?n.length:N+S,I=(t===0?``:`...`)+n.slice(t,C)+(C===n.length?``:`...`);return{message:F+` while parsing ${n===I?``:`near `}${JSON.stringify(I)}`,position:N}}else return{message:F+` while parsing '${n.slice(0,S*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(t,n,S,C){S||=20;let N=parseError(t,n,S);super(N.message),Object.assign(this,N),this.code=`EJSONPARSE`,this.systemError=t,Error.captureStackTrace(this,C||this.constructor)}get name(){return this.constructor.name}set name(t){}get[Symbol.toStringTag](){return this.constructor.name}};let S=Symbol.for(`indent`),C=Symbol.for(`newline`),N=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,F=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(t,n,I)=>{let H=stripBOM(t);I||=20;try{let[,t=`
151
151
  `,I=` `]=H.match(F)||H.match(N)||[,``,``],W=JSON.parse(H,n);return W&&typeof W==`object`&&(W[C]=t,W[S]=I),W}catch(n){if(typeof t!=`string`&&!Buffer.isBuffer(t)){let S=Array.isArray(t)&&t.length===0;throw Object.assign(TypeError(`Cannot parse ${S?`an empty array`:String(t)}`),{code:`EJSONPARSE`,systemError:n})}throw new JSONParseError(n,H,I,parseJson)}},stripBOM=t=>String(t).replace(/^\uFEFF/,``);n.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(t,n)=>{try{return JSON.parse(stripBOM(t),n)}catch{}}})),lh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
@@ -912,7 +912,7 @@ Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
912
912
  `);return`gjsify link: ${t.length} linked package(s) are not built, so linking them would hand the consumer a tree whose first import fails with MODULE_NOT_FOUND:\n${n}\n Build them in the checkout (\`gjsify run build\` there) and re-run, or narrow the selection with \`gjsify link <checkout> --packages <glob>\`. A link does not build.`}function assertDevLinksBuilt(t){let n=unbuiltDevLinks(t);if(n.length!==0)throw Error(formatUnbuiltDevLinks(n))}function collectStringLeaves(t,n){if(typeof t==`string`){n.push(t);return}if(!(!t||typeof t!=`object`))for(let S of Object.values(t))collectStringLeaves(S,n)}function ensureLocallyIgnored(t){let n=resolveGitDir(t);if(!n.commonDir)return n.why;let S=xn(t,`.gitignore`);if(existsSync(S)&&fileMentionsPattern(S,`.gjsify-link.json`))return`already-ignored`;let C=xn(n.commonDir,`info`,`exclude`);if(existsSync(C)&&fileMentionsPattern(C,`.gjsify-link.json`))return`already-ignored`;mkdirSync(wn(C),{recursive:!0});let N=existsSync(C)?readFileSync(C,`utf-8`):``;return writeFileSync(C,`${N}${N===``||N.endsWith(`
913
913
  `)?``:`
914
914
  `}${xL}\n${bL}\n`),`added`}function removeLocalIgnore(t){let n=resolveGitDir(t);if(!n.commonDir)return n.why;let S=xn(n.commonDir,`info`,`exclude`),C;try{C=readFileSync(S,`utf-8`)}catch{return`absent`}let N=C.split(/\r?\n/),F=[],I=!1;for(let t=0;t<N.length;t++){if(!I&&N[t]?.trim()===xL&&(N[t+1]?.trim()===`.gjsify-link.json`||N[t+1]?.trim()===`/.gjsify-link.json`)){t++,I=!0;continue}F.push(N[t]??``)}return I?(writeFileSync(S,F.join(`
915
- `)),`removed`):`absent`}function fileMentionsPattern(t,n){let S;try{S=readFileSync(t,`utf-8`)}catch{return!1}return S.split(/\r?\n/).some(t=>{let S=t.trim();return S===n||S===`/${n}`})}function resolveGitDir(t){let n=xn(t,`.git`),S;try{S=statSync(n)}catch{return{commonDir:null,why:`no-git`}}if(S.isDirectory())return{commonDir:n,why:`no-git`};let C;try{C=readFileSync(n,`utf-8`).trim()}catch{return{commonDir:null,why:`unreadable-git`}}let N=/^gitdir:\s*(.+)$/.exec(C)?.[1]?.trim();return N?followCommondir(bn(N)?N:vn(t,N)):{commonDir:null,why:`unreadable-git`}}function followCommondir(t){let n=xn(t,`commondir`);if(!existsSync(n))return{commonDir:t,why:`no-git`};let S;try{S=readFileSync(n,`utf-8`)}catch{return{commonDir:null,why:`unreadable-git`}}let C=S.trim();if(!C)return{commonDir:null,why:`unreadable-git`};let N=bn(C)?C:vn(t,C);return existsSync(N)?{commonDir:N,why:`no-git`}:{commonDir:null,why:`unreadable-git`}}function assertNoDevLinkUnderImmutable(t){let n=devLinkRoot(t),S=devLinkPath(n);if(!existsSync(S))return;let C=`(unreadable)`;try{C=readDevLinkOverride(n)?.checkout??C}catch{}throw Error(`gjsify install --immutable: a development link override is active — ${S}\nIt points at ${C}, so this install would build from a local checkout instead of what ${xn(n,`gjsify-lock.json`)} pins. --immutable builds only what is committed.\nRun \`gjsify unlink\` (in ${n}) or delete ${bL}, then re-run.`)}var bL,xL,SL=__esmMin(()=>{Fd(),jn(),IP(),fL(),LP(),yL(),RP(),bL=`.gjsify-link.json`,xL=`# gjsify link — local development override, never commit`}),CL=__exportAll$5({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,parseSpecName:()=>parseSpecName,pickVersion:()=>pickVersion,reachableInstallPaths:()=>reachableInstallPaths,readLockfileNodes:()=>readLockfileNodes,requiredDepEntries:()=>requiredDepEntries,requiredPeerEntries:()=>requiredPeerEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(t){if(assertNativeBackendNodeVersion(),t.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(t.prefix,{recursive:!0});let n=await loadNpmrc$1(t),S=makeLogger(t.verbose??!1),C=await acquireInstallLock(t.prefix,{signal:t.signal});try{return await installPackagesNativeLocked(t,n,S)}finally{C.release()}}async function installPackagesNativeLocked(t,n,S){let C=t.progress,N=xn(t.prefix,TL),F=readLockfile(N),I=resolveHostPlatform(),H=readPlatformForce(process.env);S(`install: platform target %s%s`,describePlatformTarget(I),H?` (--force: checks bypassed)`:``);let W,q=!1,Y=new Set;if(t.frozen||t.focusSpecs){let n=t.frozen?`--immutable`:`--focus`,C=t.frozen?`(without --immutable)`:`(without --focus)`;if(!F)throw Error(`install: ${n} requires ${TL} at ${t.prefix} — none found. Run \`gjsify install\` ${C} to generate one and commit it.`);let I=describeLockfileDrift(F,t.specs);if(I)throw Error(`install: ${n} but ${N} is stale.\n${I}\nRe-run \`gjsify install\` ${C} to refresh the lockfile.`);if(S(`install: %s, using lockfile (%d package(s))`,n,Object.keys(F.packages).length),W=lockfileToNodes(F),t.frozen&&assertNoExtraneous(t.prefix,W),t.focusSpecs){let n=reachableInstallPaths(W,t.focusSpecs.map(parseSpecName));S(`install: --focus keeps %d of %d lockfile package(s)`,n.size,W.length),W=W.filter(t=>n.has(t.installPath))}}else if(!t.refreshLockfile&&F&&F.lockfileVersion===EL&&F.peersResolved===!0&&lockfileMatchesRequest(F,t.specs))S(`install: using lockfile (%d package(s))`,Object.keys(F.packages).length),W=lockfileToNodes(F);else{let N=!t.refreshLockfile&&F?buildPreferredVersions(F):void 0;S(`install: resolving %d top-level spec(s) → %s%s`,t.specs.length,t.prefix,N?` (preserving ${N.size} locked name(s))`:``);let I=await resolveDeps(t.specs,n,S,t.overrides,t.skipDeps,t.signal,C,N,t.workspaceNames,t.specOrigins,t.optionalSpecs);W=I.nodes,Y=I.skippedEdges,q=!0}computeOptionalFlags(W,requiredTopLevelNames(t.focusSpecs??t.specs,t.optionalSpecs),S),assertRequiredEdgesResolved(W,Y),q&&t.lockfile&&(writeLockfile(N,t.specs,W),S(`install: wrote %s (%d entries)`,TL,W.length));let X=W;if(t.workspaceNames&&t.workspaceNames.size>0){let n=X.length;X=X.filter(n=>!t.workspaceNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d workspace-provided package(s) symlinked, not fetched`,C)}if(t.linkedNames&&t.linkedNames.size>0){let n=X.length;X=X.filter(n=>!t.linkedNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d dev-linked package(s) provided by a local checkout, not fetched`,C)}let Z=applyPlatformFilter(X,I,H,S);return S(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,t.prefix,n,S,t.signal,C),await linkBins(Z,t.prefix,S),warnMissingNativeBuilds(Z,t.prefix,S),S(`install: done`),topLevelResolutions(t.specs,W)}function assertNoExtraneous(t,n){let S=findExtraneous({prefix:t,installed:scanPrefix(t),expected:n});if(S.length!==0)throw Error(formatExtraneousError(S,t))}function errMsg(t){return t instanceof Error?t.message:String(t)}function applyPlatformFilter(t,n,S,C){let N=[],F=0;for(let I of t){let t=I.platform;if(!t||!declaresPlatform(t)){N.push(I);continue}let H=checkPlatform(t,n);if(H.ok){N.push(I);continue}let W=`${I.name}@${I.version}`;if(!I.optional){if(S){C(`platform-forced: %s (required, incompatible, installed anyway via --force)`,W),N.push(I);continue}throw badPlatformError(W,H)}I.inert=!0,F++,C(`platform-skip: %s (%s) current=%s required=%s`,W,I.installPath,JSON.stringify(H.current),JSON.stringify(H.required))}return F>0&&C(`install: %d optional package(s) inert — not installable on %s`,F,describePlatformTarget(n)),N}function warnMissingNativeBuilds(t,n,S){let C=process.platform,N=process.arch,F=[`preinstall`,`install`,`postinstall`];for(let I of t){let t=xn(n,I.installPath),H;try{H=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))?.scripts}catch{continue}if(!H||typeof H!=`object`)continue;let W=F.find(t=>typeof H[t]==`string`);if(W===void 0)continue;let q=!1;try{let n=xn(t,`prebuilds`);for(let t of readdirSync(n))if(t.startsWith(`${C}-`)&&readdirSync(xn(n,t)).length>0){q=!0;break}}catch{}if(!q)try{q=readdirSync(xn(t,`build`,`Release`)).some(t=>t.endsWith(`.node`)||t.endsWith(`.so`))}catch{}q||S("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",I.name,W,C,N,I.installPath,C,N)}}function topLevelResolutions(t,n){let S=new Map;for(let t of n)t.installPath===`node_modules/${t.name}`&&S.set(t.name,t);let C=[];for(let n of t){let t=parseSpecName(n),N=S.get(t);N&&C.push({name:N.name,version:N.version})}return C}function parseSpecName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return t;let S=t.indexOf(`@`,n+1);return S===-1?t:t.slice(0,S)}let n=t.indexOf(`@`);return n===-1?t:t.slice(0,n)}async function resolveDeps(t,n,S,C,N,F,I,H,W,q,Y){I?.beginPhase(`resolve`,t.length);let applyOverride=(t,n)=>{if(!C)return n;let N=C[t];return typeof N!=`string`||N.length===0||N===n?n:(S(`install: override %s %s → %s`,t,n,N),N)},X=new Map,fetchPkg=t=>{let C=X.get(t);if(C)return C;let N=fetchPackumentWithDiskCache(t,n,S,F,`full`);return X.set(t,N),N},Z=new Map,te=new Map,ne=new Set,re=new Map,ie=t.map(parseSpec$1).map(t=>{let n=applyOverride(t.name,t.range),S=re.get(t.name);S||(S=new Map,re.set(t.name,S));let C=S.get(n);C||(C=new Set,S.set(n,C));for(let n of q?.get(`${t.name}@${t.range}`)??[])C.add(n);return{from:null,name:t.name,range:n,required:!Y?.has(t.name)}});for(;ie.length>0;){let t=ie.splice(0,ie.length),n=[],C=new Set;for(let S of t)X.has(S.name)||C.has(S.name)||(C.add(S.name),n.push(S.name));await prefetchPackuments(n,fetchPkg,F);for(let n=0;n<t.length;n++){let C=t[n];if(W?.has(C.name))continue;let F=findVisible(C.from,C.name,Z);if(F&&satisfiesRange(F.version,C.range))continue;if(C.peerOf){let t=C.from===null?`node_modules/${C.name}`:`${C.from}/node_modules/${C.name}`,n=Z.get(t);if(n){ge.warn(`[gjsify] warning: peer dependency conflict: ${C.peerOf.name}@${C.peerOf.version} wants ${C.name}@${C.range}, but ${n.version} is installed at ${n.installPath} — keeping it (npm's non-strict behaviour).`);continue}}let q=null;try{let F=await fetchPkg(C.name),W=preferredVersionFor(H?.get(C.name),C.range);if(q=pickVersion(F,C.range,W),!q)throw Error(`No version of ${C.name} satisfies ${C.range}`);let Y=F.versions[q];if(!Y)throw Error(`Packument for ${C.name} promised ${q} but no entry exists`);let X=decidePlacement(C.from,C.name,q,te),ne={name:C.name,version:q,tarballUrl:Y.dist.tarball,integrity:Y.dist.integrity,installPath:X,dependencies:Y.dependencies??{},optionalDependencies:Y.optionalDependencies??{},peerDependencies:nonEmpty(Y.peerDependencies),peerDependenciesMeta:nonEmpty(Y.peerDependenciesMeta),bin:Y.bin,platform:platformDeclarationOf(Y),optional:!C.required};if(Z.set(X,ne),X===`node_modules/${C.name}`&&te.set(C.name,ne),S(`resolve: %s@%s ← %s (at %s)`,C.name,q,C.range,X),I?.update({phase:`resolve`,current:Z.size,total:Z.size+(t.length-n-1)+ie.length,name:`${C.name}@${q}`}),!N){let t=parentInstallPath(X);for(let[n,S]of requiredPeerEntries(ne))ie.push({from:t,name:n,range:applyOverride(n,S),required:!ne.optional,peerOf:ne});for(let[t,n]of requiredDepEntries(ne))ie.push({from:X,name:t,range:applyOverride(t,n),required:!ne.optional});for(let[t,n]of Object.entries(ne.optionalDependencies))ie.push({from:X,name:t,range:applyOverride(t,n),required:!1})}}catch(t){if(!C.required){ne.add(edgeKey(C.peerOf?.installPath??C.from,C.name)),S(`resolve: optional dep %s@%s skipped (%s)`,C.name,C.range,errMsg(t));continue}throw t}}}return I?.endPhase(`resolve`),emitTopLevelConflictWarnings(re,te),{nodes:Array.from(Z.values()),skippedEdges:ne}}function platformDeclarationOf(t){let n={os:t.os,cpu:t.cpu,libc:t.libc};return declaresPlatform(n)?n:void 0}function edgeKey(t,n){return`${t??``}\n${n}`}function parseEdgeKey(t){let n=t.indexOf(`
915
+ `)),`removed`):`absent`}function fileMentionsPattern(t,n){let S;try{S=readFileSync(t,`utf-8`)}catch{return!1}return S.split(/\r?\n/).some(t=>{let S=t.trim();return S===n||S===`/${n}`})}function resolveGitDir(t){let n=xn(t,`.git`),S;try{S=statSync(n)}catch{return{commonDir:null,why:`no-git`}}if(S.isDirectory())return{commonDir:n,why:`no-git`};let C;try{C=readFileSync(n,`utf-8`).trim()}catch{return{commonDir:null,why:`unreadable-git`}}let N=/^gitdir:\s*(.+)$/.exec(C)?.[1]?.trim();return N?followCommondir(bn(N)?N:vn(t,N)):{commonDir:null,why:`unreadable-git`}}function followCommondir(t){let n=xn(t,`commondir`);if(!existsSync(n))return{commonDir:t,why:`no-git`};let S;try{S=readFileSync(n,`utf-8`)}catch{return{commonDir:null,why:`unreadable-git`}}let C=S.trim();if(!C)return{commonDir:null,why:`unreadable-git`};let N=bn(C)?C:vn(t,C);return existsSync(N)?{commonDir:N,why:`no-git`}:{commonDir:null,why:`unreadable-git`}}function assertNoDevLinkUnderImmutable(t){let n=devLinkRoot(t),S=devLinkPath(n);if(!existsSync(S))return;let C=`(unreadable)`;try{C=readDevLinkOverride(n)?.checkout??C}catch{}throw Error(`gjsify install --immutable: a development link override is active — ${S}\nIt points at ${C}, so this install would build from a local checkout instead of what ${xn(n,`gjsify-lock.json`)} pins. --immutable builds only what is committed.\nRun \`gjsify unlink\` (in ${n}) or delete ${bL}, then re-run.`)}var bL,xL,SL=__esmMin(()=>{Fd(),jn(),IP(),fL(),LP(),yL(),RP(),bL=`.gjsify-link.json`,xL=`# gjsify link — local development override, never commit`}),CL=__exportAll$5({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,parseSpecName:()=>parseSpecName,pickVersion:()=>pickVersion,reachableInstallPaths:()=>reachableInstallPaths,readLockfileNodes:()=>readLockfileNodes,requiredDepEntries:()=>requiredDepEntries,requiredPeerEntries:()=>requiredPeerEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(t){if(assertNativeBackendNodeVersion(),t.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(t.prefix,{recursive:!0});let n=await loadNpmrc$1(t),S=makeLogger(t.verbose??!1),C=await acquireInstallLock(t.prefix,{signal:t.signal});try{return await installPackagesNativeLocked(t,n,S)}finally{C.release()}}async function installPackagesNativeLocked(t,n,S){let C=t.progress,N=xn(t.prefix,TL),F=readLockfile(N),I=resolveHostPlatform(),H=readPlatformForce(process.env);S(`install: platform target %s%s`,describePlatformTarget(I),H?` (--force: checks bypassed)`:``);let W,q=!1,Y=new Set;if(t.frozen||t.focusSpecs){let n=t.frozen?`--immutable`:`--focus`,C=t.frozen?`(without --immutable)`:`(without --focus)`;if(!F)throw Error(`install: ${n} requires ${TL} at ${t.prefix} — none found. Run \`gjsify install\` ${C} to generate one and commit it.`);let I=describeLockfileDrift(F,t.specs);if(I)throw Error(`install: ${n} but ${N} is stale.\n${I}\nRe-run \`gjsify install\` ${C} to refresh the lockfile.`);if(S(`install: %s, using lockfile (%d package(s))`,n,Object.keys(F.packages).length),W=lockfileToNodes(F),t.frozen&&assertNoExtraneous(t.prefix,W),t.focusSpecs){let n=reachableInstallPaths(W,t.focusSpecs.map(parseSpecName));S(`install: --focus keeps %d of %d lockfile package(s)`,n.size,W.length),W=W.filter(t=>n.has(t.installPath))}}else if(!t.refreshLockfile&&F&&F.lockfileVersion===EL&&F.peersResolved===!0&&lockfileMatchesRequest(F,t.specs))S(`install: using lockfile (%d package(s))`,Object.keys(F.packages).length),W=lockfileToNodes(F);else{let N=!t.refreshLockfile&&F?buildPreferredVersions(F):void 0;S(`install: resolving %d top-level spec(s) → %s%s`,t.specs.length,t.prefix,N?` (preserving ${N.size} locked name(s))`:``);let I=await resolveDeps(t.specs,n,S,t.overrides,t.skipDeps,t.signal,C,N,t.workspaceNames,t.specOrigins,t.optionalSpecs,t.linkedNames);W=I.nodes,Y=I.skippedEdges,q=!0}computeOptionalFlags(W,requiredTopLevelNames(t.focusSpecs??t.specs,t.optionalSpecs),S),assertRequiredEdgesResolved(W,Y),q&&t.lockfile&&(writeLockfile(N,t.specs,W),S(`install: wrote %s (%d entries)`,TL,W.length));let X=W;if(t.workspaceNames&&t.workspaceNames.size>0){let n=X.length;X=X.filter(n=>!t.workspaceNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d workspace-provided package(s) symlinked, not fetched`,C)}if(t.linkedNames&&t.linkedNames.size>0){let n=X.length;X=X.filter(n=>!t.linkedNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d dev-linked package(s) provided by a local checkout, not fetched`,C)}let Z=applyPlatformFilter(X,I,H,S);return S(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,t.prefix,n,S,t.signal,C),await linkBins(Z,t.prefix,S),warnMissingNativeBuilds(Z,t.prefix,S),S(`install: done`),topLevelResolutions(t.specs,W)}function assertNoExtraneous(t,n){let S=findExtraneous({prefix:t,installed:scanPrefix(t),expected:n});if(S.length!==0)throw Error(formatExtraneousError(S,t))}function errMsg(t){return t instanceof Error?t.message:String(t)}function applyPlatformFilter(t,n,S,C){let N=[],F=0;for(let I of t){let t=I.platform;if(!t||!declaresPlatform(t)){N.push(I);continue}let H=checkPlatform(t,n);if(H.ok){N.push(I);continue}let W=`${I.name}@${I.version}`;if(!I.optional){if(S){C(`platform-forced: %s (required, incompatible, installed anyway via --force)`,W),N.push(I);continue}throw badPlatformError(W,H)}I.inert=!0,F++,C(`platform-skip: %s (%s) current=%s required=%s`,W,I.installPath,JSON.stringify(H.current),JSON.stringify(H.required))}return F>0&&C(`install: %d optional package(s) inert — not installable on %s`,F,describePlatformTarget(n)),N}function warnMissingNativeBuilds(t,n,S){let C=process.platform,N=process.arch,F=[`preinstall`,`install`,`postinstall`];for(let I of t){let t=xn(n,I.installPath),H;try{H=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))?.scripts}catch{continue}if(!H||typeof H!=`object`)continue;let W=F.find(t=>typeof H[t]==`string`);if(W===void 0)continue;let q=!1;try{let n=xn(t,`prebuilds`);for(let t of readdirSync(n))if(t.startsWith(`${C}-`)&&readdirSync(xn(n,t)).length>0){q=!0;break}}catch{}if(!q)try{q=readdirSync(xn(t,`build`,`Release`)).some(t=>t.endsWith(`.node`)||t.endsWith(`.so`))}catch{}q||S("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",I.name,W,C,N,I.installPath,C,N)}}function topLevelResolutions(t,n){let S=new Map;for(let t of n)t.installPath===`node_modules/${t.name}`&&S.set(t.name,t);let C=[];for(let n of t){let t=parseSpecName(n),N=S.get(t);N&&C.push({name:N.name,version:N.version})}return C}function parseSpecName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return t;let S=t.indexOf(`@`,n+1);return S===-1?t:t.slice(0,S)}let n=t.indexOf(`@`);return n===-1?t:t.slice(0,n)}async function resolveDeps(t,n,S,C,N,F,I,H,W,q,Y,X){I?.beginPhase(`resolve`,t.length);let applyOverride=(t,n)=>{if(!C)return n;let N=C[t];return typeof N!=`string`||N.length===0||N===n?n:(S(`install: override %s %s → %s`,t,n,N),N)},Z=new Map,fetchPkg=t=>{let C=Z.get(t);if(C)return C;let N=fetchPackumentWithDiskCache(t,n,S,F,`full`);return Z.set(t,N),N},te=new Map,ne=new Map,re=new Set,ie=new Map,ae=t.map(parseSpec$1).map(t=>{let n=applyOverride(t.name,t.range),S=ie.get(t.name);S||(S=new Map,ie.set(t.name,S));let C=S.get(n);C||(C=new Set,S.set(n,C));for(let n of q?.get(`${t.name}@${t.range}`)??[])C.add(n);return{from:null,name:t.name,range:n,required:!Y?.has(t.name)}});for(;ae.length>0;){let t=ae.splice(0,ae.length),n=[],C=new Set;for(let S of t)Z.has(S.name)||C.has(S.name)||(C.add(S.name),n.push(S.name));await prefetchPackuments(n,fetchPkg,F);for(let n=0;n<t.length;n++){let C=t[n];if(W?.has(C.name))continue;let F=findVisible(C.from,C.name,te);if(F&&satisfiesRange(F.version,C.range))continue;if(C.peerOf){let t=C.from===null?`node_modules/${C.name}`:`${C.from}/node_modules/${C.name}`,n=te.get(t);if(n){ge.warn(`[gjsify] warning: peer dependency conflict: ${C.peerOf.name}@${C.peerOf.version} wants ${C.name}@${C.range}, but ${n.version} is installed at ${n.installPath} — keeping it (npm's non-strict behaviour).`);continue}}let q=null;try{let F=await fetchPkg(C.name),W=preferredVersionFor(H?.get(C.name),C.range);if(q=pickVersion(F,C.range,W),!q)throw Error(`No version of ${C.name} satisfies ${C.range}`);let Y=F.versions[q];if(!Y)throw Error(`Packument for ${C.name} promised ${q} but no entry exists`);let X=decidePlacement(C.from,C.name,q,ne),Z={name:C.name,version:q,tarballUrl:Y.dist.tarball,integrity:Y.dist.integrity,installPath:X,dependencies:Y.dependencies??{},optionalDependencies:Y.optionalDependencies??{},peerDependencies:nonEmpty(Y.peerDependencies),peerDependenciesMeta:nonEmpty(Y.peerDependenciesMeta),bin:Y.bin,platform:platformDeclarationOf(Y),optional:!C.required};if(te.set(X,Z),X===`node_modules/${C.name}`&&ne.set(C.name,Z),S(`resolve: %s@%s ← %s (at %s)`,C.name,q,C.range,X),I?.update({phase:`resolve`,current:te.size,total:te.size+(t.length-n-1)+ae.length,name:`${C.name}@${q}`}),!N){let t=parentInstallPath(X);for(let[n,S]of requiredPeerEntries(Z))ae.push({from:t,name:n,range:applyOverride(n,S),required:!Z.optional,peerOf:Z});for(let[t,n]of requiredDepEntries(Z))ae.push({from:X,name:t,range:applyOverride(t,n),required:!Z.optional});for(let[t,n]of Object.entries(Z.optionalDependencies))ae.push({from:X,name:t,range:applyOverride(t,n),required:!1})}}catch(t){if(X?.has(C.name)&&t instanceof PackageNotFoundError){S(`resolve: dev-linked %s not published — provided by the local checkout`,C.name);continue}if(!C.required){re.add(edgeKey(C.peerOf?.installPath??C.from,C.name)),S(`resolve: optional dep %s@%s skipped (%s)`,C.name,C.range,errMsg(t));continue}throw t}}}return I?.endPhase(`resolve`),emitTopLevelConflictWarnings(ie,ne),{nodes:Array.from(te.values()),skippedEdges:re}}function platformDeclarationOf(t){let n={os:t.os,cpu:t.cpu,libc:t.libc};return declaresPlatform(n)?n:void 0}function edgeKey(t,n){return`${t??``}\n${n}`}function parseEdgeKey(t){let n=t.indexOf(`
916
916
  `),S=t.slice(0,n);return{from:S===``?null:S,name:t.slice(n+1)}}function requiredTopLevelNames(t,n){let S=new Set;for(let C of t){let t=parseSpecName(C);n?.has(t)||S.add(t)}return S}function requiredDepEntries(t){let n=[];for(let[S,C]of Object.entries(t.dependencies))S in t.optionalDependencies||n.push([S,C]);return n}function requiredPeerEntries(t){let n=[];for(let[S,C]of Object.entries(t.peerDependencies??{}))t.peerDependenciesMeta?.[S]?.optional!==!0&&(S in t.dependencies||S in t.optionalDependencies||n.push([S,C]));return n}function computeOptionalFlags(t,n,S){let C=new Map;for(let n of t)C.set(n.installPath,n);let N=new Set,F=[],enter=t=>{N.has(t.installPath)||(N.add(t.installPath),F.push(t.installPath))};for(let t of n){let n=C.get(`node_modules/${t}`);n&&enter(n)}for(;F.length>0;){let t=F.pop();if(t===void 0)break;let n=C.get(t);if(n)for(let[S]of[...requiredDepEntries(n),...requiredPeerEntries(n)]){let n=findVisible(t,S,C);n&&enter(n)}}let I=0;for(let n of t){let t=!N.has(n.installPath);(n.optional??!1)!==t&&I++,n.optional=t}S(`install: optionality fixpoint — %d of %d node(s) reachable only via optional edges%s`,t.length-N.size,t.length,I>0?`; corrected ${I} incoming flag(s)`:``)}function reachableInstallPaths(t,n){let S=new Map;for(let n of t)S.set(n.installPath,n);let C=new Set,N=[],enter=t=>{!t||C.has(t.installPath)||(C.add(t.installPath),N.push(t))};for(let t of n)enter(S.get(`node_modules/${t}`));for(let t=N.pop();t;t=N.pop()){let n=[...Object.keys(t.dependencies),...Object.keys(t.optionalDependencies),...requiredPeerEntries(t).map(([t])=>t)];for(let C of n)enter(findVisible(t.installPath,C,S))}return C}function readLockfileNodes(t){let n=readLockfile(t);return n?lockfileToNodes(n):null}function assertRequiredEdgesResolved(t,n){if(n.size===0)return;let S=new Map;for(let n of t)S.set(n.installPath,n);for(let t of n){let{from:n,name:C}=parseEdgeKey(t);if(n===null)continue;let N=S.get(n);if(N&&!N.optional&&!(C in N.optionalDependencies))throw Error(`install: required dependency ${C} of ${N.name}@${N.version} (${N.installPath}) could not be resolved.\nThe failure was tolerated during the walk because ${N.name} looked optional at that point, but the final dependency graph makes it required — so ${C} is required too and the tree would be incomplete.\nRe-run with --verbose and look for the "resolve: optional dep ${C}@… skipped (…)" line for the underlying cause.`)}}function emitTopLevelConflictWarnings(t,n){for(let[S,C]of t){if(C.size<2)continue;let t=n.get(S);if(!t)continue;let describe=(t,n)=>n.size>0?`${t} (requested by ${[...n].join(`, `)})`:t,N=[],F=[];for(let[n,S]of C){let C;try{C=satisfies(t.version,new NP(n))}catch{continue}(C?N:F).push(describe(n,S))}F.length!==0&&ge.warn(`[gjsify] warning: version conflict for ${S}: installed ${t.version} at ${t.installPath} — does NOT satisfy ${F.join(`, `)}`+(N.length>0?`; satisfies ${N.join(`, `)}`:``)+`. One hoisted copy serves all requesters until the per-workspace dedup pass lands (Phase D.8).`)}}async function fetchPackumentWithDiskCache(t,n,S,C,N=`corgi`){let F=registryFor(t,n),I=N===`full`,H=getCachedPackument(F,t,N),onRetry=({attempt:n,error:C,delayMs:F})=>{S(`packument %s (%s): retry %d after %dms (%s)`,t,N,n,F,errMsg(C))},W=await fetchPackumentConditional(t,{npmrc:n,signal:C,ifNoneMatch:H?.etag,fullMetadata:I,onRetry});return W.status===`not-modified`&&H?(S(`packument-cache-hit: %s (%s, 304, etag %s)`,t,N,H.etag),H.packument):W.status===`fresh`&&W.packument?(W.etag&&putCachedPackument(F,t,W.etag,W.packument,N),W.packument):fetchPackument(t,{npmrc:n,signal:C,fullMetadata:I,onRetry})}async function prefetchPackuments(t,n,S){if(t.length===0)return;let C=0,N=Math.max(1,Math.min(wL,t.length)),worker=async()=>{for(;C<t.length;){if(S?.aborted)return;let N=t[C++];try{await n(N)}catch{}}};await Promise.all(Array.from({length:N},()=>worker()))}function findVisible(t,n,S){let C=[];if(t!==null){C.push(`${t}/node_modules/${n}`);let S=t;for(;;){let t=S.lastIndexOf(`/node_modules/`);if(t<0||(S=S.slice(0,t),C.push(`${S}/node_modules/${n}`),S===``))break}}C.push(`node_modules/${n}`);for(let t of C){let n=S.get(t);if(n)return n}return null}function parentInstallPath(t){let n=t.lastIndexOf(`/node_modules/`);return n<0?null:t.slice(0,n)}function decidePlacement(t,n,S,C){let N=C.get(n);return!N||N.version===S||t===null?`node_modules/${n}`:`${t}/node_modules/${n}`}function satisfiesRange(t,n){try{return satisfies(t,new NP(n))}catch{return!1}}function readLockfile(t){if(!existsSync(t))return null;try{let n=JSON.parse(readFileSync(t,`utf-8`));return!DL.has(n.lockfileVersion)||!n.packages||typeof n.packages!=`object`?null:n}catch{return null}}function writeLockfile(t,n,S){let C={},N=[...S].sort((t,n)=>t.installPath<n.installPath?-1:+(t.installPath>n.installPath));for(let t of N)C[t.installPath]={version:t.version,resolved:t.tarballUrl,integrity:t.integrity,dependencies:Object.keys(t.dependencies).length>0?t.dependencies:void 0,optionalDependencies:Object.keys(t.optionalDependencies).length>0?t.optionalDependencies:void 0,peerDependencies:nonEmpty(t.peerDependencies),peerDependenciesMeta:nonEmpty(t.peerDependenciesMeta),bin:t.bin,os:t.platform?.os,cpu:t.platform?.cpu,libc:t.platform?.libc,optional:t.optional?!0:void 0};let F={lockfileVersion:EL,requested:[...n],packages:C,peersResolved:!0};atomicWriteStrict(t,JSON.stringify(F,null,2)+`
917
917
  `)}function nonEmpty(t){return t&&Object.keys(t).length>0?t:void 0}function buildPreferredVersions(t){let n=new Map;for(let[S,C]of Object.entries(t.packages)){let t=nameFromInstallPath(S),N=n.get(t);N||(N=new Set,n.set(t,N)),N.add(C.version)}return n}function preferredVersionFor(t,n){if(!t||t.size===0)return;let S;for(let C of t)satisfiesRange(C,n)&&(S===void 0||new SemVer(C).compare(new SemVer(S))>0)&&(S=C);return S}function lockfileToNodes(t){return Object.entries(t.packages).map(([t,n])=>{let S={os:n.os,cpu:n.cpu,libc:n.libc};return{name:nameFromInstallPath(t),version:n.version,tarballUrl:n.resolved,integrity:n.integrity,installPath:t,dependencies:n.dependencies??{},optionalDependencies:n.optionalDependencies??{},peerDependencies:n.peerDependencies,peerDependenciesMeta:n.peerDependenciesMeta,bin:n.bin,platform:declaresPlatform(S)?S:void 0,optional:n.optional===!0}})}function nameFromInstallPath(t){let n=t.lastIndexOf(`/node_modules/`);return n<0?t.replace(/^node_modules\//,``):t.slice(n+14)}function lockfileMatchesRequest(t,n){if(t.requested.length!==n.length)return!1;let S=[...t.requested].sort(),C=[...n].sort();return S.every((t,n)=>t===C[n])}function describeLockfileDrift(t,n){let S=new Set(t.requested),C=new Set(n),N=[],F=[];for(let t of C)S.has(t)||N.push(t);for(let t of S)C.has(t)||F.push(t);if(N.length===0&&F.length===0)return null;let I=[];return N.length>0&&I.push(` + ${N.sort().join(`
918
918
  + `)}`),F.length>0&&I.push(` - ${F.sort().join(`
@@ -923,7 +923,7 @@ Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
923
923
  echo "gjsify: got: node $*" >&2
924
924
  exit 127 ;;
925
925
  esac
926
- `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var LL,RL,zL,BL=__esmMin(()=>{Yc(),Fd(),Ag(),jn(),Hn(),i_(),yI(),sF(),LI(),IL(),RP(),LL=!1,RL=!1,zL=`node-shim`});function markDaemonCommand(){VL=!0}function isDaemonCommand(){return VL}var VL,HL=__esmMin(()=>{VL=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(xn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=vn(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Tn(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=xn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[xn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(xn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(sK(),oK));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var UL,WL=__esmMin(()=>{_e(),Fd(),jn(),dI(),P_(),DI(),kI(),FI(),II(),BL(),RP(),qF(),HL(),IP(),i_(),L_(),UL={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:F_,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${F_.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(xn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=vn(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),GL,KL=__esmMin(()=>{_e(),jn(),sF(),GL={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?vn(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),qL,JL=__esmMin(()=>{_e(),nF(),qL={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
926
+ `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var LL,RL,zL,BL=__esmMin(()=>{Yc(),Fd(),Ag(),jn(),Hn(),i_(),yI(),sF(),LI(),IL(),RP(),LL=!1,RL=!1,zL=`node-shim`});function markDaemonCommand(){VL=!0}function isDaemonCommand(){return VL}var VL,HL=__esmMin(()=>{VL=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(xn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=vn(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Tn(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=xn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[xn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(xn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(dK(),uK));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var UL,WL=__esmMin(()=>{_e(),Fd(),jn(),dI(),P_(),DI(),kI(),FI(),II(),BL(),RP(),qF(),HL(),IP(),i_(),L_(),UL={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:F_,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${F_.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(xn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=vn(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),GL,KL=__esmMin(()=>{_e(),jn(),sF(),GL={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?vn(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),qL,JL=__esmMin(()=>{_e(),nF(),qL={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
927
927
  `);let H=n.filter(t=>t.severity===`required`),W=n.filter(t=>t.severity===`optional`);if(H.length>0){ge.log(`Required:`);for(let t of H){let n=t.found?`✓`:`✗`,S=t.version?` (${t.version})`:``;ge.log(` ${n} ${t.name}${S}`)}}if(W.length>0){ge.log(`
928
928
  Optional:`);for(let t of W){let n=t.found?`✓`:`⚠`,S=t.version?` (${t.version})`:``,C=t.requiredBy&&t.requiredBy.length>0?` — needed by ${t.requiredBy.join(`, `)}`:``;ge.log(` ${n} ${t.name}${S}${C}`)}}if(C.length>0){ge.log(`
929
929
  Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`ℹ`;ge.log(` ${n} ${t.typePackage} describes ${t.declared}, installed ${t.pkgConfig} is ${t.installed}`)}C.some(t=>t.relation===`ahead`)&&ge.log(`
@@ -944,7 +944,7 @@ No install command available for your package manager. Install manually.`),proce
944
944
  bunx @gjsify/cli@latest showcase <name>
945
945
  deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,gR={command:`showcase [name]`,description:`List or run curated gjsify showcase applications.`,builder:t=>t.positional(`name`,{description:`Showcase name to run (omit to list all)`,type:`string`}).option(`json`,{description:`Output as JSON`,type:`boolean`,default:!1}).option(`list`,{description:`List available showcases`,type:`boolean`,default:!1}).option(`runtime`,{type:`string`,choices:F_,defaultDescription:`gjs when gjs is installed, else the host runtime`,description:"Runtime to run the showcase on: gjs | node | bun | deno (default: gjs when installed, else the host runtime). node/bun/deno run its `--app node` bundle."}),handler:async t=>{if(!t.name||t.list){let n=discoverShowcases();if(t.json){ge.log(JSON.stringify(n,null,2));return}if(n.length===0){ge.log("No showcases found. The CLI ships a curated list in `showcases.json`; if it is missing the CLI install is incomplete.");return}let S=new Map;for(let t of n){let n=S.get(t.category)??[];n.push(t),S.set(t.category,n)}ge.log(`Available gjsify showcases:
946
946
  `);for(let[t,n]of S){ge.log(` ${t.toUpperCase()}:`);let S=Math.max(...n.map(t=>t.name.length));for(let t of n){let n=` `.repeat(S-t.name.length+2),C=t.description?`${n}${t.description}`:``;ge.log(` ${t.name}${C}`)}ge.log(``)}ge.log(`Run a showcase: gjsify showcase <name>`);return}let n=findShowcase(t.name);if(!n)return ge.error(`Unknown showcase: "${t.name}"`),ge.error(`Run "gjsify showcase" to list available showcases.`),process.exit(1);let S=t.runtime??defaultExampleRuntime();if(!isExampleRuntime(S))return ge.error(`Unknown --runtime "${S}" (expected: ${F_.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(S)){let t=runMinimalChecks().filter(t=>!t.found&&t.severity===`required`);if(t.length>0){ge.error(`Missing system dependencies:
947
- `);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(sK(),oK));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=wn(fileURLToPath(import.meta.url)),n=[xn(t,`..`,`dist-templates`),xn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,xn(wn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=xn(t,S),N=xn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=vR[S]??``;try{let t=JSON.parse(readFileSync(N,`utf-8`));typeof t.description==`string`&&t.description.trim()&&(F=t.description)}catch{}n.push({name:S,description:F,path:C})}return n.sort((t,n)=>t.name.localeCompare(n.name)),n}function findTemplate(t){return discoverTemplates().find(n=>n.name===t)}var vR,yR=__esmMin(()=>{Fd(),Nl(),jn(),Hn(),vR={"gtk-minimal":`Minimal GTK4 app — Gtk.ApplicationWindow + Gtk.Label, no Adwaita (Blueprint UI).`,cli:`Command-line tool using yargs (Node.js + GJS).`,"adw-canvas2d":`Adwaita app with HTML Canvas 2D rendering (Blueprint UI).`,"adw-webgl":`Adwaita app with WebGL + three.js (Blueprint UI).`,"adw-game":`Adwaita game shell using Excalibur.js, WebGL → Canvas2D fallback.`,"web-server-hono":`HTTP server using Hono (Web-standard fetch-style API).`,"web-server-express":`HTTP server using Express (familiar Node.js stack).`}});function installCommandLine(t){return[t,...xR[t]].join(` `)}function runScriptCommand(t){return SR[t]}function packageManagersForRuntime(t){return CR[t]}function hostRuntime(){let t=globalThis;return t.Bun===void 0?t.Deno===void 0?t.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(t,n){if(n)return t.find(t=>packageManagersForRuntime(t)?.includes(n));let S=hostRuntime();return t.includes(S)?S:t[0]}function startScriptFor(t){return t===`gjs`?`start`:`start:${t}`}var bR,xR,SR,CR,wR,TR=__esmMin(()=>{bR=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],xR={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},SR={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},CR={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},wR={gjs:`GNOME JavaScript — no Node.js needed at runtime.`,node:`Node.js — gi:// via the @gjsify/node-gi bridge.`,bun:`Bun — runs the same --app node bundle.`,deno:`Deno — runs the same --app node bundle.`}});function selectRuntime(t){let{flag:n,offered:S,manager:C,interactive:N}=t;if(n!==void 0)return S.length>0&&!S.includes(n)?{kind:`error`,message:`this template does not run on "${n}". Declared runtimes: ${S.join(`, `)}.`}:{kind:`value`,value:n};if(S.length===1)return{kind:`value`,value:S[0]};if(S.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let F=defaultRuntimeFor(S,C);return F===void 0?{kind:`error`,message:`no runtime this template declares installs with "${C}". Declared runtimes: ${S.join(`, `)}.`}:C===void 0?N?{kind:`prompt`,choices:S,initial:F}:{kind:`auto`,value:F,notice:`--runtime not given, using "${F}". Runs on: ${S.join(`, `)}.`}:{kind:`auto`,value:F,notice:`Setting up for ${F} — the runtime ${C} installs for.`}}function selectPackageManager(t){let{flag:n,runtime:S,install:C,interactive:N}=t,F=packageManagersForRuntime(S);return F===void 0||F.length===0?{kind:`error`,message:`no package manager known for runtime "${S}".`}:n===void 0?F.length===1?{kind:`auto`,value:F[0],notice:`Using ${F[0]} — the only package manager that installs for ${S}.`}:N?{kind:`prompt`,choices:F,initial:F[0]}:C?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${S}: ${F.join(`, `)}.`}:{kind:`auto`,value:F[0],notice:`--package-manager not given, using "${F[0]}" for ${S}.`}:F.includes(n)?{kind:`value`,value:n}:{kind:`error`,message:`"${n}" cannot install a project you intend to run on ${S}. Package managers for ${S}: ${F.join(`, `)}.`}}var ER=__esmMin(()=>{TR()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=vn(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[DR,n],[OR,applicationIdFor(n)]],C=new Set([`node_modules`,`dist`,`lib`]),N=[t];for(;N.length>0;){let t=N.pop();for(let n of readdirSync(t,{withFileTypes:!0})){let F=xn(t,n.name);if(n.isDirectory()){C.has(n.name)||N.push(F);continue}if(!n.isFile())continue;let I=n.name.lastIndexOf(`.`),H=I>=0?n.name.slice(I):``;if(!kR.has(H))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,n]of S)q=q.replaceAll(t,n);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}}function templateManifest(t){try{return JSON.parse(readFileSync(xn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var DR,OR,kR,AR=__esmMin(()=>{_e(),D_(),Fd(),jn(),yR(),TR(),ER(),DR=`new-gjsify-app`,OR=`org.gjsify.example`,kR=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`])});function isCancelled(t){return t instanceof Error&&t.message===MR}function render(t,n,S){S||tn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${jR.cyan}❯${jR.reset}`:` `,F=S===n?`${jR.bold}${jR.green}${C.label}${jR.reset}`:C.label,I=C.description?` ${jR.dim}${C.description}${jR.reset}`:``;tn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;tn.write(`${jR.bold}${t}${jR.reset} ${jR.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${jR.reset}\n`),render(n,F,!0),emitKeypressEvents(nn),nn.isTTY&&nn.setRawMode(!0),nn.resume();let cleanup=()=>{nn.removeListener(`keypress`,onKeypress),nn.isTTY&&nn.setRawMode(!1),nn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),tn.write(`
947
+ `);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(dK(),uK));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=wn(fileURLToPath(import.meta.url)),n=[xn(t,`..`,`dist-templates`),xn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,xn(wn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=xn(t,S),N=xn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=vR[S]??``;try{let t=JSON.parse(readFileSync(N,`utf-8`));typeof t.description==`string`&&t.description.trim()&&(F=t.description)}catch{}n.push({name:S,description:F,path:C})}return n.sort((t,n)=>t.name.localeCompare(n.name)),n}function findTemplate(t){return discoverTemplates().find(n=>n.name===t)}var vR,yR=__esmMin(()=>{Fd(),Nl(),jn(),Hn(),vR={"gtk-minimal":`Minimal GTK4 app — Gtk.ApplicationWindow + Gtk.Label, no Adwaita (Blueprint UI).`,cli:`Command-line tool using yargs (Node.js + GJS).`,"adw-canvas2d":`Adwaita app with HTML Canvas 2D rendering (Blueprint UI).`,"adw-webgl":`Adwaita app with WebGL + three.js (Blueprint UI).`,"adw-game":`Adwaita game shell using Excalibur.js, WebGL → Canvas2D fallback.`,"web-server-hono":`HTTP server using Hono (Web-standard fetch-style API).`,"web-server-express":`HTTP server using Express (familiar Node.js stack).`}});function installCommandLine(t){return[t,...xR[t]].join(` `)}function runScriptCommand(t){return SR[t]}function packageManagersForRuntime(t){return CR[t]}function hostRuntime(){let t=globalThis;return t.Bun===void 0?t.Deno===void 0?t.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(t,n){if(n)return t.find(t=>packageManagersForRuntime(t)?.includes(n));let S=hostRuntime();return t.includes(S)?S:t[0]}function startScriptFor(t){return t===`gjs`?`start`:`start:${t}`}var bR,xR,SR,CR,wR,TR=__esmMin(()=>{bR=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],xR={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},SR={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},CR={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},wR={gjs:`GNOME JavaScript — no Node.js needed at runtime.`,node:`Node.js — gi:// via the @gjsify/node-gi bridge.`,bun:`Bun — runs the same --app node bundle.`,deno:`Deno — runs the same --app node bundle.`}});function selectRuntime(t){let{flag:n,offered:S,manager:C,interactive:N}=t;if(n!==void 0)return S.length>0&&!S.includes(n)?{kind:`error`,message:`this template does not run on "${n}". Declared runtimes: ${S.join(`, `)}.`}:{kind:`value`,value:n};if(S.length===1)return{kind:`value`,value:S[0]};if(S.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let F=defaultRuntimeFor(S,C);return F===void 0?{kind:`error`,message:`no runtime this template declares installs with "${C}". Declared runtimes: ${S.join(`, `)}.`}:C===void 0?N?{kind:`prompt`,choices:S,initial:F}:{kind:`auto`,value:F,notice:`--runtime not given, using "${F}". Runs on: ${S.join(`, `)}.`}:{kind:`auto`,value:F,notice:`Setting up for ${F} — the runtime ${C} installs for.`}}function selectPackageManager(t){let{flag:n,runtime:S,install:C,interactive:N}=t,F=packageManagersForRuntime(S);return F===void 0||F.length===0?{kind:`error`,message:`no package manager known for runtime "${S}".`}:n===void 0?F.length===1?{kind:`auto`,value:F[0],notice:`Using ${F[0]} — the only package manager that installs for ${S}.`}:N?{kind:`prompt`,choices:F,initial:F[0]}:C?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${S}: ${F.join(`, `)}.`}:{kind:`auto`,value:F[0],notice:`--package-manager not given, using "${F[0]}" for ${S}.`}:F.includes(n)?{kind:`value`,value:n}:{kind:`error`,message:`"${n}" cannot install a project you intend to run on ${S}. Package managers for ${S}: ${F.join(`, `)}.`}}var ER=__esmMin(()=>{TR()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=vn(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[DR,n],[OR,applicationIdFor(n)]],C=new Set([`node_modules`,`dist`,`lib`]),N=[t];for(;N.length>0;){let t=N.pop();for(let n of readdirSync(t,{withFileTypes:!0})){let F=xn(t,n.name);if(n.isDirectory()){C.has(n.name)||N.push(F);continue}if(!n.isFile())continue;let I=n.name.lastIndexOf(`.`),H=I>=0?n.name.slice(I):``;if(!kR.has(H))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,n]of S)q=q.replaceAll(t,n);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}}function templateManifest(t){try{return JSON.parse(readFileSync(xn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var DR,OR,kR,AR=__esmMin(()=>{_e(),D_(),Fd(),jn(),yR(),TR(),ER(),DR=`new-gjsify-app`,OR=`org.gjsify.example`,kR=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`])});function isCancelled(t){return t instanceof Error&&t.message===MR}function render(t,n,S){S||tn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${jR.cyan}❯${jR.reset}`:` `,F=S===n?`${jR.bold}${jR.green}${C.label}${jR.reset}`:C.label,I=C.description?` ${jR.dim}${C.description}${jR.reset}`:``;tn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;tn.write(`${jR.bold}${t}${jR.reset} ${jR.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${jR.reset}\n`),render(n,F,!0),emitKeypressEvents(nn),nn.isTTY&&nn.setRawMode(!0),nn.resume();let cleanup=()=>{nn.removeListener(`keypress`,onKeypress),nn.isTTY&&nn.setRawMode(!1),nn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),tn.write(`
948
948
  `),N(Error(MR));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};nn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:wR[t]??``})),t.indexOf(n))}function promptPackageManager(t,n){return promptChoice(`Select a package manager`,t.map(t=>({value:t,label:t,description:``})),t.indexOf(n))}async function settle(t,n){switch(t.kind){case`value`:return t.value;case`auto`:return ge.error(t.notice),t.value;case`prompt`:try{return await n(t.choices,t.initial)}catch(t){if(!isCancelled(t))throw t;ge.error(`Cancelled.`);return}case`error`:ge.error(`Error: ${t.message}`);return}}async function promptSetup(t){let{offered:n,install:S,interactive:C}=t,N=await settle(selectRuntime({flag:t.runtime,offered:n,manager:t.packageManager,interactive:C}),(t,n)=>promptRuntime(t,n));if(N===void 0)return;let F=await settle(selectPackageManager({flag:t.packageManager,runtime:N,install:S,interactive:C}),(t,n)=>promptPackageManager(t,n));if(F!==void 0)return{runtime:N,packageManager:F}}var jR,MR,NR=__esmMin(()=>{_e(),rn(),Dd(),TR(),ER(),jR={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},MR=`Cancelled by user`}),PR,FR=__esmMin(()=>{_e(),AR(),NR(),PR={command:`create [project-name]`,description:`Scaffold a new Gjsify project in a new directory.`,builder:t=>{let n=discoverTemplates(),S=n.map(t=>t.name),C=[...new Set(n.flatMap(t=>supportedRuntimes(t)))];return t.positional(`project-name`,{describe:`Name of the project directory to create`,type:`string`,default:`my-gjs-app`}).option(`template`,{alias:`t`,describe:`Template to scaffold from`,type:`string`,choices:S.length>0?S:void 0}).option(`runtime`,{alias:`r`,describe:`Runtime to set the project up for. Decides which package managers are offered and which start script the next steps name.`,type:`string`,choices:C.length>0?C:void 0}).option(`force`,{alias:`f`,describe:`Scaffold into a non-empty directory`,type:`boolean`,default:!1}).option(`install`,{describe:`Install dependencies after scaffolding`,type:`boolean`,default:!1}).option(`package-manager`,{alias:`p`,describe:"Package manager to install with, and to name in the printed next steps. Must be one the chosen runtime can install for. `gjsify` is the only one that works on a host with no Node.js.",type:`string`,choices:bR})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Tn(t,$(t));return vn(wn(t),n)}var IR,LR,RR=__esmMin(()=>{_e(),D_(),vd(),jn(),Su(),IR=promisify(execFile),LR={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.xml),S=t.target?vn(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?vn(t.sourcedir):wn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(wn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await IR(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=xn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var zR=__esmMin(()=>{D_(),jn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=xn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(xn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Tn(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:xn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=xn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${xn(n,t.filename)}`,xn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await BR(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Tn(S.replace(/\.in$/,``)):`${t}.xml`}}var BR,VR,HR=__esmMin(()=>{_e(),D_(),vd(),Ag(),jn(),Su(),zR(),BR=promisify(execFile),VR={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.poDir),S=vn(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?vn(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),UR,WR,GR=__esmMin(()=>{_e(),D_(),vd(),jn(),Su(),UR=promisify(execFile),WR={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.schemadir),S=t.targetdir?vn(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await UR(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=vn(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var KR,qR=__esmMin(()=>{Fd(),jn(),KR=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`50`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var JR,YR,XR=__esmMin(()=>{JR=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],YR=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of QR){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?YR:JR),cleanup:W??[]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${ZR}. Move ${t.length>1?`them`:`it`} to ${S} — both spellings resolve until then, and \`gjsify.ship.flatpak\` wins where both are set. The app METADATA in \`gjsify.flatpak\` (name, summary, developer, categories, licence) is NOT deprecated: both blocks describe the same application and either may carry it (ADR 0024 § 8).`}var ZR,QR,$R=__esmMin(()=>{XR(),ZR=`1.0.0`,QR=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return ez}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:`${t.command}${execFieldCode(N)}`,APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`),t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}return F.push(`</component>`),F.join(`
949
949
  `)+`
950
950
  `}function renderDescriptionBlocks(t,n){let S=typeof t==`string`?stringToBlocks(t):t,C=[];for(let t of S)if(`p`in t)pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<p>${escapeXml(t.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<ul>`);for(let S of t.ul)typeof S==`string`?C.push(`${n} <li>${escapeXml(S)}</li>`):(pushTranslatorHint(C,S.translatorHint,`${n} `),C.push(`${n} <li>${escapeXml(S.item)}</li>`));C.push(`${n}</ul>`)}return C}function stringToBlocks(t){return t.trim().split(/\n\n+/).map(t=>({p:t.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(t,n,S){n&&t.push(`${S}<!-- TRANSLATORS: ${n} -->`)}function normaliseContentRating(t){return t===void 0?{type:`oars-1.1`}:typeof t==`string`?{type:t}:{type:t.type??`oars-1.1`,attributes:t.attributes}}function substitute(t,n){let S=t;for(let[t,C]of Object.entries(n))S=S.split(`{{${t}}}`).join(C);return S}function escapeXml(t){return t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}var ez,tz=__esmMin(()=>{ez=`[Desktop Entry]
@@ -1177,7 +1177,7 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
1177
1177
  reported, so the first symptom can be an unrelated-looking bundler error
1178
1178
  (\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
1179
1179
  install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=xn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(xn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var KH,qH,JH,YH,XH=__esmMin(()=>{_e(),Fd(),jn(),Hn(),D_(),GH(),IP(),nF(),sF(),yI(),ML(),LI(),rL(),kI(),P_(),RP(),hz(),IL(),_L(),yL(),FI(),SL(),KH=process.platform===`win32`?`junction`:void 0,qH=18e5,JH={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:qH}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},YH=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var ZH,QH,$H=__esmMin(()=>{_e(),Fd(),jn(),SL(),ZH={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually depends on are ever linked.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=vn(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} depends on${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Sn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${bL} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${bL} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},QH={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${bL}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${bL} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
1180
- `)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${bL} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(sK(),oK));await Y([`install`])}}});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of eU){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of eU){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},tU).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
1180
+ `)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${bL} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(dK(),uK));await Y([`install`])}}});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of eU){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of eU){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},tU).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
1181
1181
  `)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),nU).unref?.())},oe=setInterval(()=>{let t=Date.now()-ae;t<3e5||ne.size===0||(ge.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(t/6e4)}min — in-flight: ${describeInflight()}`),t>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(t/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);oe.unref?.();let settle=()=>{clearInterval(oe),re?F(re):t()},pump=()=>{if(!re){for(;Z<C;){let t=[...W.entries()].filter(([,t])=>[...t].every(t=>X.has(t))).map(([t])=>t);if(t.length===0)break;let C=t.sort()[0];W.delete(C),Z++,ne.set(C,Date.now()),te&&ge.error(`[gjsify foreach] start ${C} (${X.size}/${Y} done, ${Z} in flight)`),runOne(q.get(C),n,S,!0,N,I,H).then(()=>{X.add(C)}).catch(t=>{failFast(t instanceof Error?t:Error(String(t)))}).finally(()=>{Z--,ne.delete(C),ae=Date.now(),re?Z===0&&settle():W.size===0&&Z===0?settle():pump()})}W.size>0&&Z===0&&!re&&(clearInterval(oe),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(t,n,S,C,N,F,I){if(F){N&&ge.error(`[${t.name}] $ ${n} ${S.join(` `)}`),await spawnPrefixed(n,S,t.location,C?`[${t.name}] `:null);return}if(I&&I.tryRestore(t))return;let H=I?.snapshotOutputs(t),W=detectPackageManager(),q=W===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${W} ${q.join(` `)}`),await spawnPrefixed(W,q,t.location,C?`[${t.name}] `:null),I&&H&&I.storeAfterSuccess(t,H)}async function spawnPrefixed(t,n,S,C){let N=null,F=[];try{let I=await spawnToCompletion(t,n,{completion:`exit`,cwd:S,stdio:C?`pipe`:`inherit`,color:!0,onSpawn:t=>{N=t,eU.add(t);let n=!process.stdout.isTTY;C&&t.stdout&&t.stderr&&(F.push(prefixLines(t.stdout,process.stdout,C,n)),F.push(prefixLines(t.stderr,process.stderr,C,n)))}});for(let t of F)t();if(I.code!==0)throw Error(`${t} ${n.join(` `)} exited with code ${I.code}`)}finally{N&&eU.delete(N)}}var eU,tU,nU,rU,iU=__esmMin(()=>{_e(),P_(),JI(),Ag(),IP(),RP(),dH(),YL(),dI(),$L(),nR(),eU=new Set,tU=5e3,nU=15e3,rU={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[xn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(xn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var aU=__esmMin(()=>{jn(),P_(),RP()});async function packWorkspace(t,n={}){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
1182
1182
  `,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(xn(t,n)));let C=statSync(xn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?vn(n.destination):t,ce=xn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(xn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=xn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
1183
1183
  `)+`
@@ -1207,7 +1207,7 @@ Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCach
1207
1207
  `)[0].slice(0,200)}var QU,$U=__esmMin(()=>{_e(),D_(),Fd(),jn(),Zm(),IP(),YU(),mR(),RU(),ZU(),QU={command:`trust [packages..]`,description:"Configure npm Trusted Publishers (OIDC/GitHub Actions) for publishable workspace packages so release.yml can publish without a token. Native — no `npm` needed. Incremental: skips already-configured packages.",builder:t=>t.positional(`packages`,{description:`Optional package-name globs to limit the sweep (default: all publishable workspaces).`,type:`string`,array:!0}).option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${Wm}).`,type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as `npm-otp`. Prompted on demand if omitted.",type:`string`}).option(`dry-run`,{description:`List what would be configured without writing anything.`,type:`boolean`,default:!1}).option(`force`,{description:`Re-POST the config even for packages already trusted for this repo+workflow.`,type:`boolean`,default:!1}).option(`list`,{description:`Only report each package’s current trust state; configure nothing.`,type:`boolean`,default:!1}).option(`private`,{description:`Include private workspaces (default false — private packages are not publishable).`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await loadNpmrc(n);if(!hasAnyCredential(S))return ge.error("gjsify trust: no npm token configured. Run `gjsify login` first."),process.exit(1);let C=t.registry??process.env.npm_config_registry??S.registry??Wm;if(t[`dry-run`]!==!0){let t;try{t=await whoami(C,S)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`gjsify trust: npm auth check failed (${n}).\nYour ~/.npmrc token is dead or revoked — refresh it with \`npm login\`, then re-run.
1208
1208
  (\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=xn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??Wm,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);process.exit(1)}}}}});function resolveRepoRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,encoding:`utf8`});if(S.status===0){let t=S.stdout.trim();if(t&&existsSync(t))return t}return t}function assertEveryPatternMatches(t,n){let S=n.filter(n=>{try{return discoverWorkspaces(t,{patterns:[n]}).length===0}catch{return!0}});if(S.length===0)return;let C=[`gjsify onboard: --packages matched no package directory (${S.length} of ${n.length} pattern(s)) under ${t}:`];for(let t of S)C.push(` ${JSON.stringify(t)}`);throw C.push(" Patterns are DIRECTORY globs resolved against the repo root, and only `*` is supported",` (one path segment). A matched directory needs a package.json with a "name".`),Error(C.join(`
1209
1209
  `))}function collectOnboardPackages(t,n,S={}){let C=[],N=[],F=new Set,take=(t,n,S)=>{let I=0;for(let t of n)!t.name||F.has(t.name)||(F.add(t.name),N.push(t),I++);C.push({kind:t,patterns:S,count:I})};if(existsSync(xn(t,`package.json`)))try{take(`workspaces`,discoverWorkspaces(t,{includeRoot:!0}))}catch{}return S.patterns&&S.patterns.length>0&&take(`packages`,discoverWorkspaces(t,{patterns:[...S.patterns]}),S.patterns),take(`scanned-dirs`,mergePublishables([],n)),{packages:N,sources:C}}function describeSources(t){return t.filter(t=>t.count>0).map(t=>t.patterns?`${t.kind}(${t.patterns.join(`,`)})=${t.count}`:`${t.kind}=${t.count}`).join(` + `)}function declaredRepository(t){let n=t.manifest.repository,S=typeof n==`string`?n:n?.url;return typeof S!=`string`||S.length===0?null:parseRepoFromGitRemote(S)}function assertRepositoryAgreement(t,n){let S=n.toLowerCase(),C=t.map(t=>({ws:t,declared:declaredRepository(t)})).filter(t=>t.declared!==null&&t.declared.toLowerCase()!==S);if(C.length===0)return;let N=new Map;for(let{ws:t,declared:n}of C){let S=N.get(n)??[];S.push(t.name),N.set(n,S)}let F=[`gjsify onboard: ${C.length} selected package(s) declare a DIFFERENT repository than ${n}:`];for(let[t,n]of N){let S=n.slice(0,5).join(`, `),C=n.length>5?`, … (+${n.length-5} more)`:``;F.push(` ${t}: ${n.length} package(s) — ${S}${C}`)}throw F.push(` A Trusted Publisher scoped to the wrong repository points that package's OIDC exchange`,` at a workflow that does not publish it, which breaks the release this sweep protects.`,` Either exclude them (--exclude), select only what belongs here (--include), or point`,` --repository at the repo that actually publishes them.`),Error(F.join(`
1210
- `))}var eW=__esmMin(()=>{Fd(),D_(),IP(),jn(),YU(),ZU(),RP()});function describeRateLimitHeaders(t){if(!t)return`no headers captured`;let n=[];return t.forEach((t,S)=>{(/^retry-after$/i.test(S)||/ratelimit/i.test(S))&&n.push(`${S}: ${t}`)}),n.length>0?n.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(t){let n=t?.get(`retry-after`);if(!n)return null;let S=Number.parseInt(n.trim(),10);return!Number.isFinite(S)||S<0?null:S*1e3}async function packumentExists(t,n){let S=t.endsWith(`/`)?t.slice(0,-1):t;try{let t=await fetch(`${S}/${n.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return t.status===404?!1:t.ok?!0:null}catch{return null}}function actionForState(t){switch(t){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(t){return new Promise(n=>setTimeout(n,t))}async function requestWaitingOutRateLimit(t,n,S,C,N={}){let F=N.sleep??defaultSleep,I=N.maxRateLimitWaitMs??3e5,H=N.rateLimitBaseDelayMs??2e3,W=N.gate;W&&await W.wait();let q=await t(n,S,C),Y=0;for(let X=0;q.status===429&&Y<I;X++){let Z=retryAfterMs(q.headers),te=Math.min(Z??H*2**X,tW),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??Wm,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var tW,RateLimitGate,nW=__esmMin(()=>{Zm(),ZU(),tW=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`error`:return`HTTP ${t.status} ${t.statusText}`;default:return`unknown`}}var rW,iW,aW=__esmMin(()=>{_e(),D_(),Zm(),IP(),mR(),RU(),OU(),BU(),$U(),GU(),nR(),P_(),eW(),ZU(),nW(),rW=4,iW={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${Wm}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:rW}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??Wm,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?fn:un}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,sW,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${sW}`,updateWith:`flatpak update ${t}`,managedElsewhere:!0}}return isInside$1(N,C.resolve(t.xdgPrefix),S)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${t.xdgPrefix}`,managedElsewhere:!1}:S!==`win32`&&oW.some(t=>isInside$1(N,t,S))?{kind:`system-package`,evidence:`running from the system prefix ${N}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:N.split(C.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${N}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${N}, which matches no known install layout`,managedElsewhere:!1}}var oW,sW,cW=__esmMin(()=>{jn(),oW=[`/usr/`,`/opt/`,`/snap/`],sW=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?fn:un,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${lW}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return wn(vn(t));let n=fileURLToPath(import.meta.url),S=wn(vn(n));for(let t=0;t<8&&S!==wn(S);t++){if(existsSync(xn(S,`package.json`)))return S;S=wn(S)}return wn(vn(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===lW&&typeof n.version==`string`?n.version:null}let n=wn(vn(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==wn(n);t++){let t=xn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===lW&&typeof n.version==`string`)return n.version}n=wn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var lW,uW,dW,fW=__esmMin(()=>{_e(),Fd(),jn(),Hn(),Zm(),ML(),cW(),IL(),BL(),_L(),yL(),lW=`@gjsify/cli`,uW={command:`self-update`,description:`Update the installed ${lW} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=xn(xn(n.prefix,`node_modules`,lW),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${lW}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`),ge.log(`Fetching dist-tags for ${lW}@${t.tag} ...`);let I;try{I=await fetchPackument(lW)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let H=resolveTag(I,t.tag);if(!H)return ge.error(`Unknown dist-tag '${t.tag}' on ${lW}. Known tags: ${Object.keys(I[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${t.tag}: v${H}`);let W=N&&!hasBundlerEngineInstalled(n.prefix),q=W&&!t.skipDeps&&!t.check;if(C===H&&!t.force&&!q){ge.log(`Already up to date (v${H}).`),W&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(q&&C===H&&!t.force&&ge.log(`@gjsify/cli is at v${H} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${H}`:`Install required: → v${H}`),process.exit(1);let Y=!t.skipDeps,X=Y?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${lW}@${H}${X} ...`);let Z=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${lW}@${H}`],verbose:!1,skipDeps:!Y,progress:Z})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Y&&await installGjsEnginePackages(n.prefix,H,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let te=linkGlobalBins([lW],n);if(te.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of te)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:dW,binDir:n.binDir,resolvedBin:resolveBinOnPath(dW,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:H});if(!t.ok)return ge.error(`\nInstalled ${lW} v${H} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${lW} to v${H}.`),Y?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},dW=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
1210
+ `))}var eW=__esmMin(()=>{Fd(),D_(),IP(),jn(),YU(),ZU(),RP()});function describeRateLimitHeaders(t){if(!t)return`no headers captured`;let n=[];return t.forEach((t,S)=>{(/^retry-after$/i.test(S)||/ratelimit/i.test(S))&&n.push(`${S}: ${t}`)}),n.length>0?n.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(t){let n=t?.get(`retry-after`);if(!n)return null;let S=Number.parseInt(n.trim(),10);return!Number.isFinite(S)||S<0?null:S*1e3}async function packumentExists(t,n){let S=t.endsWith(`/`)?t.slice(0,-1):t;try{let t=await fetch(`${S}/${n.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return t.status===404?!1:t.ok?!0:null}catch{return null}}function actionForState(t){switch(t){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(t){return new Promise(n=>setTimeout(n,t))}async function requestWaitingOutRateLimit(t,n,S,C,N={}){let F=N.sleep??defaultSleep,I=N.maxRateLimitWaitMs??3e5,H=N.rateLimitBaseDelayMs??2e3,W=N.gate;W&&await W.wait();let q=await t(n,S,C),Y=0;for(let X=0;q.status===429&&Y<I;X++){let Z=retryAfterMs(q.headers),te=Math.min(Z??H*2**X,tW),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??Wm,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var tW,RateLimitGate,nW=__esmMin(()=>{Zm(),ZU(),tW=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`error`:return`HTTP ${t.status} ${t.statusText}`;default:return`unknown`}}var rW,iW,aW=__esmMin(()=>{_e(),D_(),Zm(),IP(),mR(),RU(),OU(),BU(),$U(),GU(),nR(),P_(),eW(),ZU(),nW(),rW=4,iW={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${Wm}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:rW}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??Wm,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?fn:un}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,sW,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${sW}`,updateWith:`flatpak update ${t}`,managedElsewhere:!0}}return isInside$1(N,C.resolve(t.xdgPrefix),S)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${t.xdgPrefix}`,managedElsewhere:!1}:S!==`win32`&&oW.some(t=>isInside$1(N,t,S))?{kind:`system-package`,evidence:`running from the system prefix ${N}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:N.split(C.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${N}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${N}, which matches no known install layout`,managedElsewhere:!1}}var oW,sW,cW=__esmMin(()=>{jn(),oW=[`/usr/`,`/opt/`,`/snap/`],sW=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?fn:un,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${lW}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function isNextChannelVersion(t){return t?(parse(t)?.prerelease??[]).some(t=>t===`next`):!1}function nextChannelNotice(t){return t.requestedTag!==void 0||!isNextChannelVersion(t.currentVersion)?null:`Note: v${t.currentVersion} is a \`next\` prerelease; updating without --tag moves you to \`${uW}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return wn(vn(t));let n=fileURLToPath(import.meta.url),S=wn(vn(n));for(let t=0;t<8&&S!==wn(S);t++){if(existsSync(xn(S,`package.json`)))return S;S=wn(S)}return wn(vn(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===lW&&typeof n.version==`string`?n.version:null}let n=wn(vn(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==wn(n);t++){let t=xn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===lW&&typeof n.version==`string`)return n.version}n=wn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var lW,uW,dW,fW,pW=__esmMin(()=>{_e(),Fd(),jn(),Hn(),Zm(),PP(),ML(),cW(),IL(),BL(),_L(),yL(),lW=`@gjsify/cli`,uW=`latest`,dW={command:`self-update`,description:`Update the installed ${lW} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=xn(xn(n.prefix,`node_modules`,lW),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${lW}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`);let I=t.tag??uW,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${lW}@${I} ...`);let W;try{W=await fetchPackument(lW)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let q=resolveTag(W,I);if(!q)return ge.error(`Unknown dist-tag '${I}' on ${lW}. Known tags: ${Object.keys(W[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${I}: v${q}`);let Y=N&&!hasBundlerEngineInstalled(n.prefix),X=Y&&!t.skipDeps&&!t.check;if(C===q&&!t.force&&!X){ge.log(`Already up to date (v${q}).`),Y&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(X&&C===q&&!t.force&&ge.log(`@gjsify/cli is at v${q} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${q}`:`Install required: → v${q}`),process.exit(1);let Z=!t.skipDeps,te=Z?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${lW}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${lW}@${q}`],verbose:!1,skipDeps:!Z,progress:ne})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Z&&await installGjsEnginePackages(n.prefix,q,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let re=linkGlobalBins([lW],n);if(re.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of re)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:fW,binDir:n.binDir,resolvedBin:resolveBinOnPath(fW,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${lW} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${lW} to v${q}.`),Z?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},fW=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
1211
1211
  /**
1212
1212
  * gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
1213
1213
  * on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
@@ -1732,28 +1732,28 @@ async function main() {
1732
1732
  }
1733
1733
 
1734
1734
  await main();
1735
- `}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var pW,mW,hW=__esmMin(()=>{_e(),Fd(),jn(),pW=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,mW={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:t=>t.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:t=>{let n=vn(process.cwd(),t.output);if(existsSync(n)&&!t.force)return ge.error(`${t.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let S=vn(process.cwd(),`package.json`),C=null;if(existsSync(S))try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{}let N=t.target??C?.name;if(!N)return ge.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let F=t[`bin-name`]??pickDefaultBinName(C,N),I=t[`bootstrap-url`]??pW;writeFileSync(n,loadInstallerTemplate().replace(/const DEFAULT_TARGET = '[^']+';/,`const DEFAULT_TARGET = ${JSON.stringify(N)};`).replace(/const DEFAULT_BIN_NAME = '[^']+';/,`const DEFAULT_BIN_NAME = ${JSON.stringify(F)};`).replace(/const DEFAULT_BOOTSTRAP_URL =\s*'[^']+';/,`const DEFAULT_BOOTSTRAP_URL = ${JSON.stringify(I)};`),{mode:493}),ge.log(`Wrote ${t.output} (target=${N}, bin=${F}).`),ge.log(``),ge.log(`Install one-liner for your README:`),ge.log(` curl -fsSL https://github.com/<you>/<repo>/raw/main/${t.output} -o /tmp/i.mjs \\`),ge.log(` && gjs -m /tmp/i.mjs && rm /tmp/i.mjs`)}}}),gW,_W=__esmMin(()=>{_e(),Fd(),rL(),IL(),_L(),yL(),gW={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:t=>t.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async t=>{let n=t.global?defaultGlobalLayout():null,S=n?n.prefix:process.cwd();if(!existsSync(`${S}/node_modules`)){ge.log(`gjsify prune: nothing installed at ${S}`);return}let C=resolveHostPlatform({env:{...t.os?{npm_config_os:t.os}:{},...t.cpu?{npm_config_cpu:t.cpu}:{},...t.libc?{npm_config_libc:t.libc}:{}}}),N=await acquireInstallLock(S,{}),F;try{F=executePrune(planPrune({prefix:S,target:C}),{dryRun:t.dryRun})}finally{N.release()}if(ge.log(formatPruneReport(F,{dryRun:t.dryRun,verbose:t.verbose})),F.failed.length>0)return process.exit(1)}}});function isInside(t,n){let S=Sn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${On}`)&&!bn(S)}function findBinShimsForPackage(t,n,S){if(!existsSync(t))return[];let C=[],N;try{N=readdirSync(t)}catch{return[]}for(let F of N){let N=xn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
1736
- `).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var vW,yW=__esmMin(()=>{_e(),Fd(),jn(),IL(),vW={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:t=>t.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:t=>{if(!t.global)return ge.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let n=defaultGlobalLayout(),S=t[`dry-run`]??!1,C=t.verbose??!1,N=`gjsify uninstall${S?` (dry-run)`:``} --global`;ge.log(`${N} ← ${n.prefix}`),ge.log(`${` `.repeat(N.length)} bins ← ${n.binDir}`);let F=!1;for(let N of t.packages){let t=specToPackageName(N),I=xn(n.prefix,`node_modules`,t);if(!existsSync(I)){ge.warn(` ✗ ${t} — not installed at ${I}`);continue}let H=findBinShimsForPackage(n.binDir,I,C);if(S){ge.log(` • would remove ${I}`);for(let t of H)ge.log(` • would remove ${t}`)}else{rmSync(I,{recursive:!0,force:!0}),ge.log(` • removed ${I}`);for(let t of H)unlinkSync(t),ge.log(` • removed ${t}`)}F=!0}F||(ge.error(`
1735
+ `}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var mW,hW,gW=__esmMin(()=>{_e(),Fd(),jn(),mW=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,hW={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:t=>t.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:t=>{let n=vn(process.cwd(),t.output);if(existsSync(n)&&!t.force)return ge.error(`${t.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let S=vn(process.cwd(),`package.json`),C=null;if(existsSync(S))try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{}let N=t.target??C?.name;if(!N)return ge.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let F=t[`bin-name`]??pickDefaultBinName(C,N),I=t[`bootstrap-url`]??mW;writeFileSync(n,loadInstallerTemplate().replace(/const DEFAULT_TARGET = '[^']+';/,`const DEFAULT_TARGET = ${JSON.stringify(N)};`).replace(/const DEFAULT_BIN_NAME = '[^']+';/,`const DEFAULT_BIN_NAME = ${JSON.stringify(F)};`).replace(/const DEFAULT_BOOTSTRAP_URL =\s*'[^']+';/,`const DEFAULT_BOOTSTRAP_URL = ${JSON.stringify(I)};`),{mode:493}),ge.log(`Wrote ${t.output} (target=${N}, bin=${F}).`),ge.log(``),ge.log(`Install one-liner for your README:`),ge.log(` curl -fsSL https://github.com/<you>/<repo>/raw/main/${t.output} -o /tmp/i.mjs \\`),ge.log(` && gjs -m /tmp/i.mjs && rm /tmp/i.mjs`)}}}),_W,vW=__esmMin(()=>{_e(),Fd(),rL(),IL(),_L(),yL(),_W={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:t=>t.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async t=>{let n=t.global?defaultGlobalLayout():null,S=n?n.prefix:process.cwd();if(!existsSync(`${S}/node_modules`)){ge.log(`gjsify prune: nothing installed at ${S}`);return}let C=resolveHostPlatform({env:{...t.os?{npm_config_os:t.os}:{},...t.cpu?{npm_config_cpu:t.cpu}:{},...t.libc?{npm_config_libc:t.libc}:{}}}),N=await acquireInstallLock(S,{}),F;try{F=executePrune(planPrune({prefix:S,target:C}),{dryRun:t.dryRun})}finally{N.release()}if(ge.log(formatPruneReport(F,{dryRun:t.dryRun,verbose:t.verbose})),F.failed.length>0)return process.exit(1)}}});function isInside(t,n){let S=Sn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${On}`)&&!bn(S)}function findBinShimsForPackage(t,n,S){if(!existsSync(t))return[];let C=[],N;try{N=readdirSync(t)}catch{return[]}for(let F of N){let N=xn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
1736
+ `).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var yW,bW=__esmMin(()=>{_e(),Fd(),jn(),IL(),yW={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:t=>t.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:t=>{if(!t.global)return ge.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let n=defaultGlobalLayout(),S=t[`dry-run`]??!1,C=t.verbose??!1,N=`gjsify uninstall${S?` (dry-run)`:``} --global`;ge.log(`${N} ← ${n.prefix}`),ge.log(`${` `.repeat(N.length)} bins ← ${n.binDir}`);let F=!1;for(let N of t.packages){let t=specToPackageName(N),I=xn(n.prefix,`node_modules`,t);if(!existsSync(I)){ge.warn(` ✗ ${t} — not installed at ${I}`);continue}let H=findBinShimsForPackage(n.binDir,I,C);if(S){ge.log(` • would remove ${I}`);for(let t of H)ge.log(` • would remove ${t}`)}else{rmSync(I,{recursive:!0,force:!0}),ge.log(` • removed ${I}`);for(let t of H)unlinkSync(t),ge.log(` • removed ${t}`)}F=!0}F||(ge.error(`
1737
1737
  No packages removed.`),process.exit(1))}}});function globToRegexSource(t){let n=``,S=0;for(;S<t.length;){let C=t[S];if(C===`*`&&t[S+1]===`*`&&(S===0||t[S-1]===`/`)){if(S+2===t.length){n+=`.*`,S+=2;continue}if(t[S+2]===`/`){n+=`(?:.*/)?`,S+=3;continue}}if(C===`*`)for(n+=`[^/]*`;t[S+1]===`*`;)S++;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=findClassEnd(t,S);if(C===-1)n+=`\\[`;else{let N=t.slice(S+1,C),F=!1;(N.startsWith(`!`)||N.startsWith(`^`))&&(F=!0,N=N.slice(1)),N=N.replace(/\]/g,`\\]`),n+=`[${F?`^/`:``}${N}]`,S=C}}else C===`\\`&&S+1<t.length?(S++,n+=escapeRegex(t[S])):n+=escapeRegex(C);S++}return n}function findClassEnd(t,n){let S=n+1;for((t[S]===`!`||t[S]===`^`)&&S++,t[S]===`]`&&S++;S<t.length;S++)if(t[S]===`]`)return S;return-1}function escapeRegex(t){return/[.+^${}()|[\]\\*?]/.test(t)?`\\${t}`:t}function parseLine(t){let n=t.replace(/\r$/,``);if(n=n.replace(/(?<!\\)\s+$/,``),n===``||n.startsWith(`#`))return null;let S=!1;n.startsWith(`!`)?(S=!0,n=n.slice(1)):(n.startsWith(`\\!`)||n.startsWith(`\\#`))&&(n=n.slice(1));let C=!1;if(n.endsWith(`/`)&&!n.endsWith(`\\/`)&&(C=!0,n=n.slice(0,-1)),n===``)return null;let N=n.includes(`/`);n.startsWith(`/`)&&(n=n.slice(1));let F=globToRegexSource(n);return{re:RegExp(`^${N?``:`(?:.*/)?`}${F}$`),negate:S,dirOnly:C}}function compileGitignore(t,n){let S=[];for(let n of t){let t=parseLine(n);t&&S.push(t)}let relOf=t=>{let S=Sn(n,t);return S===``||S===`..`||S.startsWith(`..${On}`)||bn(S)?null:On===`/`?S:S.split(On).join(`/`)},decide=(t,n)=>{for(let C=S.length-1;C>=0;C--){let N=S[C];if(!(N.dirOnly&&!n)&&N.re.test(t))return N.negate?`whitelist`:`ignore`}return null};return{base:n,matched(t,n){if(S.length===0)return null;let C=relOf(t);return C===null?null:decide(C,n)},matchedPathOrAnyParents(t,n){if(S.length===0)return null;let C=relOf(t);if(C===null)return null;let N=n;for(;;){let t=decide(C,N);if(t!==null)return t;let n=C.lastIndexOf(`/`);if(n===-1)return null;C=C.slice(0,n),N=!0}}}}function readGitignoreFile(t,n=wn(t)){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}return compileGitignore(S.split(`
1738
- `),n)}var bW=__esmMin(()=>{Fd(),jn()});function externalParserFor(t,n=!1){if(CW.has(t))return null;let S=$(t).slice(1),C=SW[t]??(S?xW[S]:void 0)??null;return C===`svelte`&&!n?null:C}function scanForNativeSkips(t,n=process.cwd(),S={}){let C=[],N=0,F=t.filter(t=>t.startsWith(`!`)).map(t=>t.slice(1)),I=[],H=readGitignoreFile(xn(n,`.prettierignore`));H&&I.push(H),F.length&&I.push(compileGitignore(F,n));let globallyIgnored=(t,n,S)=>I.some(C=>(S?C.matchedPathOrAnyParents(t,n):C.matched(t,n))===`ignore`),W=S.configPath?vn(n,S.configPath):null,q=loadScope(W??discoverConfig(n)),Y=W===null,scopeFor=t=>Y?nearestScope(t,q):q,expandBraces=t=>{let n=/\{([^{}]*)\}/.exec(t);return n?n[1].split(`,`).flatMap(S=>expandBraces(t.slice(0,n.index)+S+t.slice(n.index+n[0].length))):[t]},X=[],Z=new Set;for(let S of t){if(S.startsWith(`!`))continue;let t=vn(n,S);if(/[*?[{]/.test(S)&&!existsSync(t))for(let t of expandBraces(S))X.push(RegExp(`^${globToRegexSource(t.includes(`/`)?t:`**/${t}`)}$`));else Z.add(t)}(X.length||Z.size===0)&&Z.add(vn(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Tn(t),n?.svelte)&&C.push(t))},te=[];for(let t of Z){let n;try{n=statSync(t)}catch{continue}globallyIgnored(t,n.isDirectory(),!0)||(n.isDirectory()?te.push(t):n.isFile()&&record(t,scopeFor(wn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Sn(n,t).split(On).join(`/`);return X.some(t=>t.test(S))},ne=new Set,walk=(t,n,S)=>{if(ne.has(t))return;ne.add(t);let C=readGitignoreFile(xn(t,`.gitignore`)),N=C?[C,...n]:n;Y&&t!==S?.dir&&(S=scopeAt(t)??S);let F;try{F=readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of F){let C=xn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(wW.has(n.name)||n.name===`node_modules`)||globallyIgnored(C,F,!1)||gitIgnored(N,C,F)||(F?walk(C,N,S):matchesGlob(C)&&record(C,S))}},re=te.every(t=>repoRootOf(t)!==null);for(let t of te)walk(t,parentGitignores(t,re?repoRootOf(t):null,re),scopeFor(t));return{skipped:C,total:N}}function gitIgnored(t,n,S){for(let C of t){let t=C.matched(n,S);if(t!==null)return t===`ignore`}return!1}function parentGitignores(t,n,S){if(S&&n===null)return[];let C=[];for(let S=t;S!==n;){let t=wn(S);if(t===S)break;S=t;let n=readGitignoreFile(xn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(xn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=wn(n)){if(existsSync(xn(n,`.git`))||existsSync(xn(n,`.jj`)))return n;if(wn(n)===n)return null}}function configIn(t){for(let n of TW){let S=xn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=vn(t);;n=wn(n)){let t=configIn(n);if(t)return t;if(wn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=wn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(wn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=wn(t),S={};try{S=parseJsonc(readFileSync(t,`utf-8`))}catch{S={}}let C=Array.isArray(S.ignorePatterns)?S.ignorePatterns.filter(t=>typeof t==`string`):[];return{dir:n,ignore:C.length?compileGitignore(C,n):null,svelte:S.svelte!==void 0&&S.svelte!==null&&S.svelte!==!1}}function parseJsonc(t){let pass=(t,n)=>{let S=``;for(let C=0;C<t.length;){if(t[C]===`"`){let n=C+1;for(;n<t.length&&t[n]!==`"`;)n+=t[n]===`\\`?2:1;S+=t.slice(C,n+1),C=n+1;continue}let N=n(t,C);N>0?C+=N:S+=t[C++]}return S},n=pass(t,(t,n)=>{if(t.startsWith(`//`,n)){let S=t.indexOf(`
1739
- `,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,xW,SW,CW,wW,TW,EW=__esmMin(()=>{Fd(),jn(),bW(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),xW={...parsers(`yaml`,[`yml`,`mir`,`reek`,`rviz`,`sublime-syntax`,`syntax`,`yaml`,`yaml-tmlanguage`]),...parsers(`markdown`,[`md`,`livemd`,`markdown`,`mdown`,`mdwn`,`mkd`,`mkdn`,`mkdown`,`ronn`,`scd`,`workbook`]),...parsers(`html`,[`html`,`hta`,`htm`,`inc`,`xht`,`xhtml`]),...parsers(`glimmer`,[`handlebars`,`hbs`]),mdx:`mdx`,vue:`vue`,svelte:`svelte`,mjml:`mjml`},SW={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},CW=new Set([`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`MODULE.bazel.lock`,`bun.lock`,`deno.lock`,`composer.lock`,`Package.resolved`,`Pipfile.lock`,`flake.lock`,`mcmod.info`,`Cargo.lock`,`Gopkg.lock`,`pdm.lock`,`poetry.lock`,`uv.lock`]),wW=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),TW=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=vn(t,S);if(existsSync(N)&&!n){ge.log(`[gjsify format] ${S} exists at ${N} — pass --force to overwrite.`);return}writeFileSync(N,C,`utf-8`),ge.log(`[gjsify format] wrote ${N}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ge.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var DW,OW=__esmMin(()=>{_e(),Fd(),jn(),az(),EW(),DW={command:`format [paths..]`,description:`Format source files via oxfmt (Markdown/YAML/HTML/Vue need the napi build).`,builder:t=>t.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();if(t.init){handleInit({cwd:n,force:t.force??!1});return}let S=t.paths?.length?t.paths:[`.`],C=[];t.check?C.push(`--check`):t.write===!1?C.push(`--list-different`):C.push(`--write`);let N=t.configPath??findOxfmtConfig(n)??void 0;if(N&&C.push(`--config`,vn(N)),C.push(...S),t.check&&await shouldUseNativeOxfmt()){let t=scanForNativeSkips(S,n,{configPath:N});if(t.skipped.length>0){let S=t.skipped.map(t=>` ${Sn(n,t)||t}`).join(`
1740
- `);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),kW,AW=__esmMin(()=>{jn(),az(),kW={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:t=>t.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=[];t.fix&&C.push(`--fix`);let N=t.configPath??findOxlintConfig(n)??void 0;N&&C.push(`--config`,vn(N)),C.push(...S);try{setOxcExitCode(await runOxlint(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),jW,MW=__esmMin(()=>{jn(),az(),jW={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:t=>t.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=t.verbose??!1,N=t.write!==!1;try{let F=[N?`--write`:`--list-different`],I=t.configPath??findOxfmtConfig(n)??void 0;I&&F.push(`--config`,vn(I)),F.push(...S);let H=await runOxfmt(F,{cwd:n,verbose:C}),W=[];N&&W.push(`--fix`);let q=t.configPath??findOxlintConfig(n)??void 0;q&&W.push(`--config`,vn(q)),W.push(...S);let Y=await runOxlint(W,{cwd:n,verbose:C});setOxcExitCode(H||Y)}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}});function createInterface(t,n){return typeof t==`object`&&t&&!(`read`in t&&typeof t.read==`function`)?new Interface(t):new Interface({input:t,output:n})}var Interface,NW=__esmMin(()=>{Dd(),Interface=class extends Interface$1{question(t,n){return new Promise(n=>{super.question(t,n)})}}});function semverGt(t,n){try{return compare(t,n)===1}catch{return!1}}function groupByDependency(t){let n=new Map;for(let S of t){let t=n.get(S.name);t||(t={name:S.name,occurrences:[],declaredRanges:new Set,dominantRange:S.currentRange,highestVersion:S.currentVersion},n.set(S.name,t)),t.occurrences.push(S),t.declaredRanges.add(S.currentRange),S.currentVersion&&(!t.highestVersion||semverGt(S.currentVersion,t.highestVersion))&&(t.highestVersion=S.currentVersion)}for(let t of n.values()){let n=new Map;for(let S of t.occurrences)n.set(S.currentRange,(n.get(S.currentRange)??0)+1);let S=t.occurrences[0].currentRange,C=-1,N=null;for(let[t,F]of n.entries()){let n=parse(t.replace(/^[\^~>=<]+/,``))?.version??null;(F>C||F===C&&n&&N&&semverGt(n,N)||F===C&&t<S)&&(S=t,C=F,N=n)}t.dominantRange=S}return[...n.values()].sort((t,n)=>t.name.localeCompare(n.name))}function isInconsistent(t){return t.declaredRanges.size>1}function findInconsistencies(t){return t.filter(isInconsistent)}var PW=__esmMin(()=>{PP()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`[gjsify upgrade] no package.json at ${S}`);let C=JSON.parse(readFileSync(S,`utf-8`));return{root:t,workspaces:[{name:C.name??`<root>`,location:t,relativeLocation:`.`,version:C.version??`0.0.0`,manifest:C,private:C.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(t,n,S){let C=n?.split(`,`).map(t=>t.trim()).filter(Boolean),N=S?.split(`,`).map(t=>t.trim()).filter(Boolean);return(!C||C.length===0)&&(!N||N.length===0)?t:filterWorkspaces(t,{include:C,exclude:N})}function parseFilterList(t){return t?t.split(`,`).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(t,n){let S=[];for(let C of t)for(let t of collectFromWorkspace(C,n))S.push(t);return S}function collectFromWorkspace(t,n){let S=[],C=t.manifest;for(let N of IW){let F=C[N];if(!(!F||typeof F!=`object`))for(let[C,I]of Object.entries(F)){if(typeof I!=`string`||n.length&&!n.some(t=>C.toLowerCase().includes(t))||I.startsWith(`workspace:`)||I.startsWith(`file:`)||I.startsWith(`link:`)||I.startsWith(`git+`)||I.startsWith(`git:`)||I.startsWith(`http:`)||I.startsWith(`https:`)||I.startsWith(`npm:`)||I.startsWith(`portal:`))continue;let{prefix:F,version:H}=splitRange(I);S.push({workspace:t.name,workspaceLocation:t.location,name:C,field:N,currentRange:I,currentVersion:H,prefix:F})}}return S}function splitRange(t){let n=t.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!n)return{prefix:``,version:null};let S=n[1]??``,C=n[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:S,version:(C?parse(C):null)?.version??null}}function reportInexactRanges(t){let n=t.map(t=>({name:t.name,loose:t.occurrences.filter(t=>t.prefix!==``)})).filter(t=>t.loose.length>0);if(n.length===0)return 0;let S=n.reduce((t,n)=>t+n.loose.length,0);ge.error(`gjsify upgrade --check --exact: FAIL. ${S} declaration(s) across ${n.length} dep(s) carry a range operator:\n`);for(let t of n){let n=new Map;for(let S of t.loose){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${LW.bold}${t.name}${LW.reset}`);for(let[t,S]of n.entries()){let n=S.length>6?`${S.slice(0,6).join(`, `)} … +${S.length-6}`:S.join(`, `);ge.error(` ${t.padEnd(16)} — ${n}`)}}return S}function checkLockfileRangeViolations(t,n){let S=xn(n,`gjsify-lock.json`);if(!existsSync(S))return 0;let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{return 0}if(!C.packages)return 0;let N=new Map;for(let n of t){let t=N.get(n.name)??new Set;for(let S of n.occurrences)t.add(S.currentRange);N.set(n.name,t)}let F=0;for(let[t,n]of Object.entries(C.packages)){if(!n.version)continue;let S=t.split(`node_modules/`);if(S.length!==2)continue;let C=S[1],I=N.get(C);if(!I||I.size===0)continue;let H=!1;for(let t of I)try{if(n.version&&satisfies(n.version,t)){H=!0;break}}catch{}H||(ge.error(` ${C}: lockfile has ${n.version}, but declared ranges are ${[...I].join(`, `)}`),F++)}return F>0&&ge.error(`gjsify upgrade --check: FAIL. ${F} lockfile entr${F===1?`y`:`ies`} violate declared ranges:\n`),F}function runCheckMode(t,n=!1,S=process.cwd()){checkLockfileRangeViolations(t,S);let C=n?reportInexactRanges(t):0,N=findInconsistencies(t);if(N.length===0&&C>0)return ge.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ge.log(`gjsify upgrade --check: OK. ${t.length} dep(s) consistently declared across workspaces`+(n?`, every declaration pinned exactly.`:`.`));return}ge.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let t of N){let n=new Map;for(let S of t.occurrences){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${LW.bold}${t.name}${LW.reset}`);for(let[t,S]of n.entries())ge.error(` ${t.padEnd(16)} — ${S.join(`, `)}`)}ge.error(n?"\nFix: run `gjsify upgrade --align --exact` (offline; aligns each dep to its highest declared version and drops the operator).":"\nFix: run `gjsify upgrade --align` (offline; aligns each dep to its highest declared range)."),process.exit(1)}function alignTargets(t,n){return n?t.filter(t=>isInconsistent(t)||t.occurrences.some(t=>t.prefix!==``)):findInconsistencies(t)}function reportUnrepairable(t){ge.error(`\ngjsify upgrade --align: ${t.length} dep(s) left unrepaired — no version to align on:\n`);for(let n of t)ge.error(` ${LW.bold}${n.name}${LW.reset} ${[...n.declaredRanges].join(`, `)}`);return ge.error("\nThose ranges name no single version. Edit them by hand, or resolve one with `--latest`."),process.exit(1)}function runAlignMode(t,n){let S=n.exact??!1,C=alignTargets(t,S);if(C.length===0){ge.log(`gjsify upgrade --align: nothing to do. ${t.length} dep(s) already consistent`+(S?`, every declaration pinned exactly.`:`.`));return}let N=[],F=[];for(let t of C){if(!t.highestVersion){F.push(t);continue}let n=t.occurrences.find(n=>n.currentRange===t.dominantRange)?.prefix||`^`;N.push({...t,latestVersion:t.highestVersion,diff:`none`,occurrences:t.occurrences.map(t=>({...t,prefix:n}))})}if(N.length>0){ge.log(S?`gjsify upgrade --align --exact: pinning ${N.length} dep(s) to their highest declared version, without a range operator:\n`:`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let t of N){let n=t.occurrences[0]?.prefix??`^`;ge.log(` ${t.name.padEnd(28)} ranges: ${[...t.declaredRanges].join(`, `)} → ${targetRange(n,t.latestVersion,S)}`)}if(n.dryRun)ge.log(`
1741
- [gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return LW.red;case`minor`:return LW.yellow;case`patch`:return LW.green;case`prerelease`:return LW.cyan;default:return``}}function printTable(t){let n=Math.max(...t.map(t=>t.name.length),4),S=Math.max(...t.map(t=>`${t.occurrences.length}`.length+2),3),C=Math.max(...t.map(t=>declaredCellWidth(t)),7),N=Math.max(...t.map(t=>t.latestVersion.length),6),F=String(t.length).length+2,I=` `.repeat(F+2)+LW.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+LW.reset;ge.log(I),ge.log(` `.repeat(F+2)+LW.dim+`─`.repeat(n+S+C+N+16)+LW.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${LW.magenta}⚠ ${LW.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+LW.dim+`${H.occurrences.length}`.padEnd(S)+LW.reset+` `+LW.dim+renderDeclaredCell(H).padEnd(C)+LW.reset+` `+Y+H.latestVersion.padEnd(N)+LW.reset+` `+Y+H.diff+LW.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${LW.magenta}⚠${LW.reset} ${H} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(t){return renderDeclaredCell(t).length}function renderDeclaredCell(t){if(t.declaredRanges.size===1)return[...t.declaredRanges][0];let n=[...t.declaredRanges].sort().join(`, `);return n.length<=32?n:n.slice(0,29)+`…`}function printChangePlan(t,n=!1){for(let S of t)for(let t of S.occurrences)ge.log(` ${t.workspace.padEnd(38)} ${S.name.padEnd(28)} ${t.currentRange.padEnd(12)} → ${targetRange(t.prefix,S.latestVersion,n)}`)}async function promptSelection(t){if(!process.stdin.isTTY)return ge.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let n=createInterface({input:process.stdin,output:process.stdout});try{ge.log(`
1742
- Select upgrades: comma- or space-separated indices, `+LW.bold+`a`+LW.reset+` for all, ranges like `+LW.bold+`1-3`+LW.reset+`, or `+LW.bold+`ENTER`+LW.reset+` to skip:`);let S=(await n.question(`> `)).trim();if(!S)return[];if(S.toLowerCase()===`a`||S.toLowerCase()===`all`)return[...t];let C=new Set;for(let t of S.split(/[\s,]+/).filter(Boolean)){let n=t.match(/^(\d+)-(\d+)$/);if(n){let t=Number(n[1]),S=Number(n[2]);for(let n=Math.min(t,S);n<=Math.max(t,S);n++)C.add(n-1)}else/^\d+$/.test(t)&&C.add(Number(t)-1)}return[...C].filter(n=>n>=0&&n<t.length).map(n=>t[n])}finally{n.close()}}function targetRange(t,n,S){return S?n:`${t}${n}`}function applyToFiles(t,n=!1){let S=new Map;for(let n of t)for(let t of n.occurrences){let C=S.get(t.workspaceLocation)??[];C.push({...n,occurrences:[t]}),S.set(t.workspaceLocation,C)}let C=0;for(let[t,N]of S.entries()){let S=xn(t,`package.json`),F=readFileSync(S,`utf-8`),I=JSON.parse(F),H=!1,W=[];for(let t of N){let S=t.occurrences[0],C=I[S.field];if(!C)continue;let N=targetRange(S.prefix,t.latestVersion,n);C[t.name]!==N&&(C[t.name]=N,H=!0,W.push(t.name))}if(H){let t=detectIndent(F);writeFileSync(S,keepUntouchedLines(F,JSON.stringify(I,null,t)+(F.endsWith(`
1738
+ `),n)}var xW=__esmMin(()=>{Fd(),jn()});function externalParserFor(t,n=!1){if(wW.has(t))return null;let S=$(t).slice(1),C=CW[t]??(S?SW[S]:void 0)??null;return C===`svelte`&&!n?null:C}function scanForNativeSkips(t,n=process.cwd(),S={}){let C=[],N=0,F=t.filter(t=>t.startsWith(`!`)).map(t=>t.slice(1)),I=[],H=readGitignoreFile(xn(n,`.prettierignore`));H&&I.push(H),F.length&&I.push(compileGitignore(F,n));let globallyIgnored=(t,n,S)=>I.some(C=>(S?C.matchedPathOrAnyParents(t,n):C.matched(t,n))===`ignore`),W=S.configPath?vn(n,S.configPath):null,q=loadScope(W??discoverConfig(n)),Y=W===null,scopeFor=t=>Y?nearestScope(t,q):q,expandBraces=t=>{let n=/\{([^{}]*)\}/.exec(t);return n?n[1].split(`,`).flatMap(S=>expandBraces(t.slice(0,n.index)+S+t.slice(n.index+n[0].length))):[t]},X=[],Z=new Set;for(let S of t){if(S.startsWith(`!`))continue;let t=vn(n,S);if(/[*?[{]/.test(S)&&!existsSync(t))for(let t of expandBraces(S))X.push(RegExp(`^${globToRegexSource(t.includes(`/`)?t:`**/${t}`)}$`));else Z.add(t)}(X.length||Z.size===0)&&Z.add(vn(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Tn(t),n?.svelte)&&C.push(t))},te=[];for(let t of Z){let n;try{n=statSync(t)}catch{continue}globallyIgnored(t,n.isDirectory(),!0)||(n.isDirectory()?te.push(t):n.isFile()&&record(t,scopeFor(wn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Sn(n,t).split(On).join(`/`);return X.some(t=>t.test(S))},ne=new Set,walk=(t,n,S)=>{if(ne.has(t))return;ne.add(t);let C=readGitignoreFile(xn(t,`.gitignore`)),N=C?[C,...n]:n;Y&&t!==S?.dir&&(S=scopeAt(t)??S);let F;try{F=readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of F){let C=xn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(TW.has(n.name)||n.name===`node_modules`)||globallyIgnored(C,F,!1)||gitIgnored(N,C,F)||(F?walk(C,N,S):matchesGlob(C)&&record(C,S))}},re=te.every(t=>repoRootOf(t)!==null);for(let t of te)walk(t,parentGitignores(t,re?repoRootOf(t):null,re),scopeFor(t));return{skipped:C,total:N}}function gitIgnored(t,n,S){for(let C of t){let t=C.matched(n,S);if(t!==null)return t===`ignore`}return!1}function parentGitignores(t,n,S){if(S&&n===null)return[];let C=[];for(let S=t;S!==n;){let t=wn(S);if(t===S)break;S=t;let n=readGitignoreFile(xn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(xn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=wn(n)){if(existsSync(xn(n,`.git`))||existsSync(xn(n,`.jj`)))return n;if(wn(n)===n)return null}}function configIn(t){for(let n of EW){let S=xn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=vn(t);;n=wn(n)){let t=configIn(n);if(t)return t;if(wn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=wn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(wn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=wn(t),S={};try{S=parseJsonc(readFileSync(t,`utf-8`))}catch{S={}}let C=Array.isArray(S.ignorePatterns)?S.ignorePatterns.filter(t=>typeof t==`string`):[];return{dir:n,ignore:C.length?compileGitignore(C,n):null,svelte:S.svelte!==void 0&&S.svelte!==null&&S.svelte!==!1}}function parseJsonc(t){let pass=(t,n)=>{let S=``;for(let C=0;C<t.length;){if(t[C]===`"`){let n=C+1;for(;n<t.length&&t[n]!==`"`;)n+=t[n]===`\\`?2:1;S+=t.slice(C,n+1),C=n+1;continue}let N=n(t,C);N>0?C+=N:S+=t[C++]}return S},n=pass(t,(t,n)=>{if(t.startsWith(`//`,n)){let S=t.indexOf(`
1739
+ `,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,SW,CW,wW,TW,EW,DW=__esmMin(()=>{Fd(),jn(),xW(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),SW={...parsers(`yaml`,[`yml`,`mir`,`reek`,`rviz`,`sublime-syntax`,`syntax`,`yaml`,`yaml-tmlanguage`]),...parsers(`markdown`,[`md`,`livemd`,`markdown`,`mdown`,`mdwn`,`mkd`,`mkdn`,`mkdown`,`ronn`,`scd`,`workbook`]),...parsers(`html`,[`html`,`hta`,`htm`,`inc`,`xht`,`xhtml`]),...parsers(`glimmer`,[`handlebars`,`hbs`]),mdx:`mdx`,vue:`vue`,svelte:`svelte`,mjml:`mjml`},CW={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},wW=new Set([`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`MODULE.bazel.lock`,`bun.lock`,`deno.lock`,`composer.lock`,`Package.resolved`,`Pipfile.lock`,`flake.lock`,`mcmod.info`,`Cargo.lock`,`Gopkg.lock`,`pdm.lock`,`poetry.lock`,`uv.lock`]),TW=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),EW=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=vn(t,S);if(existsSync(N)&&!n){ge.log(`[gjsify format] ${S} exists at ${N} — pass --force to overwrite.`);return}writeFileSync(N,C,`utf-8`),ge.log(`[gjsify format] wrote ${N}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ge.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var OW,kW=__esmMin(()=>{_e(),Fd(),jn(),az(),DW(),OW={command:`format [paths..]`,description:`Format source files via oxfmt (Markdown/YAML/HTML/Vue need the napi build).`,builder:t=>t.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();if(t.init){handleInit({cwd:n,force:t.force??!1});return}let S=t.paths?.length?t.paths:[`.`],C=[];t.check?C.push(`--check`):t.write===!1?C.push(`--list-different`):C.push(`--write`);let N=t.configPath??findOxfmtConfig(n)??void 0;if(N&&C.push(`--config`,vn(N)),C.push(...S),t.check&&await shouldUseNativeOxfmt()){let t=scanForNativeSkips(S,n,{configPath:N});if(t.skipped.length>0){let S=t.skipped.map(t=>` ${Sn(n,t)||t}`).join(`
1740
+ `);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),AW,jW=__esmMin(()=>{jn(),az(),AW={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:t=>t.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=[];t.fix&&C.push(`--fix`);let N=t.configPath??findOxlintConfig(n)??void 0;N&&C.push(`--config`,vn(N)),C.push(...S);try{setOxcExitCode(await runOxlint(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),MW,NW=__esmMin(()=>{jn(),az(),MW={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:t=>t.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=t.verbose??!1,N=t.write!==!1;try{let F=[N?`--write`:`--list-different`],I=t.configPath??findOxfmtConfig(n)??void 0;I&&F.push(`--config`,vn(I)),F.push(...S);let H=await runOxfmt(F,{cwd:n,verbose:C}),W=[];N&&W.push(`--fix`);let q=t.configPath??findOxlintConfig(n)??void 0;q&&W.push(`--config`,vn(q)),W.push(...S);let Y=await runOxlint(W,{cwd:n,verbose:C});setOxcExitCode(H||Y)}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}});function createInterface(t,n){return typeof t==`object`&&t&&!(`read`in t&&typeof t.read==`function`)?new Interface(t):new Interface({input:t,output:n})}var Interface,PW=__esmMin(()=>{Dd(),Interface=class extends Interface$1{question(t,n){return new Promise(n=>{super.question(t,n)})}}});function semverGt(t,n){try{return compare(t,n)===1}catch{return!1}}function groupByDependency(t){let n=new Map;for(let S of t){let t=n.get(S.name);t||(t={name:S.name,occurrences:[],declaredRanges:new Set,dominantRange:S.currentRange,highestVersion:S.currentVersion},n.set(S.name,t)),t.occurrences.push(S),t.declaredRanges.add(S.currentRange),S.currentVersion&&(!t.highestVersion||semverGt(S.currentVersion,t.highestVersion))&&(t.highestVersion=S.currentVersion)}for(let t of n.values()){let n=new Map;for(let S of t.occurrences)n.set(S.currentRange,(n.get(S.currentRange)??0)+1);let S=t.occurrences[0].currentRange,C=-1,N=null;for(let[t,F]of n.entries()){let n=parse(t.replace(/^[\^~>=<]+/,``))?.version??null;(F>C||F===C&&n&&N&&semverGt(n,N)||F===C&&t<S)&&(S=t,C=F,N=n)}t.dominantRange=S}return[...n.values()].sort((t,n)=>t.name.localeCompare(n.name))}function isInconsistent(t){return t.declaredRanges.size>1}function findInconsistencies(t){return t.filter(isInconsistent)}var FW=__esmMin(()=>{PP()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`[gjsify upgrade] no package.json at ${S}`);let C=JSON.parse(readFileSync(S,`utf-8`));return{root:t,workspaces:[{name:C.name??`<root>`,location:t,relativeLocation:`.`,version:C.version??`0.0.0`,manifest:C,private:C.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(t,n,S){let C=n?.split(`,`).map(t=>t.trim()).filter(Boolean),N=S?.split(`,`).map(t=>t.trim()).filter(Boolean);return(!C||C.length===0)&&(!N||N.length===0)?t:filterWorkspaces(t,{include:C,exclude:N})}function parseFilterList(t){return t?t.split(`,`).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(t,n){let S=[];for(let C of t)for(let t of collectFromWorkspace(C,n))S.push(t);return S}function collectFromWorkspace(t,n){let S=[],C=t.manifest;for(let N of LW){let F=C[N];if(!(!F||typeof F!=`object`))for(let[C,I]of Object.entries(F)){if(typeof I!=`string`||n.length&&!n.some(t=>C.toLowerCase().includes(t))||isDistTagSpec(I)||I.startsWith(`workspace:`)||I.startsWith(`file:`)||I.startsWith(`link:`)||I.startsWith(`git+`)||I.startsWith(`git:`)||I.startsWith(`http:`)||I.startsWith(`https:`)||I.startsWith(`npm:`)||I.startsWith(`portal:`))continue;let{prefix:F,version:H}=splitRange(I);S.push({workspace:t.name,workspaceLocation:t.location,name:C,field:N,currentRange:I,currentVersion:H,prefix:F})}}return S}function isDistTagSpec(t){let n=t.trim();return RW.has(n)||!/^[A-Za-z]/.test(n)||/^v\d/.test(n)||/^v[xX*]/.test(n)?!1:/^[A-Za-z][\w.-]*$/.test(n)}function splitRange(t){let n=t.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!n)return{prefix:``,version:null};let S=n[1]??``,C=n[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:S,version:(C?parse(C):null)?.version??null}}function reportInexactRanges(t){let n=t.map(t=>({name:t.name,loose:t.occurrences.filter(t=>t.prefix!==``)})).filter(t=>t.loose.length>0);if(n.length===0)return 0;let S=n.reduce((t,n)=>t+n.loose.length,0);ge.error(`gjsify upgrade --check --exact: FAIL. ${S} declaration(s) across ${n.length} dep(s) carry a range operator:\n`);for(let t of n){let n=new Map;for(let S of t.loose){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${zW.bold}${t.name}${zW.reset}`);for(let[t,S]of n.entries()){let n=S.length>6?`${S.slice(0,6).join(`, `)} … +${S.length-6}`:S.join(`, `);ge.error(` ${t.padEnd(16)} — ${n}`)}}return S}function checkLockfileRangeViolations(t,n){let S=xn(n,`gjsify-lock.json`);if(!existsSync(S))return 0;let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{return 0}if(!C.packages)return 0;let N=new Map;for(let n of t){let t=N.get(n.name)??new Set;for(let S of n.occurrences)t.add(S.currentRange);N.set(n.name,t)}let F=0;for(let[t,n]of Object.entries(C.packages)){if(!n.version)continue;let S=t.split(`node_modules/`);if(S.length!==2)continue;let C=S[1],I=N.get(C);if(!I||I.size===0)continue;let H=!1;for(let t of I)try{if(n.version&&satisfies(n.version,t)){H=!0;break}}catch{}H||(ge.error(` ${C}: lockfile has ${n.version}, but declared ranges are ${[...I].join(`, `)}`),F++)}return F>0&&ge.error(`gjsify upgrade --check: FAIL. ${F} lockfile entr${F===1?`y`:`ies`} violate declared ranges:\n`),F}function runCheckMode(t,n=!1,S=process.cwd()){checkLockfileRangeViolations(t,S);let C=n?reportInexactRanges(t):0,N=findInconsistencies(t);if(N.length===0&&C>0)return ge.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ge.log(`gjsify upgrade --check: OK. ${t.length} dep(s) consistently declared across workspaces`+(n?`, every declaration pinned exactly.`:`.`));return}ge.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let t of N){let n=new Map;for(let S of t.occurrences){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${zW.bold}${t.name}${zW.reset}`);for(let[t,S]of n.entries())ge.error(` ${t.padEnd(16)} — ${S.join(`, `)}`)}ge.error(n?"\nFix: run `gjsify upgrade --align --exact` (offline; aligns each dep to its highest declared version and drops the operator).":"\nFix: run `gjsify upgrade --align` (offline; aligns each dep to its highest declared range)."),process.exit(1)}function alignTargets(t,n){return n?t.filter(t=>isInconsistent(t)||t.occurrences.some(t=>t.prefix!==``)):findInconsistencies(t)}function reportUnrepairable(t){ge.error(`\ngjsify upgrade --align: ${t.length} dep(s) left unrepaired — no version to align on:\n`);for(let n of t)ge.error(` ${zW.bold}${n.name}${zW.reset} ${[...n.declaredRanges].join(`, `)}`);return ge.error("\nThose ranges name no single version. Edit them by hand, or resolve one with `--latest`."),process.exit(1)}function runAlignMode(t,n){let S=n.exact??!1,C=alignTargets(t,S);if(C.length===0){ge.log(`gjsify upgrade --align: nothing to do. ${t.length} dep(s) already consistent`+(S?`, every declaration pinned exactly.`:`.`));return}let N=[],F=[];for(let t of C){if(!t.highestVersion){F.push(t);continue}let n=t.occurrences.find(n=>n.currentRange===t.dominantRange)?.prefix||`^`;N.push({...t,latestVersion:t.highestVersion,diff:`none`,occurrences:t.occurrences.map(t=>({...t,prefix:n}))})}if(N.length>0){ge.log(S?`gjsify upgrade --align --exact: pinning ${N.length} dep(s) to their highest declared version, without a range operator:\n`:`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let t of N){let n=t.occurrences[0]?.prefix??`^`;ge.log(` ${t.name.padEnd(28)} ranges: ${[...t.declaredRanges].join(`, `)} → ${targetRange(n,t.latestVersion,S)}`)}if(n.dryRun)ge.log(`
1741
+ [gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return zW.red;case`minor`:return zW.yellow;case`patch`:return zW.green;case`prerelease`:return zW.cyan;default:return``}}function printTable(t){let n=Math.max(...t.map(t=>t.name.length),4),S=Math.max(...t.map(t=>`${t.occurrences.length}`.length+2),3),C=Math.max(...t.map(t=>declaredCellWidth(t)),7),N=Math.max(...t.map(t=>t.latestVersion.length),6),F=String(t.length).length+2,I=` `.repeat(F+2)+zW.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+zW.reset;ge.log(I),ge.log(` `.repeat(F+2)+zW.dim+`─`.repeat(n+S+C+N+16)+zW.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${zW.magenta}⚠ ${zW.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+zW.dim+`${H.occurrences.length}`.padEnd(S)+zW.reset+` `+zW.dim+renderDeclaredCell(H).padEnd(C)+zW.reset+` `+Y+H.latestVersion.padEnd(N)+zW.reset+` `+Y+H.diff+zW.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${zW.magenta}⚠${zW.reset} ${H} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(t){return renderDeclaredCell(t).length}function renderDeclaredCell(t){if(t.declaredRanges.size===1)return[...t.declaredRanges][0];let n=[...t.declaredRanges].sort().join(`, `);return n.length<=32?n:n.slice(0,29)+`…`}function printChangePlan(t,n=!1){for(let S of t)for(let t of S.occurrences)ge.log(` ${t.workspace.padEnd(38)} ${S.name.padEnd(28)} ${t.currentRange.padEnd(12)} → ${targetRange(t.prefix,S.latestVersion,n)}`)}async function promptSelection(t){if(!process.stdin.isTTY)return ge.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let n=createInterface({input:process.stdin,output:process.stdout});try{ge.log(`
1742
+ Select upgrades: comma- or space-separated indices, `+zW.bold+`a`+zW.reset+` for all, ranges like `+zW.bold+`1-3`+zW.reset+`, or `+zW.bold+`ENTER`+zW.reset+` to skip:`);let S=(await n.question(`> `)).trim();if(!S)return[];if(S.toLowerCase()===`a`||S.toLowerCase()===`all`)return[...t];let C=new Set;for(let t of S.split(/[\s,]+/).filter(Boolean)){let n=t.match(/^(\d+)-(\d+)$/);if(n){let t=Number(n[1]),S=Number(n[2]);for(let n=Math.min(t,S);n<=Math.max(t,S);n++)C.add(n-1)}else/^\d+$/.test(t)&&C.add(Number(t)-1)}return[...C].filter(n=>n>=0&&n<t.length).map(n=>t[n])}finally{n.close()}}function targetRange(t,n,S){return S?n:`${t}${n}`}function applyToFiles(t,n=!1){let S=new Map;for(let n of t)for(let t of n.occurrences){let C=S.get(t.workspaceLocation)??[];C.push({...n,occurrences:[t]}),S.set(t.workspaceLocation,C)}let C=0;for(let[t,N]of S.entries()){let S=xn(t,`package.json`),F=readFileSync(S,`utf-8`),I=JSON.parse(F),H=!1,W=[];for(let t of N){let S=t.occurrences[0],C=I[S.field];if(!C)continue;let N=targetRange(S.prefix,t.latestVersion,n);C[t.name]!==N&&(C[t.name]=N,H=!0,W.push(t.name))}if(H){let t=detectIndent(F);writeFileSync(S,keepUntouchedLines(F,JSON.stringify(I,null,t)+(F.endsWith(`
1743
1743
  `)?`
1744
1744
  `:``),W),`utf-8`),C++}}return C}function keepUntouchedLines(t,n,S){let C=t.split(`
1745
1745
  `),N=n.split(`
1746
1746
  `);return C.length===N.length?N.map((t,n)=>S.some(n=>t.includes(`"${n}"`))?t:C[n]).join(`
1747
- `):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:Wm,scopes:{},authTokens:{},basicAuth:{}};for(let S of[xn(homedir(),`.npmrc`),xn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var FW,IW,LW,RW=__esmMin(()=>{_e(),Fd(),jn(),Ag(),NW(),PP(),Zm(),IP(),RP(),PW(),FW={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:t=>t.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:"Offline repair mode: find deps declared at multiple ranges across the workspace and align them to the highest. With `--exact`, also drop the range operator from declarations that already agree. No registry calls.",type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one; with `--align`, repairs exactly that. Pair with `--filter` — a repository-wide exactness run touches every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async t=>{let n=discoverContext(vn(t.cwd??process.cwd())),S=applyWorkspaceFilter(n.workspaces,t.workspace,t.excludeWorkspace);if(S.length===0){ge.log(`[gjsify upgrade] no matching workspaces.`);return}let C=collectAllDeclarations(S,parseFilterList(t.filter));if(C.length===0){ge.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let N=groupByDependency(C);if(t.check)return runCheckMode(N,t.exact);if(t.align)return runAlignMode(N,t);let F=await loadNpmrcLight(n.root),I=t.latest?`latest`:t.minor?`minor`:t.patch?`patch`:`interactive`;ge.log(`[gjsify upgrade] checking ${N.length} unique deps across ${S.length} workspace(s) against ${F.registry}…`);let H=await resolveCandidateGroups(N,F,t.verbose??!1,I);if(H.length===0){ge.log(`✅ all dependencies are up to date`);let t=findInconsistencies(N);t.length>0&&ge.log(`\n⚠ ${t.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(H);let W;if(I===`interactive`&&!t.yes?W=await promptSelection(H):(t.yes&&I===`interactive`&&ge.log(`[gjsify upgrade] -y / --yes: selecting all`),W=H),W.length===0){ge.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(t.dryRun){let n=uniqueLocations(W).length;ge.log(`[gjsify upgrade] --dry-run: would update ${W.length} deps across ${n} package.json file(s).`),printChangePlan(W,t.exact);return}let q=applyToFiles(W,t.exact);ge.log(`✏️ updated ${W.length} dep(s) across ${q} package.json file(s). Run \`gjsify install\` to apply.`)}},IW=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],LW={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function unscannableBarrelPaths(t,n){let S=[];for(let C of n){let n=vn(t,C);try{(await stat$1(n)).isDirectory()||S.push(`${n} is not a directory`)}catch(t){S.push(`${n}: ${t.message}`)}}return S}async function generateBarrels(t){let n=t.singleQuotes?`'`:`"`,S=t.noSemicolon?``:`;`,C=t.extension===`none`?``:`.${t.extension}`,N=0;for(let F of t.paths){let I=vn(t.baseDir,F),H=Tn(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>BW.test(t.name)).filter(t=>t.name!==`index.ts`).filter(n=>!t.exclude.some(t=>t.test(n.name))).sort((t,n)=>t.name.localeCompare(n.name))}catch(n){t.verbose&&ge.error(`[gjsify barrels] skip ${I}: ${n.message}`);continue}let q=W.map(t=>{let N=Tn(t.name,$(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
1747
+ `):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:Wm,scopes:{},authTokens:{},basicAuth:{}};for(let S of[xn(homedir(),`.npmrc`),xn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var IW,LW,RW,zW,BW=__esmMin(()=>{_e(),Fd(),jn(),Ag(),PW(),PP(),Zm(),IP(),RP(),FW(),IW={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:t=>t.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:"Offline repair mode: find deps declared at multiple ranges across the workspace and align them to the highest. With `--exact`, also drop the range operator from declarations that already agree. No registry calls.",type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one; with `--align`, repairs exactly that. Pair with `--filter` — a repository-wide exactness run touches every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async t=>{let n=discoverContext(vn(t.cwd??process.cwd())),S=applyWorkspaceFilter(n.workspaces,t.workspace,t.excludeWorkspace);if(S.length===0){ge.log(`[gjsify upgrade] no matching workspaces.`);return}let C=collectAllDeclarations(S,parseFilterList(t.filter));if(C.length===0){ge.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let N=groupByDependency(C);if(t.check)return runCheckMode(N,t.exact);if(t.align)return runAlignMode(N,t);let F=await loadNpmrcLight(n.root),I=t.latest?`latest`:t.minor?`minor`:t.patch?`patch`:`interactive`;ge.log(`[gjsify upgrade] checking ${N.length} unique deps across ${S.length} workspace(s) against ${F.registry}…`);let H=await resolveCandidateGroups(N,F,t.verbose??!1,I);if(H.length===0){ge.log(`✅ all dependencies are up to date`);let t=findInconsistencies(N);t.length>0&&ge.log(`\n⚠ ${t.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(H);let W;if(I===`interactive`&&!t.yes?W=await promptSelection(H):(t.yes&&I===`interactive`&&ge.log(`[gjsify upgrade] -y / --yes: selecting all`),W=H),W.length===0){ge.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(t.dryRun){let n=uniqueLocations(W).length;ge.log(`[gjsify upgrade] --dry-run: would update ${W.length} deps across ${n} package.json file(s).`),printChangePlan(W,t.exact);return}let q=applyToFiles(W,t.exact);ge.log(`✏️ updated ${W.length} dep(s) across ${q} package.json file(s). Run \`gjsify install\` to apply.`)}},LW=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],RW=new Set([`x`,`X`,`*`,``]),zW={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function unscannableBarrelPaths(t,n){let S=[];for(let C of n){let n=vn(t,C);try{(await stat$1(n)).isDirectory()||S.push(`${n} is not a directory`)}catch(t){S.push(`${n}: ${t.message}`)}}return S}async function generateBarrels(t){let n=t.singleQuotes?`'`:`"`,S=t.noSemicolon?``:`;`,C=t.extension===`none`?``:`.${t.extension}`,N=0;for(let F of t.paths){let I=vn(t.baseDir,F),H=Tn(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>HW.test(t.name)).filter(t=>t.name!==`index.ts`).filter(n=>!t.exclude.some(t=>t.test(n.name))).sort((t,n)=>t.name.localeCompare(n.name))}catch(n){t.verbose&&ge.error(`[gjsify barrels] skip ${I}: ${n.message}`);continue}let q=W.map(t=>{let N=Tn(t.name,$(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
1748
1748
  `)}\n`:`export {};
1749
- `,X=`${t.header}\n\n${Y}`,Z=xn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var zW,BW,VW=__esmMin(()=>{_e(),vd(),jn(),zW=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],BW=/\.(ts|tsx|mts|cts)$/}),HW,UW=__esmMin(()=>{_e(),VW(),HW={command:`barrels [paths..]`,description:"Regenerate `index.ts` barrel files for the given directories. Drop-in replacement for `barrelsby`.",builder:t=>t.positional(`paths`,{description:"Directories whose `index.ts` to (re)generate. May also be passed via `--paths`.",type:`string`,array:!0}).option(`paths`,{alias:`p`,description:`Alternative to positional — repeatable list of directories.`,type:`string`,array:!0}).option(`ext`,{description:"Import-specifier extension. Default: `none` (bundler-mode resolution).",type:`string`,choices:[`js`,`ts`,`none`],default:`none`}).option(`base-dir`,{alias:`b`,description:"Resolve `paths` against this directory. Default: cwd.",type:`string`}).option(`exclude`,{description:"Regex(es) of file names to skip. Repeatable. Defaults: `\\.test\\.`, `\\.spec\\.`, `\\.test-data\\.`.",type:`string`,array:!0}).option(`header`,{description:`Header comment prepended to every generated file.`,type:`string`}).option(`semicolon`,{description:"Emit trailing `;` on each export line. Negate with `--no-semicolon`. Default: omitted.",type:`boolean`,default:!1}).option(`single-quotes`,{description:"Use `'` for import specifiers. Default: true. Pass `--no-single-quotes` for `\"`.",type:`boolean`,default:!0}).option(`check`,{description:`Report drift without modifying files; exit non-zero if any barrel is stale.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Log each file scanned + written.`,type:`boolean`,default:!1}),handler:async t=>{let n=Array.from(new Set((t.paths??[]).filter(Boolean)));if(n.length===0){ge.error(`[gjsify barrels] no paths provided. Pass directories as positional arguments or via --paths.`),process.exitCode=1;return}let S=t.baseDir??process.cwd(),C=await unscannableBarrelPaths(S,n);if(C.length>0){for(let t of C)ge.error(`[gjsify barrels] cannot scan ${t}`);ge.error(`[gjsify barrels] ${C.length} of ${n.length} path(s) could not be scanned — refusing to report on the rest as if that were the whole set.`),process.exitCode=1;return}let N=t.exclude?.length?t.exclude:[...zW],F=await generateBarrels({paths:n,extension:t.ext??`none`,baseDir:S,exclude:N.map(t=>new RegExp(t)),header:t.header??"// Auto-generated by `gjsify barrels` — do not edit by hand.",noSemicolon:t.semicolon===!1||t.semicolon===void 0,singleQuotes:t.singleQuotes!==!1,check:t.check??!1,verbose:t.verbose??!1});t.check&&F>0&&(ge.error(`[gjsify barrels] ${F} barrel file(s) drifted. Run without --check to fix.`),process.exitCode=1)}}}),WW,GW=__esmMin(()=>{_e(),Nl(),jn(),Hn(),sF(),nF(),Fd(),GH(),kI(),RP(),P_(),WW={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:t=>t.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async t=>{let n=(t._??[]).slice(1).map(String),S=t.tscArgs??[],C=n.length>0?n:S,N=process.cwd(),F=[pathToFileURL(`${findWorkspaceRoot(N)??N}/__gjsify_tsc__.js`).href,import.meta.url],I;for(let t of F)try{I=createRequire(t).resolve(`@gjsify/tsc/bundle`);break}catch{}let H;for(let t of F)try{H=xn(wn(createRequire(t).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!I&&!H)return ge.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ge.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let W=buildNativeEnv(detectNativePackages(N)),q={...process.env,...W},runNodeTsc=async()=>{let t=nodeBinary();if(!(t.includes(`/`)||t.includes(`\\`)?existsSync(t):isOnPath(t)))return ge.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${t}\` cannot be run, so upstream \`typescript\` cannot run either.`),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ge.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((n,S)=>{spawnToCompletion(t,[H,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(S)})}catch(t){let n=t;return n.code===`ENOENT`?(ge.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ge.error(`gjsify tsc (node typescript): ${n.message}`),forceExit(1)}};if(I)try{await new Promise((t,n)=>{spawnToCompletion(`gjs`,[`-m`,I,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(n)})}catch(t){let n=t;return n.code===`ENOENT`&&H?await runNodeTsc():(n.code===`ENOENT`?(ge.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ge.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ge.error(`gjsify tsc: ${n.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(t){return t.split(`
1750
- `).map(t=>t.trim()).filter(Boolean)}var KW=__esmMin(()=>{Fd()});function isResolvableScript(t){return ZW.test(t)&&!qW.some(n=>n.test(t))&&!XW.some(n=>n.match.test(t))}function resolveRootScripts(t,n){let S=new Set,C=[];for(let n of t)isResolvableScript(n)?C.push(n):S.add(n);let N=new Set;for(;C.length>0;){let t=C.shift();if(!N.has(t)){N.add(t);for(let N of n(t))JW.some(t=>t.test(N))||(isResolvableScript(N)?C.push(N):S.add(N))}}return{files:[...S],scripts:N.size}}function classifyAndExpand(t,n,S){let C=n.map(t=>t.replace(/\\/g,`/`)).filter(t=>t.length>0);if(C.length===0)return{global:!1,reason:`empty-diff`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};let N=[];for(let t of C)JW.some(n=>n.test(t))||N.push(t);let F=``;if(S){let t=resolveRootScripts(N,S);t.scripts>0&&(N=t.files,F=`; ${t.scripts} root script(s) resolved to their readers`)}if(N.length===0)return{global:!1,reason:`ignored-only`+F,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};for(let n of N)for(let S of qW)if(S.test(n))return{global:!0,reason:`global-trigger ${S.source} matched ${n}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};let{matched:I,unmatched:H}=workspacesForChangedFiles(t,N),W=new Set(t.map(t=>t.name)),q=new Set,Y=new Set,X=!1;for(let n of XW){let S=N.filter(t=>n.match.test(t));if(S.length!==0){for(let t of S)Y.add(t);for(let S of n.seeds){if(!W.has(S))return{global:!0,reason:`script-coupling seed ${S} is not a workspace (${n.match.source} → ${n.why}); SCRIPT_COUPLINGS in commands/affected.ts is stale`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};q.add(S)}n.runE2E&&(X=!0)}}let Z=H.filter(t=>!Y.has(t));if(Z.length>0)return{global:!0,reason:`unmatched files (${Z.length}): ${Z.slice(0,3).join(`, `)}${Z.length>3?`…`:``}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};for(let t of q)I.add(t);if(q.size===0&&N.every(t=>YW.some(n=>n.test(t)))&&I.size===1){let t=[...I][0],n=N.some(t=>t.startsWith(`tests/e2e/`)),S=N.some(t=>t.startsWith(`tests/integration/`));return{global:!1,reason:`test-only (${N.length} file(s) in ${t})${F}`,workspaces:[t],runE2E:n||X,runIntegration:S||isIntegrationWorkspace(t),skipAll:!1}}let te=affectedClosure(buildReverseDependencyGraph(t,{includeDev:!1}),[...I]),ne=buildDependencyGraph(t,{includeDev:!0}),re=!1;for(let[t,n]of ne.edges)if(isIntegrationWorkspace(t)){for(let S of n)if(te.has(S)){te.add(t),re=!0;break}}let ie=N.some(t=>t.startsWith(`tests/e2e/`))||X;return{global:!1,reason:`closure (${te.size} ws from ${I.size} seed(s))`+(q.size>0?`, ${q.size} via script-coupling`:``)+F,workspaces:[...te].sort(),runE2E:ie,runIntegration:re,skipAll:!1}}function isIntegrationWorkspace(t){return t.startsWith(`@gjsify/integration-`)}var qW,JW,YW,XW,ZW,QW=__esmMin(()=>{IP(),qW=[/^packages\/infra\/workspace\//,/^packages\/infra\/cli\//,/^packages\/infra\/rolldown-plugin-gjsify\//,/^packages\/infra\/resolve-npm\//,/^packages\/gjs\/unit\//,/^\.github\/actions\//,/^gjsify-lock\.json$/,/^package\.json$/,/^tsconfig[^/]*\.json$/,/^\.github\/workflows\/main\.yml$/,/^scripts\/audit-runtimes\.mjs$/],JW=[/\.md$/i,/^refs\//,/^website\//,/^docs\//,/^\.github\/workflows\/(deploy-docs|commitlint|release|release-cut|audit-runtimes|prebuilds|node-gi|napi|cli-cross-platform|build-ci-image|cancel-pr-runs|macos-suites|windows-suites|gtk-os-suites)\.yml$/,/^\.github\/prebuild-toolchain\//,/^scripts\/manifest-conformance\//,/^status\//,/^scripts\/generate-status\.mjs$/,/^packages\/node-gi\//,/^packages\/napi\//,/^flatpak\//,/^LICENSE/,/^\.gitignore$/,/^\.gjsify-[^/]*\.md$/,/^STATUS\.md$/,/^CHANGELOG\.md$/,/^AGENTS\.md$/,/^CLAUDE\.md$/,/^README\.md$/],YW=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],XW=[{match:/^\.githooks\//,seeds:[],runE2E:!0,why:`tests/e2e/git-hooks-cli-bundle-staleness drives .githooks/pre-commit`},{match:/^templates\//,seeds:[`@gjsify/create-app`],runE2E:!0,why:`@gjsify/create-app build → node scripts/process-template.mjs reads templates/`},{match:/^packages\/framework\/react-native\//,seeds:[],runE2E:!0,why:`tests/e2e/react-native-devtools is the only external observer of AppRegistry.runApplication`}],ZW=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
1749
+ `,X=`${t.header}\n\n${Y}`,Z=xn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var VW,HW,UW=__esmMin(()=>{_e(),vd(),jn(),VW=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],HW=/\.(ts|tsx|mts|cts)$/}),WW,GW=__esmMin(()=>{_e(),UW(),WW={command:`barrels [paths..]`,description:"Regenerate `index.ts` barrel files for the given directories. Drop-in replacement for `barrelsby`.",builder:t=>t.positional(`paths`,{description:"Directories whose `index.ts` to (re)generate. May also be passed via `--paths`.",type:`string`,array:!0}).option(`paths`,{alias:`p`,description:`Alternative to positional — repeatable list of directories.`,type:`string`,array:!0}).option(`ext`,{description:"Import-specifier extension. Default: `none` (bundler-mode resolution).",type:`string`,choices:[`js`,`ts`,`none`],default:`none`}).option(`base-dir`,{alias:`b`,description:"Resolve `paths` against this directory. Default: cwd.",type:`string`}).option(`exclude`,{description:"Regex(es) of file names to skip. Repeatable. Defaults: `\\.test\\.`, `\\.spec\\.`, `\\.test-data\\.`.",type:`string`,array:!0}).option(`header`,{description:`Header comment prepended to every generated file.`,type:`string`}).option(`semicolon`,{description:"Emit trailing `;` on each export line. Negate with `--no-semicolon`. Default: omitted.",type:`boolean`,default:!1}).option(`single-quotes`,{description:"Use `'` for import specifiers. Default: true. Pass `--no-single-quotes` for `\"`.",type:`boolean`,default:!0}).option(`check`,{description:`Report drift without modifying files; exit non-zero if any barrel is stale.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Log each file scanned + written.`,type:`boolean`,default:!1}),handler:async t=>{let n=Array.from(new Set((t.paths??[]).filter(Boolean)));if(n.length===0){ge.error(`[gjsify barrels] no paths provided. Pass directories as positional arguments or via --paths.`),process.exitCode=1;return}let S=t.baseDir??process.cwd(),C=await unscannableBarrelPaths(S,n);if(C.length>0){for(let t of C)ge.error(`[gjsify barrels] cannot scan ${t}`);ge.error(`[gjsify barrels] ${C.length} of ${n.length} path(s) could not be scanned — refusing to report on the rest as if that were the whole set.`),process.exitCode=1;return}let N=t.exclude?.length?t.exclude:[...VW],F=await generateBarrels({paths:n,extension:t.ext??`none`,baseDir:S,exclude:N.map(t=>new RegExp(t)),header:t.header??"// Auto-generated by `gjsify barrels` — do not edit by hand.",noSemicolon:t.semicolon===!1||t.semicolon===void 0,singleQuotes:t.singleQuotes!==!1,check:t.check??!1,verbose:t.verbose??!1});t.check&&F>0&&(ge.error(`[gjsify barrels] ${F} barrel file(s) drifted. Run without --check to fix.`),process.exitCode=1)}}}),KW,qW=__esmMin(()=>{_e(),Nl(),jn(),Hn(),sF(),nF(),Fd(),GH(),kI(),RP(),P_(),KW={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:t=>t.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async t=>{let n=(t._??[]).slice(1).map(String),S=t.tscArgs??[],C=n.length>0?n:S,N=process.cwd(),F=[pathToFileURL(`${findWorkspaceRoot(N)??N}/__gjsify_tsc__.js`).href,import.meta.url],I;for(let t of F)try{I=createRequire(t).resolve(`@gjsify/tsc/bundle`);break}catch{}let H;for(let t of F)try{H=xn(wn(createRequire(t).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!I&&!H)return ge.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ge.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let W=buildNativeEnv(detectNativePackages(N)),q={...process.env,...W},runNodeTsc=async()=>{let t=nodeBinary();if(!(t.includes(`/`)||t.includes(`\\`)?existsSync(t):isOnPath(t)))return ge.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${t}\` cannot be run, so upstream \`typescript\` cannot run either.`),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ge.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((n,S)=>{spawnToCompletion(t,[H,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(S)})}catch(t){let n=t;return n.code===`ENOENT`?(ge.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ge.error(`gjsify tsc (node typescript): ${n.message}`),forceExit(1)}};if(I)try{await new Promise((t,n)=>{spawnToCompletion(`gjs`,[`-m`,I,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(n)})}catch(t){let n=t;return n.code===`ENOENT`&&H?await runNodeTsc():(n.code===`ENOENT`?(ge.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ge.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ge.error(`gjsify tsc: ${n.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(t){return t.split(`
1750
+ `).map(t=>t.trim()).filter(Boolean)}var JW=__esmMin(()=>{Fd()});function isResolvableScript(t){return $W.test(t)&&!YW.some(n=>n.test(t))&&!QW.some(n=>n.match.test(t))}function resolveRootScripts(t,n){let S=new Set,C=[];for(let n of t)isResolvableScript(n)?C.push(n):S.add(n);let N=new Set;for(;C.length>0;){let t=C.shift();if(!N.has(t)){N.add(t);for(let N of n(t))XW.some(t=>t.test(N))||(isResolvableScript(N)?C.push(N):S.add(N))}}return{files:[...S],scripts:N.size}}function classifyAndExpand(t,n,S){let C=n.map(t=>t.replace(/\\/g,`/`)).filter(t=>t.length>0);if(C.length===0)return{global:!1,reason:`empty-diff`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};let N=[];for(let t of C)XW.some(n=>n.test(t))||N.push(t);let F=``;if(S){let t=resolveRootScripts(N,S);t.scripts>0&&(N=t.files,F=`; ${t.scripts} root script(s) resolved to their readers`)}if(N.length===0)return{global:!1,reason:`ignored-only`+F,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};for(let n of N)for(let S of YW)if(S.test(n))return{global:!0,reason:`global-trigger ${S.source} matched ${n}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};let{matched:I,unmatched:H}=workspacesForChangedFiles(t,N),W=new Set(t.map(t=>t.name)),q=new Set,Y=new Set,X=!1;for(let n of QW){let S=N.filter(t=>n.match.test(t));if(S.length!==0){for(let t of S)Y.add(t);for(let S of n.seeds){if(!W.has(S))return{global:!0,reason:`script-coupling seed ${S} is not a workspace (${n.match.source} → ${n.why}); SCRIPT_COUPLINGS in commands/affected.ts is stale`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};q.add(S)}n.runE2E&&(X=!0)}}let Z=H.filter(t=>!Y.has(t));if(Z.length>0)return{global:!0,reason:`unmatched files (${Z.length}): ${Z.slice(0,3).join(`, `)}${Z.length>3?`…`:``}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};for(let t of q)I.add(t);if(q.size===0&&N.every(t=>ZW.some(n=>n.test(t)))&&I.size===1){let t=[...I][0],n=N.some(t=>t.startsWith(`tests/e2e/`)),S=N.some(t=>t.startsWith(`tests/integration/`));return{global:!1,reason:`test-only (${N.length} file(s) in ${t})${F}`,workspaces:[t],runE2E:n||X,runIntegration:S||isIntegrationWorkspace(t),skipAll:!1}}let te=affectedClosure(buildReverseDependencyGraph(t,{includeDev:!1}),[...I]),ne=buildDependencyGraph(t,{includeDev:!0}),re=!1;for(let[t,n]of ne.edges)if(isIntegrationWorkspace(t)){for(let S of n)if(te.has(S)){te.add(t),re=!0;break}}let ie=N.some(t=>t.startsWith(`tests/e2e/`))||X;return{global:!1,reason:`closure (${te.size} ws from ${I.size} seed(s))`+(q.size>0?`, ${q.size} via script-coupling`:``)+F,workspaces:[...te].sort(),runE2E:ie,runIntegration:re,skipAll:!1}}function isIntegrationWorkspace(t){return t.startsWith(`@gjsify/integration-`)}var YW,XW,ZW,QW,$W,eG=__esmMin(()=>{IP(),YW=[/^packages\/infra\/workspace\//,/^packages\/infra\/cli\//,/^packages\/infra\/rolldown-plugin-gjsify\//,/^packages\/infra\/resolve-npm\//,/^packages\/gjs\/unit\//,/^\.github\/actions\//,/^gjsify-lock\.json$/,/^package\.json$/,/^tsconfig[^/]*\.json$/,/^\.github\/workflows\/main\.yml$/,/^scripts\/audit-runtimes\.mjs$/],XW=[/\.md$/i,/^refs\//,/^website\//,/^docs\//,/^\.github\/workflows\/(deploy-docs|commitlint|release|release-cut|audit-runtimes|prebuilds|node-gi|napi|cli-cross-platform|build-ci-image|cancel-pr-runs|macos-suites|windows-suites|gtk-os-suites)\.yml$/,/^\.github\/prebuild-toolchain\//,/^scripts\/manifest-conformance\//,/^status\//,/^scripts\/generate-status\.mjs$/,/^packages\/node-gi\//,/^packages\/napi\//,/^flatpak\//,/^LICENSE/,/^\.gitignore$/,/^\.gjsify-[^/]*\.md$/,/^STATUS\.md$/,/^CHANGELOG\.md$/,/^AGENTS\.md$/,/^CLAUDE\.md$/,/^README\.md$/],ZW=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],QW=[{match:/^\.githooks\//,seeds:[],runE2E:!0,why:`tests/e2e/git-hooks-cli-bundle-staleness drives .githooks/pre-commit`},{match:/^templates\//,seeds:[`@gjsify/create-app`],runE2E:!0,why:`@gjsify/create-app build → node scripts/process-template.mjs reads templates/`},{match:/^packages\/framework\/react-native\//,seeds:[],runE2E:!0,why:`tests/e2e/react-native-devtools is the only external observer of AppRegistry.runApplication`}],$W=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
1751
1751
  `).filter(t=>!S.test(t)).join(`
1752
1752
  `)}function scriptNamePattern(t){let n=un.basename(t),S=/^(.*?)(\.d)?\.[mc]?[jt]sx?$/.exec(n),C=S?`${escapeRe(S[1])}(\\.d)?\\.[mc]?[jt]sx?\\b`:`${escapeRe(n)}\\b`;return RegExp(`(^|[^\\w.-])${C}`)}function gatedJobs(t){let n=new Map,S=new Set;for(let{job:C,text:N}of t){if(!C)continue;n.has(C)||n.set(C,[]);let t=/^ {4}needs:\s*\[(.*)\]/.exec(N)??/^ {4}needs:\s*([A-Za-z0-9_-]+)\s*$/.exec(N);t&&n.set(C,t[1].split(`,`).map(t=>t.trim()).filter(Boolean)),(/needs\.changes\b/.test(N)||/^ {4}needs:\s*$/.test(N))&&S.add(C)}let C=new Set([`changes`,...S]),N=!0;for(;N;){N=!1;for(let[t,S]of n)!C.has(t)&&S.some(t=>C.has(t))&&(C.add(t),N=!0)}return C.delete(`changes`),C}function workflowLines(t){let n=t.split(`
1753
- `),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===$W||S===eG||n.set(S,stripCommentLines(S,C));let S=t.get($W),C=S===void 0?[]:workflowLines(S),N=gatedJobs(C),gatedWorkflowNames=t=>C.some(n=>t.test(n.text)&&(n.job===void 0||N.has(n.job))),F,I=t.get(eG);I!==void 0&&(F=JSON.parse(I));let manifestReads=t=>{if(!F)return!1;for(let[n,S]of Object.entries(F))if(n!==`scripts`&&t.test(JSON.stringify(S)))return!0;let n=F.scripts??{};for(let[S,C]of Object.entries(n)){if(!t.test(C))continue;if(nG.test(S))return!0;let N=RegExp(`(^|[\\s"'])${escapeRe(S)}($|[\\s"'&;|])`);if(Object.entries(n).some(([t,n])=>t!==S&&N.test(n))||gatedWorkflowNames(N))return!0}return!1};return t=>{let S=scriptNamePattern(t),C=[];for(let[N,F]of n)N!==t&&S.test(F)&&C.push(N);return gatedWorkflowNames(S)&&C.push($W),manifestReads(S)&&C.push(eG),C.sort()}}function readTrackedTexts(t){let n=spawnSync(`git`,[`ls-files`,`-z`],{cwd:t,encoding:`utf8`});if(n.status!==0)throw Error(`git ls-files failed (${n.status}): ${String(n.stderr).trim()}`);let S=new Map;for(let C of n.stdout.split(`\0`)){if(!C||C.startsWith(`refs/`))continue;let n=xn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>tG)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var $W,eG,tG,nG,escapeRe,rG=__esmMin(()=>{D_(),Fd(),jn(),$W=`.github/workflows/main.yml`,eG=`package.json`,tG=2*1024*1024,nG=/^(pre|post)?(install|prepare|build|test)(:|$)/,escapeRe=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)});function scriptReadersFor(t,n){if(n.some(t=>/^scripts\/[^/]+$/.test(t.replace(/\\/g,`/`))))try{return buildScriptReferrers(readTrackedTexts(t))}catch(t){process.stderr.write(`gjsify affected: cannot index the tree for script readers (${String(t)}); root scripts stay unmatched\n`);return}}function runGitDiff(t,n,S){let C=spawnSync(`git`,[`diff`,`--no-renames`,`--name-only`,`${n}...${S}`],{cwd:t,encoding:`utf8`});if(C.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${C.status}): ${C.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${C.status})`);return C.stdout.split(`
1753
+ `),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===tG||S===nG||n.set(S,stripCommentLines(S,C));let S=t.get(tG),C=S===void 0?[]:workflowLines(S),N=gatedJobs(C),gatedWorkflowNames=t=>C.some(n=>t.test(n.text)&&(n.job===void 0||N.has(n.job))),F,I=t.get(nG);I!==void 0&&(F=JSON.parse(I));let manifestReads=t=>{if(!F)return!1;for(let[n,S]of Object.entries(F))if(n!==`scripts`&&t.test(JSON.stringify(S)))return!0;let n=F.scripts??{};for(let[S,C]of Object.entries(n)){if(!t.test(C))continue;if(iG.test(S))return!0;let N=RegExp(`(^|[\\s"'])${escapeRe(S)}($|[\\s"'&;|])`);if(Object.entries(n).some(([t,n])=>t!==S&&N.test(n))||gatedWorkflowNames(N))return!0}return!1};return t=>{let S=scriptNamePattern(t),C=[];for(let[N,F]of n)N!==t&&S.test(F)&&C.push(N);return gatedWorkflowNames(S)&&C.push(tG),manifestReads(S)&&C.push(nG),C.sort()}}function readTrackedTexts(t){let n=spawnSync(`git`,[`ls-files`,`-z`],{cwd:t,encoding:`utf8`});if(n.status!==0)throw Error(`git ls-files failed (${n.status}): ${String(n.stderr).trim()}`);let S=new Map;for(let C of n.stdout.split(`\0`)){if(!C||C.startsWith(`refs/`))continue;let n=xn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>rG)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var tG,nG,rG,iG,escapeRe,aG=__esmMin(()=>{D_(),Fd(),jn(),tG=`.github/workflows/main.yml`,nG=`package.json`,rG=2*1024*1024,iG=/^(pre|post)?(install|prepare|build|test)(:|$)/,escapeRe=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)});function scriptReadersFor(t,n){if(n.some(t=>/^scripts\/[^/]+$/.test(t.replace(/\\/g,`/`))))try{return buildScriptReferrers(readTrackedTexts(t))}catch(t){process.stderr.write(`gjsify affected: cannot index the tree for script readers (${String(t)}); root scripts stay unmatched\n`);return}}function runGitDiff(t,n,S){let C=spawnSync(`git`,[`diff`,`--no-renames`,`--name-only`,`${n}...${S}`],{cwd:t,encoding:`utf8`});if(C.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${C.status}): ${C.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${C.status})`);return C.stdout.split(`
1754
1754
  `).filter(Boolean)}function emit(t,n){if(t===`json`){process.stdout.write(JSON.stringify(n)+`
1755
1755
  `);return}if(t===`globs`){for(let t of n.workspaces)process.stdout.write(`${t}\n`);return}if(t===`github-actions`){let t=n.global?``:n.workspaces.map(t=>`--include ${assertShellSafeWorkspaceName(t)}`).join(` `),S=process.env.GITHUB_OUTPUT,C=[`skip-all=${n.skipAll}`,`global=${n.global}`,`include-args=${t}`,`run-integration=${n.runIntegration}`,`run-e2e=${n.runE2E}`,`reason=${n.reason}`];if(S)for(let t of C)appendFileSync(S,`${t}\n`);else for(let t of C)process.stdout.write(`${t}\n`);return}process.stdout.write(`affected:
1756
- `),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(aG.test(t))return t;throw process.stderr.write(`gjsify affected: workspace name ${JSON.stringify(t)} is not shell-safe, so it cannot be emitted as an\n \`include-args\` token (the value is consumed by an UNQUOTED $INCLUDE_ARGS expansion — see the\n contract at the top of commands/affected.ts). Rename the workspace, or teach this command a\n transport the consumers can unquote. Refusing to emit a filter that would silently mis-match.\n`),process.exit(2),Error(`gjsify affected: unsafe workspace name ${t}`)}var iG,aG,oG=__esmMin(()=>{D_(),Fd(),KW(),IP(),QW(),rG(),RP(),iG={command:`affected`,description:"Classify changed files against the workspace tree and print the set of workspaces affected (seeds + transitive dependents). Designed for CI to gate `gjsify foreach test --include …` so unrelated workspaces are not re-tested on every PR.",builder:t=>t.option(`base`,{description:"Diff base. Default: `origin/main`. Resolved via `git rev-parse`. On a PR set this to `${{ github.event.pull_request.base.sha }}`.",type:`string`}).option(`head`,{description:"Diff head. Default: `HEAD`.",type:`string`,default:`HEAD`}).option(`format`,{description:`Output shape.`,choices:[`text`,`json`,`globs`,`github-actions`],default:`text`}).option(`changed-from-stdin`,{description:"Skip `git diff`. Read a newline-separated list of repo-relative paths from stdin instead. Lets callers — tests, ad-hoc scripts — control the input exactly.",type:`boolean`,default:!1}).option(`cwd`,{description:"Workspace root. Default: discovered from `process.cwd()`.",type:`string`}),handler:async t=>{let n=t.cwd??findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n,{includeRoot:!0}),C=t[`changed-from-stdin`]?readStdinLines():runGitDiff(n,t.base??`origin/main`,t.head??`HEAD`),N=classifyAndExpand(S,C,scriptReadersFor(n,C));emit(t.format,N)}},aG=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),sG=__exportAll$5({isSelfWrite:()=>isSelfWrite,runWatchLoop:()=>runWatchLoop,spawnBundleSupervised:()=>spawnBundleSupervised,spawnSupervised:()=>spawnSupervised});function spawnSupervised(t,n,S){return new Promise((C,N)=>{spawnToCompletion(t,n,{completion:`daemon`,env:S,onSpawn:C}).catch(N)})}async function spawnBundleSupervised(t,n,S,C){if(t!==`gjs`){let{bundleRequiresNodeGi:N,resolveNodeGiForBundle:F}=await Promise.resolve().then(()=>(kI(),OI));if(N(n)&&!F(n,S))throw Error(`Cannot run ${C} on ${t}: \`@gjsify/node-gi\` is not installed. Add @gjsify/node-gi as a dependency to run ${C} on ${t}.`)}let{computeNativeEnvForBundle:N}=await Promise.resolve().then(()=>(DI(),EI)),{env:F}=N(n,S),I={...process.env,...F};if(t===`gjs`)return spawnSupervised(`gjs`,[`-m`,n],I);if(t===`node`){let{nodeBinary:t}=await Promise.resolve().then(()=>(kI(),OI));return spawnSupervised(t(),[n],I)}let[H,W]=I_[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=vn(t,S),N=vn(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=wn(N);return F===vn(t)?!1:C===F||C.startsWith(`${F}${On}`)}async function runWatchLoop(t){let{dir:n,label:S,prepare:C,build:N,spawnChild:F,output:I,ignore:H,debounceMs:W=200}=t;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{C&&await C(),q&&=(q.kill(),null),await N(),F&&(q=await F())}catch(t){ge.error(`[${S}] rebuild failed: ${t.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=(t.watch??[{path:n,recursive:!0}]).map(t=>watch(t.path,{recursive:t.recursive},(n,S)=>{let C=typeof S==`string`?S:null;isSelfWrite(t.path,I,C)||H&&C!==null&&H(vn(t.path,C))||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))}));holdMainLoop();let ne=!1,shutdown=()=>{if(!ne){ne=!0,Z&&clearTimeout(Z),q?.kill();for(let t of te)t.close();process.exit(0)}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ge.log(`[${S}] watching ${t.dirLabel??n} — press Ctrl+C to stop`)}var cG=__esmMin(()=>{_e(),Fd(),jn(),Me(),HL(),P_(),L_()});function readPackage$4(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(t){let n=[];if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){if(S.name===`node_modules`||S.name.startsWith(`.`))continue;let C=xn(t,S.name);S.isDirectory()?n.push(...findStoryFiles(C)):/\.story\.(ts|js|mts|mjs)$/.test(S.name)&&n.push(C)}return n}function generateEntry$3(t,n,S){let C=t.map((t,n)=>`import * as m${n} from ${JSON.stringify(t)};`).join(`
1756
+ `),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(sG.test(t))return t;throw process.stderr.write(`gjsify affected: workspace name ${JSON.stringify(t)} is not shell-safe, so it cannot be emitted as an\n \`include-args\` token (the value is consumed by an UNQUOTED $INCLUDE_ARGS expansion — see the\n contract at the top of commands/affected.ts). Rename the workspace, or teach this command a\n transport the consumers can unquote. Refusing to emit a filter that would silently mis-match.\n`),process.exit(2),Error(`gjsify affected: unsafe workspace name ${t}`)}var oG,sG,cG=__esmMin(()=>{D_(),Fd(),JW(),IP(),eG(),aG(),RP(),oG={command:`affected`,description:"Classify changed files against the workspace tree and print the set of workspaces affected (seeds + transitive dependents). Designed for CI to gate `gjsify foreach test --include …` so unrelated workspaces are not re-tested on every PR.",builder:t=>t.option(`base`,{description:"Diff base. Default: `origin/main`. Resolved via `git rev-parse`. On a PR set this to `${{ github.event.pull_request.base.sha }}`.",type:`string`}).option(`head`,{description:"Diff head. Default: `HEAD`.",type:`string`,default:`HEAD`}).option(`format`,{description:`Output shape.`,choices:[`text`,`json`,`globs`,`github-actions`],default:`text`}).option(`changed-from-stdin`,{description:"Skip `git diff`. Read a newline-separated list of repo-relative paths from stdin instead. Lets callers — tests, ad-hoc scripts — control the input exactly.",type:`boolean`,default:!1}).option(`cwd`,{description:"Workspace root. Default: discovered from `process.cwd()`.",type:`string`}),handler:async t=>{let n=t.cwd??findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n,{includeRoot:!0}),C=t[`changed-from-stdin`]?readStdinLines():runGitDiff(n,t.base??`origin/main`,t.head??`HEAD`),N=classifyAndExpand(S,C,scriptReadersFor(n,C));emit(t.format,N)}},sG=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),lG=__exportAll$5({isSelfWrite:()=>isSelfWrite,runWatchLoop:()=>runWatchLoop,spawnBundleSupervised:()=>spawnBundleSupervised,spawnSupervised:()=>spawnSupervised});function spawnSupervised(t,n,S){return new Promise((C,N)=>{spawnToCompletion(t,n,{completion:`daemon`,env:S,onSpawn:C}).catch(N)})}async function spawnBundleSupervised(t,n,S,C){if(t!==`gjs`){let{bundleRequiresNodeGi:N,resolveNodeGiForBundle:F}=await Promise.resolve().then(()=>(kI(),OI));if(N(n)&&!F(n,S))throw Error(`Cannot run ${C} on ${t}: \`@gjsify/node-gi\` is not installed. Add @gjsify/node-gi as a dependency to run ${C} on ${t}.`)}let{computeNativeEnvForBundle:N}=await Promise.resolve().then(()=>(DI(),EI)),{env:F}=N(n,S),I={...process.env,...F};if(t===`gjs`)return spawnSupervised(`gjs`,[`-m`,n],I);if(t===`node`){let{nodeBinary:t}=await Promise.resolve().then(()=>(kI(),OI));return spawnSupervised(t(),[n],I)}let[H,W]=I_[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=vn(t,S),N=vn(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=wn(N);return F===vn(t)?!1:C===F||C.startsWith(`${F}${On}`)}async function runWatchLoop(t){let{dir:n,label:S,prepare:C,build:N,spawnChild:F,output:I,ignore:H,debounceMs:W=200}=t;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{C&&await C(),q&&=(q.kill(),null),await N(),F&&(q=await F())}catch(t){ge.error(`[${S}] rebuild failed: ${t.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=(t.watch??[{path:n,recursive:!0}]).map(t=>watch(t.path,{recursive:t.recursive},(n,S)=>{let C=typeof S==`string`?S:null;isSelfWrite(t.path,I,C)||H&&C!==null&&H(vn(t.path,C))||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))}));holdMainLoop();let ne=!1,shutdown=()=>{if(!ne){ne=!0,Z&&clearTimeout(Z),q?.kill();for(let t of te)t.close();process.exit(0)}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ge.log(`[${S}] watching ${t.dirLabel??n} — press Ctrl+C to stop`)}var uG=__esmMin(()=>{_e(),Fd(),jn(),Me(),HL(),P_(),L_()});function readPackage$4(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(t){let n=[];if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){if(S.name===`node_modules`||S.name.startsWith(`.`))continue;let C=xn(t,S.name);S.isDirectory()?n.push(...findStoryFiles(C)):/\.story\.(ts|js|mts|mjs)$/.test(S.name)&&n.push(C)}return n}function generateEntry$4(t,n,S){let C=t.map((t,n)=>`import * as m${n} from ${JSON.stringify(t)};`).join(`
1757
1757
  `),N=t.map((t,n)=>`m${n}`).join(`, `),F=S?`\n title: ${JSON.stringify(S)},`:``;return`// Auto-generated by \`gjsify storybook\` — do not edit by hand.
1758
1758
  import { collectStoryModules, runStorybook } from '@gjsify/storybook';
1759
1759
  ${C}
@@ -1762,7 +1762,14 @@ await runStorybook({
1762
1762
  applicationId: ${JSON.stringify(n)},${F}
1763
1763
  stories: collectStoryModules([${N}]),
1764
1764
  });
1765
- `}var lG,uG=__esmMin(()=>{_e(),Fd(),jn(),i_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$3,`generateEntry`),lG={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=vn(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=xn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$3(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Sn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Sn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(sK(),oK)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(DI(),EI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(kI(),OI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(kI(),OI));await t(W,Z,[],{completion:`exit`,exitOnSuccess:!0})}};if(!t.watch){if(await buildBundle(),t.buildOnly)return;await launch();return}let{runWatchLoop:re,spawnBundleSupervised:ie}=await Promise.resolve().then(()=>(cG(),sG));await re({dir:N,dirLabel:Sn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??wn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var dG=__esmMin(()=>{jn(),qF()});function readPackage$3(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}var fG,pG=__esmMin(()=>{_e(),Fd(),jn(),dG(),L_(),i_(),__name$1(readPackage$3,`readPackage`),fG={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:F_,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:vn(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=vn(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Sn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Sn(n,H);ge.log(`Watching ${Sn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(sK(),oK)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(cG(),sG));await X({dir:W,dirLabel:Sn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
1765
+ `}var dG,fG=__esmMin(()=>{_e(),Fd(),jn(),i_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),dG={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=vn(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=xn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$4(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Sn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Sn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(dK(),uK)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(DI(),EI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(kI(),OI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(kI(),OI));await t(W,Z,[],{completion:`exit`,exitOnSuccess:!0})}};if(!t.watch){if(await buildBundle(),t.buildOnly)return;await launch();return}let{runWatchLoop:re,spawnBundleSupervised:ie}=await Promise.resolve().then(()=>(uG(),lG));await re({dir:N,dirLabel:Sn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function resolveSitePackage(t){let n=vn(t);for(;;){let t=xn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(xn(t,`package.json`)))return t;let S=wn(n);if(S===n)return;n=S}}function generateEntry$3(t){let n=`// Auto-generated by \`gjsify site\` — do not edit by hand.
1766
+ import { runSiteCli } from '@gjsify/site';
1767
+ `;return t===`gjs`?`${n}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${n}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}var pG,mG=__esmMin(()=>{_e(),Fd(),jn(),i_(),__name$1(generateEntry$3,`generateEntry`),pG={command:`site <operation>`,description:`Render this project's static landing page from its AppStream metainfo (downloads, screenshots, release notes, support links), or sync the page catalogues.`,builder:t=>t.positional(`operation`,{description:`build — render the pages; i18n — update the page catalogues`,type:`string`,choices:[`build`,`i18n`],demandOption:!0}).option(`root`,{description:`Repository to read from (default: the working directory)`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: <root>/dist)`,type:`string`}).option(`offline`,{description:`Skip every network call`,type:`boolean`,default:!1}).option(`cache`,{description:`Use the one-hour HTTP response cache (--no-cache to ignore it)`,type:`boolean`,default:!0}).option(`cache-dir`,{description:`Where the response cache and the image renditions live`,defaultDescription:`<root>/node_modules/.cache/gjsify-site`,type:`string`}).option(`check`,{description:`i18n: report what is out of date instead of writing it`,type:`boolean`,default:!1}).option(`package`,{description:`i18n: sync @gjsify/site's own catalogues instead of this project's`,type:`boolean`,default:!1}).option(`runtime`,{description:"Runtime to build for and run on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle and require @gjsify/node-gi in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}),handler:async t=>{let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`gjsify site: @gjsify/site is not installed in this project.
1768
+
1769
+ The generator ships as its own package so a project only pays for it when it
1770
+ publishes a page. Add it, then run this again:
1771
+
1772
+ npm install --save-dev @gjsify/site`),process.exit(1);if(!existsSync(xn(S,`lib`,`client`,`site.js`)))return ge.error(`gjsify site: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=t.runtime??hostRuntime$1(),N=C===`gjs`?`gjs`:`node`,F=xn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=xn(F,`entry.${N}.ts`),H=xn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N));let{runCli:W}=await Promise.resolve().then(()=>(dK(),uK));await W([`build`,I,`--app`,N,`--globals`,t.globals??`auto`,`--outfile`,H]);let q=[t.operation,`--package-dir`,S];if(t.root&&q.push(`--root`,vn(n,t.root)),t.out&&q.push(`--out`,vn(n,t.out)),t.offline&&q.push(`--offline`),t.cache?t.cacheDir&&q.push(`--cache-dir`,vn(n,t.cacheDir)):q.push(`--no-cache`),t.check&&q.push(`--check`),t.package&&q.push(`--package`),C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(DI(),EI));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(kI(),OI));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(kI(),OI));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??wn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var hG=__esmMin(()=>{jn(),qF()});function readPackage$3(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}var gG,_G=__esmMin(()=>{_e(),Fd(),jn(),hG(),L_(),i_(),__name$1(readPackage$3,`readPackage`),gG={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:F_,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:vn(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=vn(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Sn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Sn(n,H);ge.log(`Watching ${Sn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(dK(),uK)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(uG(),lG));await X({dir:W,dirLabel:Sn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
1766
1773
  import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
1767
1774
 
1768
1775
  await runDevtoolsMcp(storybookProfile(${F}${I}));
@@ -1782,18 +1789,18 @@ await runDevtoolsMcp({
1782
1789
  version: ${JSON.stringify(C)},
1783
1790
  busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
1784
1791
  });
1785
- `}var mG,hG=__esmMin(()=>{_e(),Fd(),jn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),mG={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=xn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=xn(W,`entry.ts`),Y=t.out?vn(n,t.out):xn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(sK(),oK));if(await Z([`build`,q,`--app`,`gjs`,`--shebang`,`--globals`,I,`--outfile`,Y]),t.buildOnly){ge.error(`[gjsify debug] built ${Y}`);return}let{runGjsBundle:te}=await Promise.resolve().then(()=>(DI(),EI));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1792
+ `}var vG,yG=__esmMin(()=>{_e(),Fd(),jn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),vG={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=xn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=xn(W,`entry.ts`),Y=t.out?vn(n,t.out):xn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(dK(),uK));if(await Z([`build`,q,`--app`,`gjs`,`--shebang`,`--globals`,I,`--outfile`,Y]),t.buildOnly){ge.error(`[gjsify debug] built ${Y}`);return}let{runGjsBundle:te}=await Promise.resolve().then(()=>(DI(),EI));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1786
1793
  import system from 'system';
1787
1794
 
1788
1795
  import { runDevtoolsCli } from '@gjsify/devtools-mcp';
1789
1796
 
1790
1797
  system.exit(await runDevtoolsCli(system.programArgs));
1791
- `}var gG,_G=__esmMin(()=>{_e(),Fd(),jn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),gG={command:`devtools`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=xn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=xn(F,`entry.ts`),H=t.out?vn(n,t.out):xn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(sK(),oK));await q([`build`,I,`--app`,`gjs`,`--globals`,W,`--outfile`,H]);let Y=[t.operation,...t.operands??[],`--bus-name`,N];t.address&&Y.push(`--address`,t.address),t.instance&&Y.push(`--instance`,t.instance),Y.push(`--timeout`,String(t.timeout));let{runGjsBundle:X}=await Promise.resolve().then(()=>(DI(),EI));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
1798
+ `}var bG,xG=__esmMin(()=>{_e(),Fd(),jn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),bG={command:`devtools`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=xn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=xn(F,`entry.ts`),H=t.out?vn(n,t.out):xn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(dK(),uK));await q([`build`,I,`--app`,`gjs`,`--globals`,W,`--outfile`,H]);let Y=[t.operation,...t.operands??[],`--bus-name`,N];t.address&&Y.push(`--address`,t.address),t.instance&&Y.push(`--instance`,t.instance),Y.push(`--timeout`,String(t.timeout));let{runGjsBundle:X}=await Promise.resolve().then(()=>(DI(),EI));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
1792
1799
  import { runBrowserDevtools } from '@gjsify/devtools-browser';
1793
1800
 
1794
1801
  await runBrowserDevtools({
1795
1802
  applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
1796
1803
  });
1797
- `}var vG,yG=__esmMin(()=>{_e(),Fd(),jn(),vG={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=xn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?vn(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(sK(),oK));if(await te([`build`,X,`--app`,`gjs`,`--globals`,I,`--outfile`,Z]),t.buildOnly){ge.log(`[gjsify browse] built ${Z}`);return}q&&(process.env.GJSIFY_DEVTOOLS=`1`),W!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${W}`);let{runGjsBundle:ne}=await Promise.resolve().then(()=>(DI(),EI));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Tn(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Tn(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(xn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,xn(C,n));else for(let[n,S]of t.png)writeFileSync(xn(C,n),S)}var bG=__esmMin(()=>{Fd(),jn(),tB()});function isRecord$1(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function mergeManifest(t,n){let S={...t};for(let[t,C]of Object.entries(n))C===null?delete S[t]:isRecord$1(C)&&isRecord$1(S[t])?S[t]=mergeManifest(S[t],C):S[t]=C;return S}function applyTargetOverrides(t,n){let{$targets:S,...C}=t;if(S===void 0)return C;if(!isRecord$1(S))throw Error("gjsify webext: the manifest's `$targets` must be an object.");let N=S[n];if(N===void 0)return C;if(!isRecord$1(N))throw Error(`gjsify webext: \`$targets["${n}"]\` in the manifest must be an object.`);return mergeManifest(C,N)}async function composeManifest(t,n){let S=typeof t==`function`?await t(n):applyTargetOverrides(t,n.target);if(!isRecord$1(S))throw Error(`gjsify webext: the manifest for ${n.target} is not an object (got ${typeof S}).`);if(S.version!==void 0)return S;let C={};for(let[t,N]of Object.entries(S))C[t]=N,t===`name`&&(C.version=n.version);return C.version===void 0&&(C.version=n.version),C}async function loadManifestTemplate(t){if(/\.json$/i.test(t))try{return JSON.parse(readFileSync(t,`utf8`))}catch(n){throw Error(`gjsify webext: ${t} is not valid JSON: ${n.message}`)}let n,cleanup=null;if(isGjs()){let{BuildAction:S}=await Promise.resolve().then(()=>(eI(),ZF)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Tn(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=xn(wn(C),`manifest-${process.pid}-${++xG}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++xG}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(xn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(xn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(xn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var xG,SG=__esmMin(()=>{Fd(),jn(),Hn(),i_(),__name$1(isRecord$1,`isRecord`),xG=0});function planPage(t,n,S){let C=wn(n),N=[],F=[],local=t=>{if(kG.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return bn(n)?n:vn(C,n)},I=S.replace(CG,n=>{let S=TG.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!AG.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:DG.test(n)?`esm`:`iife`,output:F}),n.replace(TG,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(wG,t=>{if(!OG.test(t))return t;let n=EG.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Tn(S);return F.push({source:S,output:C}),t.replace(EG,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var CG,wG,TG,EG,DG,OG,kG,AG,jG=__esmMin(()=>{jn(),CG=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,wG=/<link\b[^>]*>/gi,TG=/\bsrc\s*=\s*(["'])([^"']+)\1/i,EG=/\bhref\s*=\s*(["'])([^"']+)\1/i,DG=/\btype\s*=\s*["']module["']/i,OG=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,kG=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,AG=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=MG?n:MG}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=xn(S,C.name);C.isDirectory()?walk(N):n.push({path:Sn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=xn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:xn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:xn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,xn(H,t.output))}writeFileSync(xn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=xn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,xn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(xn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
1798
- - `)}`);if(Z.folders.set(I.id,S),F(`built ${Sn(process.cwd(),S)||S}`),t.zip){let t=xn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Sn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var MG,NG=__esmMin(()=>{_e(),Fd(),jn(),uH(),bG(),SG(),jG(),MG=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!PG.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${PG.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?IG.get(S):void 0;if(N!==void 0)throw Error(`gjsify webext: target "${t}" does not exist any more: ${N}. Use ${S}-mv3.`);return{id:t,browser:S,manifestVersion:C}}function webExtRunTarget(t){return t.browser===`firefox`?`firefox-desktop`:t.browser===`chrome`||t.browser===`edge`||t.browser===`opera`?`chromium`:null}var PG,FG,IG,LG=__esmMin(()=>{PG=[`chrome`,`edge`,`firefox`,`opera`,`safari`],FG=[`chrome-mv3`,`firefox-mv3`],IG=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>bn(t)?t:vn(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...FG];if(!Array.isArray(H)||H.length===0)C.push("`targets` must be a non-empty array of target names.");else for(let t of H)try{I.some(n=>n.id===t)?C.push(`target "${t}" is listed twice.`):I.push(parseWebextTarget(String(t)))}catch(t){C.push(t.message.replace(/^gjsify webext: /,``))}let W=``;if(F.manifest!==void 0)W=need("`manifest`",F.manifest,`file`);else{let t=zG.find(t=>S(xn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${zG.join(`, `)} exists.`):W=xn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!BG.test(N)){C.push(`\`${t}.${N}\`: an output name is a plain file name (letters, digits, . _ -).`);continue}if(typeof F!=`string`){C.push(`\`${t}.${N}\` must be a path.`);continue}n.set(N,need(`\`${t}.${N}\``,F,`file`)),t===`scripts`?claim(`${N}.js`,`\`scripts.${N}\``):claim(`${N}.html`,`\`pages.${N}\``)}return n},Y=readEntries(`scripts`),X=readEntries(`pages`);Y.size===0&&X.size===0&&C.push("declare at least one entry under `scripts` or `pages`; there is nothing to build.");for(let t of X.keys())Y.has(t)&&C.push(`\`scripts.${t}\` and the script of \`pages.${t}\` both write ${t}.js.`);let Z=null;if(F.icons!==void 0)if(!isRecord(F.icons)||!isRecord(F.icons.sources))C.push("`icons` must be an object with a `sources` map (icon name → SVG).");else{let t=F.icons.sizes??RG;(!Array.isArray(t)||t.length===0||t.some(t=>!Number.isInteger(t)||t<=0))&&C.push("`icons.sizes` must be a non-empty list of positive integers.");let n=new Set(F.icons.svg??[]);for(let t of n)I.some(n=>n.id===t)||C.push(`\`icons.svg\` names "${t}", which is not one of this package's targets.`);let N=new Map;for(let[n,I]of Object.entries(F.icons.sources)){if(!BG.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=xn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${xn(n,`package.json`)}:\n - ${C.join(`
1799
- - `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var RG,zG,BG,VG=__esmMin(()=>{Fd(),jn(),LG(),RG=[16,32,48,128],zG=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],BG=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return xn(S.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=wn(n)){let t=xn(n,`node_modules`,`.bin`);if(existsSync(xn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(kn)}};if(wn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var HG,UG=__esmMin(()=>{Fd(),Ag(),jn(),nF(),LG(),HG="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(sK(),oK)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?vn(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=xn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+On)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var WG,GG,KG,qG,JG,YG,XG=__esmMin(()=>{_e(),Fd(),jn(),NG(),VG(),UG(),WG={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},GG={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},KG={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},qG={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,WG).option(`out-dir`,GG).option(`define`,KG).option(`mode`,{description:`Passed to the manifest as ctx.mode; development also skips minification.`,type:`string`,choices:[`production`,`development`],default:`production`}),handler:t=>runBuild(t,!1)},JG={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,WG).option(`out-dir`,GG).option(`define`,KG),handler:t=>runBuild(t,!0)},YG={command:`dev`,description:`Build one target in development mode, launch it in a browser via web-ext, and rebuild in place on change.`,builder:t=>t.option(`target`,{...WG,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,KG).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?vn(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=xn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(HG);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?vn(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(wn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(cG(),sG));W=await q(H.cmd,F,H.env),W.on(`exit`,t=>{ge.log(`[webext] browser closed (${t??0}) — stopping`),process.exit(0)})},{runWatchLoop:q}=await Promise.resolve().then(()=>(cG(),sG));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+On),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}}}),ZG,QG=__esmMin(()=>{XG(),ZG={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(qG.command,qG.description,qG.builder,qG.handler).command(JG.command,JG.description,JG.builder,JG.handler).command(YG.command,YG.description,YG.builder,YG.handler).demandCommand(1).strict()}});function blueprintsUnder(t,n){let S;try{S=statSync(t)}catch{return n}if(!S.isDirectory())return t.endsWith(`.blp`)&&n.push(t),n;for(let S of readdirSync(t).sort())$G.has(S)||S.startsWith(`.`)||blueprintsUnder(xn(t,S),n);return n}var $G,eK,formatFor,tK,nK=__esmMin(()=>{_e(),Fd(),jn(),wk(),jk(),$G=new Set([`node_modules`,`dist`,`lib`,`.git`]),eK=new Map,formatFor=t=>{let n=eK.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return eK.set(t,S),S},tK={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>bn(t)?t:vn(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Tn(n),formatFor(wn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),rK,iK=__esmMin(()=>{nK(),rK={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(tK.command,tK.description,tK.builder,tK.handler).demandCommand(1).strict()}}),aK=__esmMin(()=>{aI(),sI(),uI(),mI(),jI(),PI(),WL(),KL(),JL(),iR(),_R(),FR(),RR(),HR(),GR(),Nz(),WH(),pR(),XH(),$H(),iU(),nR(),lU(),BU(),HU(),GU(),qU(),$U(),aW(),fW(),hW(),_W(),yW(),OW(),AW(),MW(),RW(),UW(),GW(),oG(),uG(),pG(),hG(),_G(),yG(),QG(),iK()}),oK=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=zm(t);await n.scriptName(eh).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(PR.command,PR.description,PR.builder,PR.handler).command(JH.command,JH.description,JH.builder,JH.handler).command(ZH.command,ZH.description,ZH.builder,ZH.handler).command(QH.command,QH.description,QH.builder,QH.handler).command(iI.command,iI.description,iI.builder,iI.handler).command(oI.command,oI.description,oI.builder,oI.handler).command(lI.command,lI.description,lI.builder,lI.handler).command(pI.command,pI.description,pI.builder,pI.handler).command(AI.command,AI.description,AI.builder,AI.handler).command(NI.command,NI.description,NI.builder,NI.handler).command(UL.command,UL.description,UL.builder,UL.handler).command(fR.command,fR.description,fR.builder,fR.handler).command(GL.command,GL.description,GL.builder,GL.handler).command(qL.command,qL.description,qL.builder,qL.handler).command(rR.command,rR.description,rR.builder,rR.handler).command(gR.command,gR.description,gR.builder,gR.handler).command(LR.command,LR.description,LR.builder,LR.handler).command(VR.command,VR.description,VR.builder,VR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(Mz.command,Mz.description,Mz.builder,Mz.handler).command(UH.command,UH.description,UH.builder,UH.handler).command(rU.command,rU.description,rU.builder,rU.handler).command(tR.command,tR.description,tR.builder,tR.handler).command(oU.command,oU.description,oU.builder,oU.handler).command(zU.command,zU.description,zU.builder,zU.handler).command(VU.command,VU.description,VU.builder,VU.handler).command(WU.command,WU.description,WU.builder,WU.handler).command(KU.command,KU.description,KU.builder,KU.handler).command(QU.command,QU.description,QU.builder,QU.handler).command(iW.command,iW.description,iW.builder,iW.handler).command(uW.command,uW.description,uW.builder,uW.handler).command(mW.command,mW.description,mW.builder,mW.handler).command(vW.command,vW.description,vW.builder,vW.handler).command(gW.command,gW.description,gW.builder,gW.handler).command(FW.command,FW.description,FW.builder,FW.handler).command(DW.command,DW.description,DW.builder,DW.handler).command(kW.command,kW.description,kW.builder,kW.handler).command(jW.command,jW.description,jW.builder,jW.handler).command(HW.command,HW.description,HW.builder,HW.handler).command(WW.command,WW.description,WW.builder,WW.handler).command(iG.command,iG.description,iG.builder,iG.handler).command(lG.command,lG.description,lG.builder,lG.handler).command(fG.command,fG.description,fG.builder,fG.handler).command(mG.command,mG.description,mG.builder,mG.handler).command(gG.command,gG.description,gG.builder,gG.handler).command(vG.command,vG.description,vG.builder,vG.handler).command(ZG.command,ZG.description,ZG.builder,ZG.handler).command(rK.command,rK.description,rK.builder,rK.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var sK=__esmMin(()=>{Bm(),Vm(),$m(),aK(),th(),i_(),BL()});sK(),i_(),HL();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),i_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const cK=globalThis.process,lK=Number(cK?.exitCode);Number.isInteger(lK)&&lK!==0&&cK.exit(lK);
1804
+ `}var SG,CG=__esmMin(()=>{_e(),Fd(),jn(),SG={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=xn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?vn(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(dK(),uK));if(await te([`build`,X,`--app`,`gjs`,`--globals`,I,`--outfile`,Z]),t.buildOnly){ge.log(`[gjsify browse] built ${Z}`);return}q&&(process.env.GJSIFY_DEVTOOLS=`1`),W!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${W}`);let{runGjsBundle:ne}=await Promise.resolve().then(()=>(DI(),EI));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Tn(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Tn(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(xn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,xn(C,n));else for(let[n,S]of t.png)writeFileSync(xn(C,n),S)}var wG=__esmMin(()=>{Fd(),jn(),tB()});function isRecord$1(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function mergeManifest(t,n){let S={...t};for(let[t,C]of Object.entries(n))C===null?delete S[t]:isRecord$1(C)&&isRecord$1(S[t])?S[t]=mergeManifest(S[t],C):S[t]=C;return S}function applyTargetOverrides(t,n){let{$targets:S,...C}=t;if(S===void 0)return C;if(!isRecord$1(S))throw Error("gjsify webext: the manifest's `$targets` must be an object.");let N=S[n];if(N===void 0)return C;if(!isRecord$1(N))throw Error(`gjsify webext: \`$targets["${n}"]\` in the manifest must be an object.`);return mergeManifest(C,N)}async function composeManifest(t,n){let S=typeof t==`function`?await t(n):applyTargetOverrides(t,n.target);if(!isRecord$1(S))throw Error(`gjsify webext: the manifest for ${n.target} is not an object (got ${typeof S}).`);if(S.version!==void 0)return S;let C={};for(let[t,N]of Object.entries(S))C[t]=N,t===`name`&&(C.version=n.version);return C.version===void 0&&(C.version=n.version),C}async function loadManifestTemplate(t){if(/\.json$/i.test(t))try{return JSON.parse(readFileSync(t,`utf8`))}catch(n){throw Error(`gjsify webext: ${t} is not valid JSON: ${n.message}`)}let n,cleanup=null;if(isGjs()){let{BuildAction:S}=await Promise.resolve().then(()=>(eI(),ZF)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Tn(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=xn(wn(C),`manifest-${process.pid}-${++TG}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++TG}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(xn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(xn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(xn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var TG,EG=__esmMin(()=>{Fd(),jn(),Hn(),i_(),__name$1(isRecord$1,`isRecord`),TG=0});function planPage(t,n,S){let C=wn(n),N=[],F=[],local=t=>{if(NG.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return bn(n)?n:vn(C,n)},I=S.replace(DG,n=>{let S=kG.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!PG.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:jG.test(n)?`esm`:`iife`,output:F}),n.replace(kG,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(OG,t=>{if(!MG.test(t))return t;let n=AG.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Tn(S);return F.push({source:S,output:C}),t.replace(AG,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var DG,OG,kG,AG,jG,MG,NG,PG,FG=__esmMin(()=>{jn(),DG=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,OG=/<link\b[^>]*>/gi,kG=/\bsrc\s*=\s*(["'])([^"']+)\1/i,AG=/\bhref\s*=\s*(["'])([^"']+)\1/i,jG=/\btype\s*=\s*["']module["']/i,MG=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,NG=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,PG=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=IG?n:IG}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=xn(S,C.name);C.isDirectory()?walk(N):n.push({path:Sn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=xn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:xn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:xn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,xn(H,t.output))}writeFileSync(xn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=xn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,xn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(xn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
1805
+ - `)}`);if(Z.folders.set(I.id,S),F(`built ${Sn(process.cwd(),S)||S}`),t.zip){let t=xn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Sn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var IG,LG=__esmMin(()=>{_e(),Fd(),jn(),uH(),wG(),EG(),FG(),IG=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!RG.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${RG.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?BG.get(S):void 0;if(N!==void 0)throw Error(`gjsify webext: target "${t}" does not exist any more: ${N}. Use ${S}-mv3.`);return{id:t,browser:S,manifestVersion:C}}function webExtRunTarget(t){return t.browser===`firefox`?`firefox-desktop`:t.browser===`chrome`||t.browser===`edge`||t.browser===`opera`?`chromium`:null}var RG,zG,BG,VG=__esmMin(()=>{RG=[`chrome`,`edge`,`firefox`,`opera`,`safari`],zG=[`chrome-mv3`,`firefox-mv3`],BG=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>bn(t)?t:vn(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...zG];if(!Array.isArray(H)||H.length===0)C.push("`targets` must be a non-empty array of target names.");else for(let t of H)try{I.some(n=>n.id===t)?C.push(`target "${t}" is listed twice.`):I.push(parseWebextTarget(String(t)))}catch(t){C.push(t.message.replace(/^gjsify webext: /,``))}let W=``;if(F.manifest!==void 0)W=need("`manifest`",F.manifest,`file`);else{let t=UG.find(t=>S(xn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${UG.join(`, `)} exists.`):W=xn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!WG.test(N)){C.push(`\`${t}.${N}\`: an output name is a plain file name (letters, digits, . _ -).`);continue}if(typeof F!=`string`){C.push(`\`${t}.${N}\` must be a path.`);continue}n.set(N,need(`\`${t}.${N}\``,F,`file`)),t===`scripts`?claim(`${N}.js`,`\`scripts.${N}\``):claim(`${N}.html`,`\`pages.${N}\``)}return n},Y=readEntries(`scripts`),X=readEntries(`pages`);Y.size===0&&X.size===0&&C.push("declare at least one entry under `scripts` or `pages`; there is nothing to build.");for(let t of X.keys())Y.has(t)&&C.push(`\`scripts.${t}\` and the script of \`pages.${t}\` both write ${t}.js.`);let Z=null;if(F.icons!==void 0)if(!isRecord(F.icons)||!isRecord(F.icons.sources))C.push("`icons` must be an object with a `sources` map (icon name → SVG).");else{let t=F.icons.sizes??HG;(!Array.isArray(t)||t.length===0||t.some(t=>!Number.isInteger(t)||t<=0))&&C.push("`icons.sizes` must be a non-empty list of positive integers.");let n=new Set(F.icons.svg??[]);for(let t of n)I.some(n=>n.id===t)||C.push(`\`icons.svg\` names "${t}", which is not one of this package's targets.`);let N=new Map;for(let[n,I]of Object.entries(F.icons.sources)){if(!WG.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=xn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${xn(n,`package.json`)}:\n - ${C.join(`
1806
+ - `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var HG,UG,WG,GG=__esmMin(()=>{Fd(),jn(),VG(),HG=[16,32,48,128],UG=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],WG=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return xn(S.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=wn(n)){let t=xn(n,`node_modules`,`.bin`);if(existsSync(xn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(kn)}};if(wn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var KG,qG=__esmMin(()=>{Fd(),Ag(),jn(),nF(),VG(),KG="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(dK(),uK)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?vn(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=xn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+On)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var JG,YG,XG,ZG,QG,$G,eK=__esmMin(()=>{_e(),Fd(),jn(),LG(),GG(),qG(),JG={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},YG={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},XG={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},ZG={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,JG).option(`out-dir`,YG).option(`define`,XG).option(`mode`,{description:`Passed to the manifest as ctx.mode; development also skips minification.`,type:`string`,choices:[`production`,`development`],default:`production`}),handler:t=>runBuild(t,!1)},QG={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,JG).option(`out-dir`,YG).option(`define`,XG),handler:t=>runBuild(t,!0)},$G={command:`dev`,description:`Build one target in development mode, launch it in a browser via web-ext, and rebuild in place on change.`,builder:t=>t.option(`target`,{...JG,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,XG).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?vn(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=xn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(KG);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?vn(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(wn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(uG(),lG));W=await q(H.cmd,F,H.env),W.on(`exit`,t=>{ge.log(`[webext] browser closed (${t??0}) — stopping`),process.exit(0)})},{runWatchLoop:q}=await Promise.resolve().then(()=>(uG(),lG));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+On),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}}}),tK,nK=__esmMin(()=>{eK(),tK={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(ZG.command,ZG.description,ZG.builder,ZG.handler).command(QG.command,QG.description,QG.builder,QG.handler).command($G.command,$G.description,$G.builder,$G.handler).demandCommand(1).strict()}});function blueprintsUnder(t,n){let S;try{S=statSync(t)}catch{return n}if(!S.isDirectory())return t.endsWith(`.blp`)&&n.push(t),n;for(let S of readdirSync(t).sort())rK.has(S)||S.startsWith(`.`)||blueprintsUnder(xn(t,S),n);return n}var rK,iK,formatFor,aK,oK=__esmMin(()=>{_e(),Fd(),jn(),wk(),jk(),rK=new Set([`node_modules`,`dist`,`lib`,`.git`]),iK=new Map,formatFor=t=>{let n=iK.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return iK.set(t,S),S},aK={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>bn(t)?t:vn(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Tn(n),formatFor(wn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),sK,cK=__esmMin(()=>{oK(),sK={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(aK.command,aK.description,aK.builder,aK.handler).demandCommand(1).strict()}}),lK=__esmMin(()=>{aI(),sI(),uI(),mI(),jI(),PI(),WL(),KL(),JL(),iR(),_R(),FR(),RR(),HR(),GR(),Nz(),WH(),pR(),XH(),$H(),iU(),nR(),lU(),BU(),HU(),GU(),qU(),$U(),aW(),pW(),gW(),vW(),bW(),kW(),jW(),NW(),BW(),GW(),qW(),cG(),fG(),mG(),_G(),yG(),xG(),CG(),nK(),cK()}),uK=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=zm(t);await n.scriptName(eh).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(PR.command,PR.description,PR.builder,PR.handler).command(JH.command,JH.description,JH.builder,JH.handler).command(ZH.command,ZH.description,ZH.builder,ZH.handler).command(QH.command,QH.description,QH.builder,QH.handler).command(iI.command,iI.description,iI.builder,iI.handler).command(oI.command,oI.description,oI.builder,oI.handler).command(lI.command,lI.description,lI.builder,lI.handler).command(pI.command,pI.description,pI.builder,pI.handler).command(AI.command,AI.description,AI.builder,AI.handler).command(NI.command,NI.description,NI.builder,NI.handler).command(UL.command,UL.description,UL.builder,UL.handler).command(fR.command,fR.description,fR.builder,fR.handler).command(GL.command,GL.description,GL.builder,GL.handler).command(qL.command,qL.description,qL.builder,qL.handler).command(rR.command,rR.description,rR.builder,rR.handler).command(gR.command,gR.description,gR.builder,gR.handler).command(LR.command,LR.description,LR.builder,LR.handler).command(VR.command,VR.description,VR.builder,VR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(Mz.command,Mz.description,Mz.builder,Mz.handler).command(UH.command,UH.description,UH.builder,UH.handler).command(rU.command,rU.description,rU.builder,rU.handler).command(tR.command,tR.description,tR.builder,tR.handler).command(oU.command,oU.description,oU.builder,oU.handler).command(zU.command,zU.description,zU.builder,zU.handler).command(VU.command,VU.description,VU.builder,VU.handler).command(WU.command,WU.description,WU.builder,WU.handler).command(KU.command,KU.description,KU.builder,KU.handler).command(QU.command,QU.description,QU.builder,QU.handler).command(iW.command,iW.description,iW.builder,iW.handler).command(dW.command,dW.description,dW.builder,dW.handler).command(hW.command,hW.description,hW.builder,hW.handler).command(yW.command,yW.description,yW.builder,yW.handler).command(_W.command,_W.description,_W.builder,_W.handler).command(IW.command,IW.description,IW.builder,IW.handler).command(OW.command,OW.description,OW.builder,OW.handler).command(AW.command,AW.description,AW.builder,AW.handler).command(MW.command,MW.description,MW.builder,MW.handler).command(WW.command,WW.description,WW.builder,WW.handler).command(KW.command,KW.description,KW.builder,KW.handler).command(oG.command,oG.description,oG.builder,oG.handler).command(dG.command,dG.description,dG.builder,dG.handler).command(pG.command,pG.description,pG.builder,pG.handler).command(gG.command,gG.description,gG.builder,gG.handler).command(vG.command,vG.description,vG.builder,vG.handler).command(bG.command,bG.description,bG.builder,bG.handler).command(SG.command,SG.description,SG.builder,SG.handler).command(tK.command,tK.description,tK.builder,tK.handler).command(sK.command,sK.description,sK.builder,sK.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var dK=__esmMin(()=>{Bm(),Vm(),$m(),lK(),th(),i_(),BL()});dK(),i_(),HL();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),i_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const fK=globalThis.process,pK=Number(fK?.exitCode);Number.isInteger(pK)&&pK!==0&&fK.exit(pK);