@gjsify/cli 0.64.53 → 0.64.55

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
@@ -6,12 +6,12 @@ if(globalThis.__gjsifyBundleUrl??=import.meta.url,Symbol.dispose||(Symbol.dispos
6
6
  `)}else if(de){let S=` `.repeat(this._groupDepth*this._groupIndentation)+_formatArgs(...n);t===`stderr`?printerr(S):print(S)}else{let S=globalThis.console;t===`stderr`?S.error(...n):S.log(...n)}}log(...t){this._write(`stdout`,...t)}info(...t){this._write(`stdout`,...t)}debug(...t){this._write(`stdout`,...t)}warn(...t){this._write(`stderr`,...t)}error(...t){this._write(`stderr`,...t)}dir(t,n){this._write(`stdout`,t)}dirxml(...t){this.log(...t)}assert(t,...n){t||this.error(`Assertion failed:`,...n)}clear(){this._stdout?this._stdout.write(`\x1Bc`):de?print(`\x1Bc`):globalThis.console.clear()}count(t=`default`){let n=(this._counters.get(t)||0)+1;this._counters.set(t,n),this.log(`${t}: ${n}`)}countReset(t=`default`){this._counters.delete(t)}group(...t){t.length>0&&this.log(...t),this._groupDepth++}groupCollapsed(...t){this.group(...t)}groupEnd(){this._groupDepth>0&&this._groupDepth--}table(t,n){this._stdout?this._write(`stdout`,t):de?print(JSON.stringify(t,null,2)):globalThis.console.table(t,n)}time(t=`default`){this._timers.set(t,Date.now())}timeEnd(t=`default`){let n=this._timers.get(t);n===void 0?this.warn(`Warning: No such label '${t}' for console.timeEnd()`):(this.log(`${t}: ${Date.now()-n}ms`),this._timers.delete(t))}timeLog(t=`default`,...n){let S=this._timers.get(t);S===void 0?this.warn(`Warning: No such label '${t}' for console.timeLog()`):this.log(`${t}: ${Date.now()-S}ms`,...n)}trace(...t){let n=Error().stack?.split(`
7
7
  `).slice(1).join(`
8
8
  `)||``;this._write(`stderr`,`Trace:`,...t,`
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 decodeXmlEntities(t){return t.includes(`&`)?t.replace(/&(#[Xx][0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g,(t,n)=>{if(n.charAt(0)!==`#`)return Se[n]??t;let S=n.charAt(1)===`x`||n.charAt(1)===`X`,C=Number.parseInt(S?n.slice(2):n.slice(1),S?16:10);return!Number.isFinite(C)||C<1||C>1114111||C>=55296&&C<=57343?t:String.fromCodePoint(C)}):t}function findTagEnd(t,n){let S=``;for(let C=n+1;C<t.length;C++){let n=t.charAt(C);if(S)n===S&&(S=``);else if(n===`"`||n===`'`)S=n;else if(n===`>`)return C}return-1}function parseAttributes(t){let n={};Ce.lastIndex=0;let S=Ce.exec(t);for(;S!==null;)S[1]in n||(n[S[1]]=decodeXmlEntities(S[2]??S[3]??``)),S=Ce.exec(t);return n}function scanXml(t){let n=[],pushText=t=>{n.push({kind:`text`,text:decodeXmlEntities(t)})},S=0;for(;S<t.length;){let C=t.indexOf(`<`,S);if(C<0){pushText(t.slice(S));break}if(C>S&&pushText(t.slice(S,C)),t.startsWith(`<!--`,C)){let n=t.indexOf(`-->`,C+4);S=n<0?t.length:n+3;continue}if(t.startsWith(`<![CDATA[`,C)){let N=t.indexOf(`]]>`,C+9);n.push({kind:`text`,text:t.slice(C+9,N<0?t.length:N)}),S=N<0?t.length:N+3;continue}if(t.startsWith(`<?`,C)){let n=t.indexOf(`?>`,C+2);S=n<0?t.length:n+2;continue}if(t.startsWith(`<!`,C)){let n=t.indexOf(`>`,C+2);S=n<0?t.length:n+1;continue}let N=findTagEnd(t,C);if(N<0){pushText(t.slice(C));break}let F=t.slice(C+1,N);if(S=N+1,F.charAt(0)===`/`){let t=F.slice(1).trim();t!==``&&n.push({kind:`close`,name:t});continue}let I=F,H=!1;I.endsWith(`/`)&&(H=!0,I=I.slice(0,-1));let W=/^([^\s/<>]+)/.exec(I);if(W===null)continue;let q=W[1];n.push({kind:`open`,name:q,attributes:parseAttributes(I.slice(q.length)),selfClosing:H})}return n}var Se,Ce,we=__esmMin(()=>{Se={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`},Ce=/([^\s=/<>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g});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 Te=__esmMin(()=>{});function classOf(t){return Ee.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&&De[C]||De[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(Oe.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(Oe.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 Ee,De,Oe,ke=__esmMin(()=>{({toString:Ee}=Object.prototype),De={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Oe=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(Ae!==null)return Ae>0?Ae: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 Ae=Number.isInteger(n)&&n>0?n:0,Ae>0?Ae: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
- `)){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 Ae,je=__esmMin(()=>{Ae=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib$1(){let t=globalThis;if(typeof t.process?.versions?.gjs==`string`||t.process===void 0)return t.imports?.gi?.GLib}function arm(t){Ie||(Ie=!0,t.runAsync().catch(()=>{}))}function ensureMainLoop(){return Re=!1,createLoop()}function createLoop(){let t=glib$1();if(t)return Fe?Me:(Me=new t.MainLoop(null,!1),Fe=!0,t.main_depth()===0&&arm(Me),Me)}function holdMainLoop(){let t=ensureMainLoop();return t&&arm(t),t}function acquireMainLoop(){let t=Fe,n=createLoop();if(n)return Le===0&&!Ve&&(Re=!t),Le+=1,n}function releaseMainLoop(){Le===0||!Me||(--Le,drainIfIdle())}function trackTimer(){ze+=1}function untrackTimer(){dropPending()}function trackRequest(){ze+=1}function untrackRequest(){dropPending()}function trackedCallback(t){return trackRequest(),(...n)=>{try{t(...n)}finally{untrackRequest()}}}function dropPending(){ze!==0&&(--ze,ze===0&&drainIfIdle())}function drainIfIdle(){if(Le!==0||!Me||!Re)return;let t=Me;if(!Ie){quitMainLoop();return}if(ze!==0){Ve=!0;return}if(!t.is_running()){Ve=!0,awaitEntrySettle(t);return}exitParked()}function awaitEntrySettle(t){let n=glib$1();!n||He||(He=!0,n.timeout_add(n.PRIORITY_DEFAULT,20,()=>Me!==t||Le!==0||ze!==0?(He=!1,n.SOURCE_REMOVE):t.is_running()?(He=!1,exitParked(),n.SOURCE_REMOVE):n.SOURCE_CONTINUE))}function exitParked(){let t=globalThis.process,n=glib$1();if(typeof t?.exit!=`function`||!n){quitMainLoop(),t?.exit?.(t.exitCode??0);return}if(Be)return;Be=!0;let S=Me;n.timeout_add(n.PRIORITY_DEFAULT,0,()=>{if(Be=!1,Me!==S||Le!==0)return n.SOURCE_REMOVE;if(ze!==0)return Ve=!0,n.SOURCE_REMOVE;let C=t.exitCode??0;return quitMainLoop(),t.exit(C),n.SOURCE_REMOVE})}function quitMainLoop(){Me&&(Me.quit(),Fe=!1,Ie=!1,Me=null,Le=0,Re=!1,Ve=!1)}var Me,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue=__esmMin(()=>{Me=null,Fe=!1,Ie=!1,Le=0,Re=!1,ze=0,Be=!1,Ve=!1,He=!1,__name$1(glib$1,`glib`)});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,Ge=__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 setDrainerArmed(t){qe!==t&&(qe=t,t?trackRequest():untrackRequest())}function drainOnce(t){let n=Math.min(64,Ke.length);for(let S=0;S<n;S++){let n=Ke.shift();try{n()}catch(n){try{t.log_default_handler(`gjsify-nextTick`,t.LogLevelFlags.LEVEL_WARNING,String(n?.stack||n),null)}catch{}}}Ke.length>0?t.timeout_add(t.PRIORITY_DEFAULT,1,()=>(drainOnce(t),!1)):setDrainerArmed(!1)}function tryGLibTimeout(t){let n=globalThis.imports?.gi?.GLib;return n?.timeout_add?(Ke.push(t),qe||(setDrainerArmed(!0),n.timeout_add(n.PRIORITY_DEFAULT,0,()=>(drainOnce(n),!1))),!0):!1}var Ke,qe,nextTick,Je=__esmMin(()=>{Ue(),Ke=[],qe=!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)}}}),Ye=__esmMin(()=>{ie(),oe(),se(),ce(),ue(),ye(),xe(),we(),Te(),ke(),je(),Ue(),Ge(),Je()});re(),Ye(),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|Ze[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+=Xe[C>>18&63]+Xe[C>>12&63]+Xe[C>>6&63]+Xe[C&63]}if(S+1===t.length){let C=t.charCodeAt(S)<<16;n+=Xe[C>>18&63]+Xe[C>>12&63]+`==`}else if(S+2===t.length){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8;n+=Xe[C>>18&63]+Xe[C>>12&63]+Xe[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|Ze[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+=Xe[N>>2],n+=Xe[(N&3)<<4|F>>4],n+=C+1<S?Xe[(F&15)<<2|I>>6]:`=`,n+=C+2<S?Xe[I&63]:`=`}return n}var Xe,Ze,Qe=__esmMin(()=>{Xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ze=new Uint8Array(256);for(let t=0;t<64;t++)Ze[Xe.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(!$e.includes(n))throw TypeError(`Unknown encoding: ${t}`)}var $e,et=__esmMin(()=>{$e=[`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 tt,nt,textEncoder,textDecoder,rt=__esmMin(()=>{Qe(),textEncoder=()=>tt??=new TextEncoder,textDecoder=()=>nt??=new TextDecoder}),it,ot,st,ct,lt,SlowBuffer,ut=__esmMin(()=>{rt(),et(),it=typeof SharedArrayBuffer<`u`,ot=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(it&&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||it&&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}},st=2**31-1,ct=2**28-16,lt={MAX_LENGTH:st,MAX_STRING_LENGTH:ct},SlowBuffer=class extends ot{constructor(t){super(t)}}}),dt=__exportAll$5({Blob:()=>te,Buffer:()=>ot,File:()=>ne,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>ft,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>pt,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>lt,default:()=>mt,kMaxLength:()=>st,kStringMaxLength:()=>ct,normalizeEncoding:()=>normalizeEncoding}),ft,pt,mt,ht=__esmMin(()=>{Qe(),re(),et(),ut(),ft=globalThis.atob,pt=globalThis.btoa,mt={Buffer:ot,SlowBuffer,Blob:te,File:ne,atob:ft,btoa:pt,kMaxLength:st,kStringMaxLength:ct,constants:lt,INSPECT_MAX_BYTES:50}});ht(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:ot,enumerable:!1,writable:!0,configurable:!0});var gt,_t=__esmMin(()=>{gt=t}),vt,yt=__esmMin(()=>{_t(),vt=gt});yt(),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 vt.base64_encode(n)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(t){let n=String(t).replace(/[\t\n\f\r ]/g,``);n.length%4!=0&&!n.includes(`=`)&&(n+=`=`.repeat(4-n.length%4));let S=vt.base64_decode(n),C=``;for(let t=0;t<S.length;t++)C+=String.fromCharCode(S[t]);return C},enumerable:!0,writable:!0,configurable:!0}),Ye(),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 bt=__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()-xt,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()-xt}var xt,St=__esmMin(()=>{bt(),xt=getMonotonicTime()});function probeUname(){if(Ct!==void 0)return Ct;Ct=null;try{let t=getGjsGlobal().imports?.gi?.GLib;if(!t)return Ct;let n=t.spawn_sync,S=t.SpawnFlags?.SEARCH_PATH;if(!n||S===void 0)return Ct;let[C,N]=n(null,[`uname`,`-sm`],null,S,null);if(!C||!N)return Ct;let F=new TextDecoder().decode(N).trim().split(/\s+/);if(F.length<2)return Ct;let I=mapSysname(F[0]),H=mapMachine(F[F.length-1]);if(!I||!H)return Ct;Ct={platform:I,arch:H}}catch{}return Ct}var Ct,wt=__esmMin(()=>{bt(),Ye()});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 Tt=__esmMin(()=>{bt(),wt(),Ye(),__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`)}function getExecArgv(){if(!isGjsHost()){let t=globalThis.process;return Array.isArray(t?.execArgv)?t.execArgv:[]}try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.file_get_contents){let[,n]=t.file_get_contents(`/proc/self/cmdline`);if(n){let t=n instanceof Uint8Array?n:new Uint8Array(n),S=new TextDecoder().decode(t).split(`\0`).filter(t=>t.length>0),C=[];for(let t=1;t<S.length&&S[t].startsWith(`-`);t++)C.push(S[t]);return C}}}catch{}return[]}var Et=__esmMin(()=>{bt(),Ye()});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 Dt=__esmMin(()=>{bt()});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}function readId$1(t){let n=getGjsGlobal().imports?.gi?.GLib;if(!n)throw Error(`process.get${t}: GLib is not available`);try{let[S,C]=n.file_get_contents(`/proc/self/status`);if(S){let{line:n,column:S}=Ot[t],N=RegExp(`^${n}:\\s*(\\d+)\\s+(\\d+)`,`m`).exec(new TextDecoder().decode(C));if(N)return parseInt(N[S+1],10)}}catch{}let S=At.get(t);if(S!==void 0)return S;let[C,N]=n.spawn_sync(null,[`id`,...kt[t]],null,4,null),F=C&&N?new TextDecoder().decode(N).trim():``;if(!/^\d+$/.test(F))throw Error(`process.get${t}: could not determine the id (no /proc, no id(1))`);let I=parseInt(F,10);return At.set(t,I),I}var Ot,kt,At,jt=__esmMin(()=>{bt(),Ye(),__name$1(isGjs$1,`isGjs`),Ot={uid:{line:`Uid`,column:0},euid:{line:`Uid`,column:1},gid:{line:`Gid`,column:0},egid:{line:`Gid`,column:1}},kt={uid:[`-ru`],euid:[`-u`],gid:[`-rg`],egid:[`-g`]},At=new Map,__name$1(readId$1,`readId`)});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 Mt}function armSignal(t,n){if(Nt.has(t))return;let S=Mt[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));Nt.set(t,I)}function disarmSignal(t){let n=Nt.get(t);if(n===void 0)return;Nt.delete(t);let S=getGjsGlobal().imports?.gi?.GLib;S&&typeof S.source_remove==`function`&&S.source_remove(n)}var Mt,Nt,Pt=__esmMin(()=>{bt(),Mt={SIGHUP:1,SIGINT:2,SIGTERM:15},Nt=new Map});function claimRawMode(t,n){Lt.set(t,n)}function releaseRawMode(t){Lt.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=[...Lt.entries()];Lt.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 Ft,It,Lt,Rt=__esmMin(()=>{Ft=Symbol.for(`@gjsify/terminal-native:raw-mode-claims`),It=globalThis,Lt=It[Ft]??=new Map});function callableModule(){if(!Bt)return null;try{return Bt.Terminal.is_tty(2),Bt}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 zt,Bt,Vt,Ht=__esmMin(()=>{Rt(),Ye(),zt=loadOptionalNativeModule(`GjsifyTerminal`,[`Terminal`,`ResizeWatcher`]),Bt=zt.module,Vt=Bt});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 Ut,Wt,Gt,Kt=__esmMin(()=>{_e(),Ut=Symbol(`kCapture`),Wt=Symbol.for(`nodejs.rejection`),Gt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=Wt;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;[Ut];constructor(t){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[Ut]=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[Ut]&&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[Ut]&&this._addCatch(C,t,n)}}return!0}_addCatch(t,n,S){typeof t?.then==`function`&&t.then(void 0,t=>{let C=this[Wt];if(typeof C==`function`)C.call(this,t,n,...S);else{let n=this[Ut];try{this[Ut]=!1,this.emit(`error`,t)}finally{this[Ut]=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)}}}},Gt.EventEmitter=Gt;for(let t of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let n=Gt.prototype[t];typeof n==`function`&&Object.defineProperty(Gt.prototype,t,{enumerable:!0,configurable:!0,writable:!0,value:n})}Object.defineProperty(Gt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Gt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Gt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),qt=__exportAll$5({EventEmitter:()=>Jt,addAbortListener:()=>an,captureRejectionSymbol:()=>Yt,default:()=>Jt,defaultMaxListeners:()=>Zt,errorMonitor:()=>Xt,getEventListeners:()=>nn,getMaxListeners:()=>$t,listenerCount:()=>rn,"module.exports":()=>Jt,on:()=>tn,once:()=>en,setMaxListeners:()=>Qt}),Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn,rn,an,on=__esmMin(()=>{Kt(),Ye(),Jt=makeCallable(Gt),Jt.EventEmitter=Jt,Yt=Jt.captureRejectionSymbol,Xt=Jt.errorMonitor,Zt=Jt.defaultMaxListeners,Qt=Jt.setMaxListeners,$t=Jt.getMaxListeners,en=Jt.once,tn=Jt.on,nn=Jt.getEventListeners,rn=Jt.listenerCount,an=Jt.addAbortListener}),sn=__exportAll$5({StringDecoder:()=>cn,default:()=>ln});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 cn,ln,un=__esmMin(()=>{ht(),cn=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},cn.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)}},cn.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},ln={StringDecoder:cn}}),dn,ProcessWriteStream,ProcessReadStream,fn=__esmMin(()=>{_e(),bt(),Ht(),on(),Ye(),un(),dn=new TextEncoder,ProcessWriteStream=class extends Jt{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`?dn.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 Jt{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 cn(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}[Symbol.asyncIterator](){let t=[],n=!1,S=null,C=null,notify=()=>{let t=C;C=null,t?.()},onData=n=>{t.push(n),notify()},onEnd=()=>{n=!0,notify()},onError=t=>{S=t instanceof Error?t:Error(String(t)),notify()},stop=()=>{this.off(`data`,onData),this.off(`end`,onEnd),this.off(`error`,onError)};return this.on(`error`,onError),this.on(`end`,onEnd),this.on(`data`,onData),{next:async()=>{for(;;){if(t.length>0)return{value:t.shift(),done:!1};if(S)throw stop(),S;if(n)return stop(),{value:void 0,done:!0};await new Promise(t=>{C=t})}},return:async()=>(stop(),{value:void 0,done:!0}),[Symbol.asyncIterator](){return this}}}_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 pn,Process,mn=__esmMin(()=>{_e(),Tt(),Et(),Dt(),St(),jt(),Pt(),fn(),Ht(),on(),pn=Date.now(),Process=class extends Jt{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=getExecArgv(),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()-pn)/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;getuid(){return readId$1(`uid`)}geteuid(){return readId$1(`euid`)}getgid(){return readId$1(`gid`)}getegid(){return readId$1(`egid`)}emitWarning(t,n){ge.warn(typeof t==`string`?`(${n||`Warning`}): ${t}`:t.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}});function gi(){let t=globalThis.imports?.gi;if(!t?.Gio||!t.GLib)throw Error(`@gjsify/ipc-channel needs a GJS host (imports.gi)`);return{Gio:t.Gio,GLib:t.GLib}}var gio,glib,hn=__esmMin(()=>{gio=()=>gi().Gio,glib=()=>gi().GLib}),gn,LineChannel,_n=__esmMin(()=>{hn(),gn=new TextEncoder,LineChannel=class{_output;_input;constructor(t,n=null){this._output=t,this._input=n?gio().DataInputStream.new(n):null}get writable(){return this._output!==null}writeLine(t){if(!this._output)throw Error(`LineChannel: output is closed`);this._output.write_all(gn.encode(t),null)}send(t){this.writeLine(JSON.stringify(t)+`
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 decodeXmlEntities(t){return t.includes(`&`)?t.replace(/&(#[Xx][0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g,(t,n)=>{if(n.charAt(0)!==`#`)return Se[n]??t;let S=n.charAt(1)===`x`||n.charAt(1)===`X`,C=Number.parseInt(S?n.slice(2):n.slice(1),S?16:10);return!Number.isFinite(C)||C<1||C>1114111||C>=55296&&C<=57343?t:String.fromCodePoint(C)}):t}function findTagEnd(t,n){let S=``;for(let C=n+1;C<t.length;C++){let n=t.charAt(C);if(S)n===S&&(S=``);else if(n===`"`||n===`'`)S=n;else if(n===`>`)return C}return-1}function parseAttributes(t){let n={};Ce.lastIndex=0;let S=Ce.exec(t);for(;S!==null;)S[1]in n||(n[S[1]]=decodeXmlEntities(S[2]??S[3]??``)),S=Ce.exec(t);return n}function scanXml(t){let n=[],pushText=t=>{n.push({kind:`text`,text:decodeXmlEntities(t)})},S=0;for(;S<t.length;){let C=t.indexOf(`<`,S);if(C<0){pushText(t.slice(S));break}if(C>S&&pushText(t.slice(S,C)),t.startsWith(`<!--`,C)){let n=t.indexOf(`-->`,C+4);S=n<0?t.length:n+3;continue}if(t.startsWith(`<![CDATA[`,C)){let N=t.indexOf(`]]>`,C+9);n.push({kind:`text`,text:t.slice(C+9,N<0?t.length:N)}),S=N<0?t.length:N+3;continue}if(t.startsWith(`<?`,C)){let n=t.indexOf(`?>`,C+2);S=n<0?t.length:n+2;continue}if(t.startsWith(`<!`,C)){let n=t.indexOf(`>`,C+2);S=n<0?t.length:n+1;continue}let N=findTagEnd(t,C);if(N<0){pushText(t.slice(C));break}let F=t.slice(C+1,N);if(S=N+1,F.charAt(0)===`/`){let t=F.slice(1).trim();t!==``&&n.push({kind:`close`,name:t});continue}let I=F,H=!1;I.endsWith(`/`)&&(H=!0,I=I.slice(0,-1));let W=/^([^\s/<>]+)/.exec(I);if(W===null)continue;let q=W[1];n.push({kind:`open`,name:q,attributes:parseAttributes(I.slice(q.length)),selfClosing:H})}return n}var Se,Ce,we=__esmMin(()=>{Se={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`},Ce=/([^\s=/<>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g});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 Te=__esmMin(()=>{});function classOf(t){return Ee.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&&De[C]||De[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(Oe.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(Oe.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 Ee,De,Oe,ke=__esmMin(()=>{({toString:Ee}=Object.prototype),De={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Oe=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$1(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(Ae!==null)return Ae>0?Ae:void 0;let t=hostGlib();if(!t)return;let n=0,S=hasProcfs()?readText$1(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 Ae=Number.isInteger(n)&&n>0?n:0,Ae>0?Ae:void 0}function hostPpid(){let t=hostGlib();if(!t)return;let n=hasProcfs()?readText$1(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$1(t,`/proc/self/status`):null;if(n){let t=new Map;for(let S of n.split(`
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 Ae,je=__esmMin(()=>{__name$1(readText$1,`readText`),Ae=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib$1(){let t=globalThis;if(typeof t.process?.versions?.gjs==`string`||t.process===void 0)return t.imports?.gi?.GLib}function arm(t){Ie||(Ie=!0,t.runAsync().catch(()=>{}))}function ensureMainLoop(){return Re=!1,createLoop()}function createLoop(){let t=glib$1();if(t)return Fe?Me:(Me=new t.MainLoop(null,!1),Fe=!0,t.main_depth()===0&&arm(Me),Me)}function holdMainLoop(){let t=ensureMainLoop();return t&&arm(t),t}function acquireMainLoop(){let t=Fe,n=createLoop();if(n)return Le===0&&!Ve&&(Re=!t),Le+=1,n}function releaseMainLoop(){Le===0||!Me||(--Le,drainIfIdle())}function trackTimer(){ze+=1}function untrackTimer(){dropPending()}function trackRequest(){ze+=1}function untrackRequest(){dropPending()}function trackedCallback(t){return trackRequest(),(...n)=>{try{t(...n)}finally{untrackRequest()}}}function dropPending(){ze!==0&&(--ze,ze===0&&drainIfIdle())}function drainIfIdle(){if(Le!==0||!Me||!Re)return;let t=Me;if(!Ie){quitMainLoop();return}if(ze!==0){Ve=!0;return}if(!t.is_running()){Ve=!0,awaitEntrySettle(t);return}exitParked()}function awaitEntrySettle(t){let n=glib$1();!n||He||(He=!0,n.timeout_add(n.PRIORITY_DEFAULT,20,()=>Me!==t||Le!==0||ze!==0?(He=!1,n.SOURCE_REMOVE):t.is_running()?(He=!1,exitParked(),n.SOURCE_REMOVE):n.SOURCE_CONTINUE))}function exitParked(){let t=globalThis.process,n=glib$1();if(typeof t?.exit!=`function`||!n){quitMainLoop(),t?.exit?.(t.exitCode??0);return}if(Be)return;Be=!0;let S=Me;n.timeout_add(n.PRIORITY_DEFAULT,0,()=>{if(Be=!1,Me!==S||Le!==0)return n.SOURCE_REMOVE;if(ze!==0)return Ve=!0,n.SOURCE_REMOVE;let C=t.exitCode??0;return quitMainLoop(),t.exit(C),n.SOURCE_REMOVE})}function quitMainLoop(){Me&&(Me.quit(),Fe=!1,Ie=!1,Me=null,Le=0,Re=!1,Ve=!1)}function monotonicMs(){let t=glib$1();return t?t.get_monotonic_time()/1e3:globalThis.performance.now()}function startLagMonitor(t={}){let n=t.intervalMs??10,S=t.thresholdMs??50,C=t.maxSamples??1e5,N=[],F=0,I=0,H=0,W=monotonicMs(),tick=()=>{let q=monotonicMs(),Y=Math.max(0,q-W-n);W=q,N[F%C]=Y,F+=1,Y>H&&(H=Y),t.onSample?.(Y),Y>S&&(I+=1,t.onStall?.(Y))},stop,q=glib$1();if(q){let t=q.timeout_add(q.PRIORITY_HIGH,n,()=>(tick(),q.SOURCE_CONTINUE));stop=()=>{t!==0&&q.MainContext.default().find_source_by_id(t)&&q.source_remove(t)}}else{let t=setInterval(tick,n);t.unref?.(),stop=()=>clearInterval(t)}let Y=!1;return{samples:()=>F<=C?N.slice():[...N.slice(F%C),...N.slice(0,F%C)],get ticks(){return F},get stalls(){return I},get maxMs(){return H},stop:()=>{Y||(Y=!0,stop())}}}var Me,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue=__esmMin(()=>{Me=null,Fe=!1,Ie=!1,Le=0,Re=!1,ze=0,Be=!1,Ve=!1,He=!1,__name$1(glib$1,`glib`)});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,Ge=__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 setDrainerArmed(t){qe!==t&&(qe=t,t?trackRequest():untrackRequest())}function drainOnce(t){let n=Math.min(64,Ke.length);for(let S=0;S<n;S++){let n=Ke.shift();try{n()}catch(n){try{t.log_default_handler(`gjsify-nextTick`,t.LogLevelFlags.LEVEL_WARNING,String(n?.stack||n),null)}catch{}}}Ke.length>0?t.timeout_add(t.PRIORITY_DEFAULT,1,()=>(drainOnce(t),!1)):setDrainerArmed(!1)}function tryGLibTimeout(t){let n=globalThis.imports?.gi?.GLib;return n?.timeout_add?(Ke.push(t),qe||(setDrainerArmed(!0),n.timeout_add(n.PRIORITY_DEFAULT,0,()=>(drainOnce(n),!1))),!0):!1}var Ke,qe,nextTick,Je=__esmMin(()=>{Ue(),Ke=[],qe=!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)}}}),Ye=__esmMin(()=>{ie(),oe(),se(),ce(),ue(),ye(),xe(),we(),Te(),ke(),je(),Ue(),Ge(),Je()});re(),Ye(),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|Ze[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+=Xe[C>>18&63]+Xe[C>>12&63]+Xe[C>>6&63]+Xe[C&63]}if(S+1===t.length){let C=t.charCodeAt(S)<<16;n+=Xe[C>>18&63]+Xe[C>>12&63]+`==`}else if(S+2===t.length){let C=t.charCodeAt(S)<<16|t.charCodeAt(S+1)<<8;n+=Xe[C>>18&63]+Xe[C>>12&63]+Xe[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|Ze[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+=Xe[N>>2],n+=Xe[(N&3)<<4|F>>4],n+=C+1<S?Xe[(F&15)<<2|I>>6]:`=`,n+=C+2<S?Xe[I&63]:`=`}return n}var Xe,Ze,Qe=__esmMin(()=>{Xe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ze=new Uint8Array(256);for(let t=0;t<64;t++)Ze[Xe.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(!$e.includes(n))throw TypeError(`Unknown encoding: ${t}`)}var $e,et=__esmMin(()=>{$e=[`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 tt,nt,textEncoder,textDecoder,rt=__esmMin(()=>{Qe(),textEncoder=()=>tt??=new TextEncoder,textDecoder=()=>nt??=new TextDecoder}),it,ot,st,ct,lt,SlowBuffer,ut=__esmMin(()=>{rt(),et(),it=typeof SharedArrayBuffer<`u`,ot=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(it&&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||it&&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}},st=2**31-1,ct=2**28-16,lt={MAX_LENGTH:st,MAX_STRING_LENGTH:ct},SlowBuffer=class extends ot{constructor(t){super(t)}}}),dt=__exportAll$5({Blob:()=>te,Buffer:()=>ot,File:()=>ne,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>ft,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>pt,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>lt,default:()=>mt,kMaxLength:()=>st,kStringMaxLength:()=>ct,normalizeEncoding:()=>normalizeEncoding}),ft,pt,mt,ht=__esmMin(()=>{Qe(),re(),et(),ut(),ft=globalThis.atob,pt=globalThis.btoa,mt={Buffer:ot,SlowBuffer,Blob:te,File:ne,atob:ft,btoa:pt,kMaxLength:st,kStringMaxLength:ct,constants:lt,INSPECT_MAX_BYTES:50}});ht(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:ot,enumerable:!1,writable:!0,configurable:!0});var gt,_t=__esmMin(()=>{gt=t}),vt,yt=__esmMin(()=>{_t(),vt=gt});yt(),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 vt.base64_encode(n)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(t){let n=String(t).replace(/[\t\n\f\r ]/g,``);n.length%4!=0&&!n.includes(`=`)&&(n+=`=`.repeat(4-n.length%4));let S=vt.base64_decode(n),C=``;for(let t=0;t<S.length;t++)C+=String.fromCharCode(S[t]);return C},enumerable:!0,writable:!0,configurable:!0}),Ye(),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 bt=__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()-xt,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()-xt}var xt,St=__esmMin(()=>{bt(),xt=getMonotonicTime()});function probeUname(){if(Ct!==void 0)return Ct;Ct=null;try{let t=getGjsGlobal().imports?.gi?.GLib;if(!t)return Ct;let n=t.spawn_sync,S=t.SpawnFlags?.SEARCH_PATH;if(!n||S===void 0)return Ct;let[C,N]=n(null,[`uname`,`-sm`],null,S,null);if(!C||!N)return Ct;let F=new TextDecoder().decode(N).trim().split(/\s+/);if(F.length<2)return Ct;let I=mapSysname(F[0]),H=mapMachine(F[F.length-1]);if(!I||!H)return Ct;Ct={platform:I,arch:H}}catch{}return Ct}var Ct,wt=__esmMin(()=>{bt(),Ye()});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 Tt=__esmMin(()=>{bt(),wt(),Ye(),__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`)}function getExecArgv(){if(!isGjsHost()){let t=globalThis.process;return Array.isArray(t?.execArgv)?t.execArgv:[]}try{let t=getGjsGlobal().imports?.gi?.GLib;if(t?.file_get_contents){let[,n]=t.file_get_contents(`/proc/self/cmdline`);if(n){let t=n instanceof Uint8Array?n:new Uint8Array(n),S=new TextDecoder().decode(t).split(`\0`).filter(t=>t.length>0),C=[];for(let t=1;t<S.length&&S[t].startsWith(`-`);t++)C.push(S[t]);return C}}}catch{}return[]}var Et=__esmMin(()=>{bt(),Ye()});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 Dt=__esmMin(()=>{bt()});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}function readId$1(t){let n=getGjsGlobal().imports?.gi?.GLib;if(!n)throw Error(`process.get${t}: GLib is not available`);try{let[S,C]=n.file_get_contents(`/proc/self/status`);if(S){let{line:n,column:S}=Ot[t],N=RegExp(`^${n}:\\s*(\\d+)\\s+(\\d+)`,`m`).exec(new TextDecoder().decode(C));if(N)return parseInt(N[S+1],10)}}catch{}let S=At.get(t);if(S!==void 0)return S;let[C,N]=n.spawn_sync(null,[`id`,...kt[t]],null,4,null),F=C&&N?new TextDecoder().decode(N).trim():``;if(!/^\d+$/.test(F))throw Error(`process.get${t}: could not determine the id (no /proc, no id(1))`);let I=parseInt(F,10);return At.set(t,I),I}var Ot,kt,At,jt=__esmMin(()=>{bt(),Ye(),__name$1(isGjs$1,`isGjs`),Ot={uid:{line:`Uid`,column:0},euid:{line:`Uid`,column:1},gid:{line:`Gid`,column:0},egid:{line:`Gid`,column:1}},kt={uid:[`-ru`],euid:[`-u`],gid:[`-rg`],egid:[`-g`]},At=new Map,__name$1(readId$1,`readId`)});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 Mt}function armSignal(t,n){if(Nt.has(t))return;let S=Mt[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));Nt.set(t,I)}function disarmSignal(t){let n=Nt.get(t);if(n===void 0)return;Nt.delete(t);let S=getGjsGlobal().imports?.gi?.GLib;S&&typeof S.source_remove==`function`&&S.source_remove(n)}var Mt,Nt,Pt=__esmMin(()=>{bt(),Mt={SIGHUP:1,SIGINT:2,SIGTERM:15},Nt=new Map});function claimRawMode(t,n){Lt.set(t,n)}function releaseRawMode(t){Lt.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=[...Lt.entries()];Lt.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 Ft,It,Lt,Rt=__esmMin(()=>{Ft=Symbol.for(`@gjsify/terminal-native:raw-mode-claims`),It=globalThis,Lt=It[Ft]??=new Map});function callableModule(){if(!Bt)return null;try{return Bt.Terminal.is_tty(2),Bt}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 zt,Bt,Vt,Ht=__esmMin(()=>{Rt(),Ye(),zt=loadOptionalNativeModule(`GjsifyTerminal`,[`Terminal`,`ResizeWatcher`]),Bt=zt.module,Vt=Bt});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 Ut,Wt,Gt,Kt=__esmMin(()=>{_e(),Ut=Symbol(`kCapture`),Wt=Symbol.for(`nodejs.rejection`),Gt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=Wt;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;[Ut];constructor(t){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[Ut]=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[Ut]&&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[Ut]&&this._addCatch(C,t,n)}}return!0}_addCatch(t,n,S){typeof t?.then==`function`&&t.then(void 0,t=>{let C=this[Wt];if(typeof C==`function`)C.call(this,t,n,...S);else{let n=this[Ut];try{this[Ut]=!1,this.emit(`error`,t)}finally{this[Ut]=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)}}}},Gt.EventEmitter=Gt;for(let t of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let n=Gt.prototype[t];typeof n==`function`&&Object.defineProperty(Gt.prototype,t,{enumerable:!0,configurable:!0,writable:!0,value:n})}Object.defineProperty(Gt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Gt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Gt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),qt=__exportAll$5({EventEmitter:()=>Jt,addAbortListener:()=>an,captureRejectionSymbol:()=>Yt,default:()=>Jt,defaultMaxListeners:()=>Zt,errorMonitor:()=>Xt,getEventListeners:()=>nn,getMaxListeners:()=>$t,listenerCount:()=>rn,"module.exports":()=>Jt,on:()=>tn,once:()=>en,setMaxListeners:()=>Qt}),Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn,rn,an,on=__esmMin(()=>{Kt(),Ye(),Jt=makeCallable(Gt),Jt.EventEmitter=Jt,Yt=Jt.captureRejectionSymbol,Xt=Jt.errorMonitor,Zt=Jt.defaultMaxListeners,Qt=Jt.setMaxListeners,$t=Jt.getMaxListeners,en=Jt.once,tn=Jt.on,nn=Jt.getEventListeners,rn=Jt.listenerCount,an=Jt.addAbortListener}),sn=__exportAll$5({StringDecoder:()=>cn,default:()=>ln});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 cn,ln,un=__esmMin(()=>{ht(),cn=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},cn.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)}},cn.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},ln={StringDecoder:cn}}),dn,ProcessWriteStream,ProcessReadStream,fn=__esmMin(()=>{_e(),bt(),Ht(),on(),Ye(),un(),dn=new TextEncoder,ProcessWriteStream=class extends Jt{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`?dn.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 Jt{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 cn(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}[Symbol.asyncIterator](){let t=[],n=!1,S=null,C=null,notify=()=>{let t=C;C=null,t?.()},onData=n=>{t.push(n),notify()},onEnd=()=>{n=!0,notify()},onError=t=>{S=t instanceof Error?t:Error(String(t)),notify()},stop=()=>{this.off(`data`,onData),this.off(`end`,onEnd),this.off(`error`,onError)};return this.on(`error`,onError),this.on(`end`,onEnd),this.on(`data`,onData),{next:async()=>{for(;;){if(t.length>0)return{value:t.shift(),done:!1};if(S)throw stop(),S;if(n)return stop(),{value:void 0,done:!0};await new Promise(t=>{C=t})}},return:async()=>(stop(),{value:void 0,done:!0}),[Symbol.asyncIterator](){return this}}}_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 pn,Process,mn=__esmMin(()=>{_e(),Tt(),Et(),Dt(),St(),jt(),Pt(),fn(),Ht(),on(),pn=Date.now(),Process=class extends Jt{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=getExecArgv(),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()-pn)/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;getuid(){return readId$1(`uid`)}geteuid(){return readId$1(`euid`)}getgid(){return readId$1(`gid`)}getegid(){return readId$1(`egid`)}emitWarning(t,n){ge.warn(typeof t==`string`?`(${n||`Warning`}): ${t}`:t.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}});function gi(){let t=globalThis.imports?.gi;if(!t?.Gio||!t.GLib)throw Error(`@gjsify/ipc-channel needs a GJS host (imports.gi)`);return{Gio:t.Gio,GLib:t.GLib}}var gio,glib,hn=__esmMin(()=>{gio=()=>gi().Gio,glib=()=>gi().GLib}),gn,LineChannel,_n=__esmMin(()=>{hn(),gn=new TextEncoder,LineChannel=class{_output;_input;constructor(t,n=null){this._output=t,this._input=n?gio().DataInputStream.new(n):null}get writable(){return this._output!==null}writeLine(t){if(!this._output)throw Error(`LineChannel: output is closed`);this._output.write_all(gn.encode(t),null)}send(t){this.writeLine(JSON.stringify(t)+`
11
11
  `)}startReading(t,n){let S=this._input;if(!S)throw Error(`LineChannel: no input stream`);let readNext=()=>{S.read_line_async(glib().PRIORITY_DEFAULT,null,(C,N)=>{let F;try{let[t]=S.read_line_finish_utf8(N);if(t===null){n?.();return}F=JSON.parse(t)}catch{n?.();return}try{t(F)}catch{}finally{readNext()}})};readNext()}closeOutput(){if(this._output){try{this._output.close(null)}catch{}this._output=null}}}});function codedError$1(t,n,S){let C=new t(S);return C.code=n,C}function isInternalMessage(t){if(typeof t!=`object`||!t)return!1;let n=t.cmd;return typeof n==`string`&&n.length>4&&n.startsWith(`NODE_`)}function setupNodeChannel(t,n){let S=gio().Socket.new_from_fd(n),C=S.connection_factory_create_connection(),N=new LineChannel(C.get_output_stream(),C.get_input_stream()),F=!0,I=!0,H=!1,updateHold=()=>{let n=F&&I&&t.listenerCount(`message`)+t.listenerCount(`disconnect`)>0;n!==H&&(H=n,n?acquireMainLoop():releaseMainLoop())};t.on(`newListener`,t=>{(t===`message`||t===`disconnect`)&&queueMicrotask(updateHold)}),t.on(`removeListener`,t=>{(t===`message`||t===`disconnect`)&&queueMicrotask(updateHold)});let W=!0,release=()=>{try{S.close()}catch{}},close=()=>{if(F){F=!1,t.connected=!1,t.channel=null;try{S.shutdown(!0,!0)}catch{}W||release(),queueMicrotask(()=>{t.emit(`disconnect`),updateHold()})}},send=(n,S,C,I)=>{typeof S==`function`?(I=S,S=void 0):typeof C==`function`&&(I=C);let H=typeof I==`function`?I:void 0;if(!F){let n=codedError$1(Error,`ERR_IPC_CHANNEL_CLOSED`,`Channel closed`);return queueMicrotask(H?()=>H(n):()=>t.emit(`error`,n)),!1}if(n===void 0)throw codedError$1(TypeError,`ERR_MISSING_ARGS`,`The "message" argument must be specified`);if(![`string`,`object`,`number`,`boolean`].includes(typeof n))throw codedError$1(TypeError,`ERR_INVALID_ARG_TYPE`,`The "message" argument must be one of type string, object, number, or boolean. Received type ${typeof n}`);if(S!=null)throw codedError$1(Error,`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`,`Sending a handle over the IPC channel is not supported under GJS`);try{N.send(n)}catch(n){let S=n instanceof Error?n:Error(String(n));return queueMicrotask(H?()=>H(S):()=>t.emit(`error`,S)),!1}return H&&queueMicrotask(()=>H(null)),!0},disconnect=()=>{if(!F){t.emit(`error`,codedError$1(Error,`ERR_IPC_DISCONNECTED`,`IPC channel is already disconnected`));return}close()},q={fd:n,ref(){I=!0,updateHold()},unref(){I=!1,updateHold()}};return Object.assign(t,{send,disconnect,channel:q,connected:!0}),N.startReading(n=>{F&&(isInternalMessage(n)?t.emit(`internalMessage`,n):t.emit(`message`,n,void 0))},()=>{W=!1,close(),release()}),H=!0,acquireMainLoop(),queueMicrotask(updateHold),q}var vn=__esmMin(()=>{hn(),_n(),Ue(),__name$1(codedError$1,`codedError`)});function connectParentChannel(t){if(!isGjsHost())return;let n=t.env.NODE_CHANNEL_FD;if(n===void 0)return;let S=t.env.NODE_CHANNEL_SERIALIZATION_MODE??`json`;delete t.env.NODE_CHANNEL_FD,delete t.env.NODE_CHANNEL_SERIALIZATION_MODE;let C=Number.parseInt(n,10);if(!(!Number.isInteger(C)||C<0)){if(S!==`json`){t.emitWarning(`IPC serialization '${S}' is not supported under GJS yet; no channel to the parent`,`ExperimentalWarning`);return}try{setupNodeChannel(t,C)}catch(n){t.emitWarning(`Could not open the IPC channel to the parent: ${n.message}`)}}}var yn=__esmMin(()=>{Et(),vn()}),bn,xn,Sn,Cn=__esmMin(()=>{if(St(),mn(),yn(),Ht(),bn=new Process,connectParentChannel(bn),Vt)try{let t=new Vt.ResizeWatcher;t.connect(`resized`,(t,n,S)=>{bn.stdout.emit(`resize`),bn.stderr.emit(`resize`)}),t.start()}catch{}bn.platform,bn.arch,bn.env,bn.argv,bn.argv0,bn.execPath,bn.pid,bn.ppid,bn.version,bn.versions,bn.cwd.bind(bn),bn.chdir.bind(bn),bn.exit.bind(bn),bn.nextTick.bind(bn),Object.assign(bn.hrtime.bind(bn),{bigint:hrtimeBigint}),bn.uptime.bind(bn),bn.memoryUsage.bind(bn),bn.cpuUsage.bind(bn),bn.kill.bind(bn),bn.abort.bind(bn),bn.umask.bind(bn),bn.getuid.bind(bn),bn.geteuid.bind(bn),bn.getgid.bind(bn),bn.getegid.bind(bn),bn.emitWarning.bind(bn),bn.execArgv,bn.config,xn=bn.stdout,bn.stderr,Sn=bn.stdin});Ye(),Cn(),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:bn,enumerable:!1,writable:!0,configurable:!0}),Ye(),typeof globalThis.structuredClone!=`function`&&Object.defineProperty(globalThis,"structuredClone",{value:structuredClone$1,enumerable:!0,writable:!0,configurable:!0}),Ue();function getGLib(){return globalThis.imports?.gi?.GLib}const wn=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;_tracked=!1;_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._track(),this._id=n(t.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){reportTimerThrow(t,n),globalThis.__gjsify_worker_context?.crash(n)}return this._repeat?t.SOURCE_CONTINUE:(this._id=null,this._untrack(),t.SOURCE_REMOVE)})}unref(){return this._refed=!1,this._untrack(),this}ref(){return this._refed=!0,this._id!==null&&this._track(),this}_track(){this._tracked||!this._refed||(this._tracked=!0,trackTimer())}_untrack(){this._tracked&&(this._tracked=!1,untrackTimer())}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null,this._untrack())}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(wn){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 $,Tn,En=__esmMin(()=>{$=Object.defineProperty,Tn=__name$1((t,n)=>{let S={};for(var C in t)$(S,C,{get:t[C],enumerable:!0});return n||$(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 Dn=__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$6(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 On,kn=__esmMin(()=>{En(),Dn(),On=Tn({basename:()=>basename$2,delimiter:()=>`:`,dirname:()=>dirname$2,extname:()=>extname$2,format:()=>format$3,isAbsolute:()=>isAbsolute$2,join:()=>join$3,normalize:()=>normalize$2,parse:()=>parse$6,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$6,`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 jn.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$5(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 An,jn,Mn=__esmMin(()=>{En(),Dn(),An=Tn({basename:()=>basename$1,delimiter:()=>`;`,dirname:()=>dirname$1,extname:()=>extname$1,format:()=>format$2,isAbsolute:()=>isAbsolute$1,join:()=>join$2,normalize:()=>normalize$1,parse:()=>parse$5,relative:()=>relative,resolve:()=>resolve$3,sep:()=>`\\`,toNamespacedPath:()=>toNamespacedPath}),__name$1(cwd$1,`cwd`),__name$1(resolve$3,`resolve`),__name$1(normalize$1,`normalize`),jn=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$5,`parse`)});function selectFlavour(t){return t===`win32`?An:On}var Nn=__esmMin(()=>{kn(),Mn()}),Pn=__exportAll$5({basename:()=>Un,default:()=>Yn,delimiter:()=>Jn,dirname:()=>Hn,extname:()=>Wn,format:()=>Gn,isAbsolute:()=>Rn,join:()=>zn,normalize:()=>Ln,parse:()=>Kn,posix:()=>On,relative:()=>Bn,resolve:()=>In,sep:()=>qn,toNamespacedPath:()=>Vn,win32:()=>An}),Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn=__esmMin(()=>{kn(),Mn(),Nn(),Ye(),Fn=selectFlavour(hostOs()),{resolve:In,normalize:Ln,isAbsolute:Rn,join:zn,relative:Bn,toNamespacedPath:Vn,dirname:Hn,basename:Un,extname:Wn,format:Gn,parse:Kn,sep:qn,delimiter:Jn}=Fn,Yn={resolve:Fn.resolve,normalize:Fn.normalize,isAbsolute:Fn.isAbsolute,join:Fn.join,relative:Fn.relative,toNamespacedPath:Fn.toNamespacedPath,dirname:Fn.dirname,basename:Fn.basename,extname:Fn.extname,format:Fn.format,parse:Fn.parse,sep:Fn.sep,delimiter:Fn.delimiter,posix:On,win32:An}}),Zn=__exportAll$5({URL:()=>ar,URLSearchParams:()=>er,default:()=>sr,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$1,parse:()=>parse$4,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 tr.has(t)}function defaultPort(t){return tr.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===`%`||ir.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(ir.has(n))return;return percentEncode(t,``)}if(!hasForbiddenDomainCodePoint(t))return t.toLowerCase()}function parseHostSetterValue(t,n,S,C,N){let F=t.replace(rr,``),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(rr,``);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$4(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 er(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 ar)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 er(n.query).toString();t&&(S+=`?`+t)}return n.hash&&(S+=n.hash),S}function resolve$2(t,n){return new ar(n,new ar(t,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(t,n){if(typeof t==`string`&&(t=new ar(t)),!(t instanceof ar))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?An:On).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]!==qn&&(C+=`/`),new ar(pathToFileUrlHref(C,{windows:S}))}function currentDir(){return typeof globalThis.process?.cwd==`function`?globalThis.process.cwd():vt.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 ar(`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 ar(`http://${t}`).hostname}catch{return``}}function domainToUnicode(t){try{return new ar(`http://${t}`).hostname}catch{return``}}var Qn,$n,er,tr,nr,rr,ir,ar,sr,cr=__esmMin(()=>{yt(),Ye(),Xn(),Qn=vt.UriFlags.HAS_PASSWORD|vt.UriFlags.ENCODED|vt.UriFlags.SCHEME_NORMALIZE,$n=new WeakMap,er=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]);$n.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)),$n.get(this)?.()}append(t,n){this._entries.push([t,n]),$n.get(this)?.()}sort(){this._entries.sort((t,n)=>t[0]<n[0]?-1:+(t[0]>n[0])),$n.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}},tr=new Map([[`ftp`,21],[`file`,null],[`http`,80],[`https`,443],[`ws`,80],[`wss`,443]]),nr='"#/:;<=>?@[\\]^`{|}',rr=/[\t\n\r]/g,__name$1(isHexDigit$1,`isHexDigit`),ir=new Set([`\0`,` `,`
12
12
  `,`\r`,` `,`#`,`/`,`:`,`<`,`>`,`?`,`@`,`[`,`\\`,`]`,`^`,`|`]),ar=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=vt.Uri.parse(t,Qn).parse_relative(S,Qn)}else C=vt.Uri.parse(S,Qn)}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 er,this.#c._entries=parseFormUrlencoded(this.#l??``),$n.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(rr,``)+`:`;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(rr,``));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(rr,``);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(rr,``);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),nr))}get password(){return this.#n}set password(t){this.#u()||(this.#n=percentEncode(String(t),nr))}#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&&(vt.unlink(n),URL._objectURLPaths.delete(t))}},__name$1(parse$4,`parse`),__name$1(format$1,`format`),__name$1(resolve$2,`resolve`),sr={URL:ar,URLSearchParams:er,parse:parse$4,format:format$1,resolve:resolve$2,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});cr(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:ar,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:er,enumerable:!1,writable:!0,configurable:!0});var lr,ur,File,dr=__esmMin(()=>{lr=Symbol(`File.name`),ur=Symbol(`File.lastModified`),File=class extends Blob{[lr];[ur];webkitRelativePath=``;constructor(t,n,S){super(t,S),this[lr]=String(n),this[ur]=S?.lastModified??Date.now()}get name(){return this[lr]}get lastModified(){return this[ur]}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
13
13
  `)}\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
14
- `)}return S.push(`--${n}--`),new Blob(S,{type:`multipart/form-data; boundary=${n}`})}var fr=__esmMin(()=>{dr()});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 pr,FormData$1,mr=__esmMin(()=>{dr(),pr=Symbol(`FormData.entries`),FormData$1=class{static{__name$1(this,`FormData`)}[pr]=[];constructor(){}append(t,n,S){this[pr].push({name:String(t),value:normalizeValue(t,n,S)})}delete(t){let n=String(t);this[pr]=this[pr].filter(t=>t.name!==n)}get(t){let n=String(t),S=this[pr].find(t=>t.name===n);return S?S.value:null}getAll(t){let n=String(t);return this[pr].filter(t=>t.name===n).map(t=>t.value)}has(t){let n=String(t);return this[pr].some(t=>t.name===n)}set(t,n,S){let C=String(t),N=normalizeValue(C,n,S),F=!1;this[pr]=this[pr].filter(t=>t.name===C?F?!1:(F=!0,t.value=N,!0):!0),F||this[pr].push({name:C,value:N})}forEach(t,n){for(let S of this[pr])t.call(n,S.value,S.name,this)}*entries(){for(let t of this[pr])yield[t.name,t.value]}*keys(){for(let t of this[pr])yield t.name}*values(){for(let t of this[pr])yield t.value}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`FormData`}}}),hr=__esmMin(()=>{fr(),mr()});hr();const gr=globalThis;typeof globalThis.FormData!=`function`&&(gr.FormData=FormData$1);var _r=__exportAll$5({PerformanceEntry:()=>Sr,PerformanceMark:()=>wr,PerformanceMeasure:()=>Tr,PerformanceObserver:()=>br,PerformanceObserverEntryList:()=>Cr,default:()=>Er,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>vr,timerify:()=>timerify});function eventLoopUtilization(t,n){return{idle:0,active:0,utilization:0}}function timerify(t){let wrapped=function(...n){let S=vr.now(),C=t.apply(this,n);return vr.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 vr,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,yr,br,Sr,Cr,wr,Tr,Er,Dr=__esmMin(()=>{if(globalThis.performance)vr=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();vr={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[]}},yr=globalThis,br=yr.PerformanceObserver||PerformanceObserverStub,Sr=yr.PerformanceEntry||PerformanceEntryStub,Cr=yr.PerformanceObserverEntryList||PerformanceObserverEntryListStub,wr=yr.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},Tr=yr.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Er={performance:vr,PerformanceObserver:br,PerformanceEntry:Sr,PerformanceObserverEntryList:Cr,PerformanceMark:wr,PerformanceMeasure:Tr,eventLoopUtilization,timerify,monitorEventLoopDelay}});Dr();const Or=globalThis;globalThis.performance===void 0&&(Or.performance=vr),typeof Or.PerformanceObserver!=`function`&&(Or.PerformanceObserver=br);const kr={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(kr,this.name)?kr[this.name]:0}};const Ar=globalThis.DOMException??_DOMExceptionPolyfill;_e();const jr=Symbol(`type`),Mr=Symbol(`bubbles`),Nr=Symbol(`cancelable`),Pr=Symbol(`composed`),Fr=Symbol(`target`),Ir=Symbol(`currentTarget`),Lr=Symbol(`eventPhase`),Rr=Symbol(`defaultPrevented`),zr=Symbol(`isTrusted`),Br=Symbol(`timeStamp`),Vr=Symbol(`stop`),Hr=Symbol(`immediateStop`),Ur=Symbol(`dispatching`),Wr=Symbol(`inPassiveListener`);var Event=class{[jr];[Mr];[Nr];[Pr];[Fr]=null;[Ir]=null;[Lr]=0;[Rr]=!1;[zr]=!1;[Br];[Vr]=!1;[Hr]=!1;[Ur]=!1;[Wr]=!1;get type(){return this[jr]}get bubbles(){return this[Mr]}get cancelable(){return this[Nr]}get composed(){return this[Pr]}get target(){return this[Fr]}get currentTarget(){return this[Ir]}get eventPhase(){return this[Lr]}get defaultPrevented(){return this[Rr]}get timeStamp(){return this[Br]}get cancelBubble(){return this[Vr]}set cancelBubble(t){t&&this.stopPropagation()}get returnValue(){return!this[Rr]}set returnValue(t){t||this.preventDefault()}get srcElement(){return this[Fr]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(t,n){this[jr]=t,this[Mr]=n?.bubbles??!1,this[Nr]=n?.cancelable??!1,this[Pr]=n?.composed??!1,this[Br]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[zr],enumerable:!0,configurable:!1})}composedPath(){return this[Ir]?[this[Ir]]:[]}preventDefault(){this[Nr]&&!this[Wr]&&(this[Rr]=!0)}stopPropagation(){this[Vr]=!0}stopImmediatePropagation(){this[Vr]=!0,this[Hr]=!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[Ur])throw new Ar(`The event is already being dispatched.`,`InvalidStateError`);n[Ur]=!0,n[Fr]=this,n[Ir]=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[Hr]||n[Vr])break;S.once&&this.removeEventListener(t.type,S.listener,{capture:S.capture});try{S.passive&&(n[Wr]=!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[Wr]=!1}}}}finally{n[Lr]=Event.NONE,n[Ir]=null,n[Ur]=!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 Gr=Symbol(`abort`),Kr=Symbol(`internal`);var qr=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(t){if(super(),t!==Kr)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}[Gr](t){if(this.#e)return;this.#e=!0,this.#t=t??new Ar(`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(Kr);return n[Gr](t),n}static timeout(t){let n=new AbortSignal(Kr);return setTimeout(()=>{n[Gr](new Ar(`The operation timed out.`,`TimeoutError`))},t),n}static any(t){let n=new AbortSignal(Kr);for(let S of t)if(S.aborted)return n[Gr](S.reason),n;let onAbort=()=>{if(!n.aborted){let S=t.find(t=>t.aborted);n[Gr](S?.reason)}};for(let n of t)n.addEventListener(`abort`,onAbort,{once:!0});return n}},Jr=class AbortController{signal;constructor(){this.signal=new qr(Kr)}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[Gr](t)}};const Yr=globalThis;globalThis.AbortController===void 0&&(Yr.AbortController=Jr),globalThis.AbortSignal===void 0&&(Yr.AbortSignal=qr);const Xr=Symbol(`kState`),Zr=Symbol(`kType`);function isBrandCheck(t){return n=>typeof n==`object`&&!!n&&n[Xr]!==void 0&&n[Zr]===t}function dequeueValue(t){let n=t[Xr].queue.shift();if(n===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:S,size:C}=n;return t[Xr].queueTotalSize=Math.max(0,t[Xr].queueTotalSize-C),S}function resetQueue(t){t[Xr].queue=[],t[Xr].queueTotalSize=0}function peekQueueValue(t){return t[Xr].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[Xr].queue.push({value:n,size:S}),t[Xr].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 Qr={__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 $r=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}},ei=Symbol(`kAbort`),ti=Symbol(`kCloseSentinel`),ni=Symbol(`kError`),ri=Symbol(`kSkipThrow`);var WritableStream=class{[Zr]=`WritableStream`;[Xr];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[Xr]=createWritableStreamState();let C=extractSizeAlgorithm(n?.size),N=extractHighWaterMark(n?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,t,N,C)}get locked(){if(!ii(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(t){return ii(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){return ii(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(!ii(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[Zr]=`WritableStreamDefaultWriter`;[Xr];constructor(t){if(!ii(t))throw TypeError(`Expected a WritableStream`);this[Xr]={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 ai(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!ai(this))throw TypeError(`Invalid this`);if(this[Xr].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return ai(this)?this[Xr].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(t){return ai(this)?this[Xr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){if(!ai(this))return Promise.reject(TypeError(`Invalid this`));let{stream:t}=this[Xr];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(!ai(this))throw TypeError(`Invalid this`);let{stream:t}=this[Xr];t!==void 0&&writableStreamDefaultWriterRelease(this)}write(t){return ai(this)?this[Xr].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{[Zr]=`WritableStreamDefaultController`;[Xr];constructor(t){if(t!==ri)throw TypeError(`Illegal constructor`)}[ei](t){let n=this[Xr].abortAlgorithm(t);return writableStreamDefaultControllerClearAlgorithms(this),n}[ni](){resetQueue(this)}get signal(){if(!oi(this))throw TypeError(`Invalid this`);return this[Xr].abortController.signal}error(t){if(!oi(this))throw TypeError(`Invalid this`);this[Xr].stream[Xr].state===`writable`&&writableStreamDefaultControllerError(this,t)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const ii=isBrandCheck(`WritableStream`),ai=isBrandCheck(`WritableStreamDefaultWriter`),oi=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[Xr].writer!==void 0}function setupWritableStreamDefaultWriter(t,n){if(isWritableStreamLocked(n))throw TypeError(`WritableStream is locked`);switch(t[Xr].stream=n,n[Xr].writer=t,n[Xr].state){case`writable`:!writableStreamCloseQueuedOrInFlight(n)&&n[Xr].backpressure?t[Xr].ready=Promise.withResolvers():t[Xr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Xr].close=Promise.withResolvers();break;case`erroring`:t[Xr].ready={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise),t[Xr].close=Promise.withResolvers();break;case`closed`:t[Xr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Xr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:t[Xr].ready={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},t[Xr].close={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise),setPromiseHandled(t[Xr].close.promise)}}function writableStreamAbort(t,n){let{state:S,controller:C}=t[Xr];if(S===`closed`||S===`errored`)return Promise.resolve();if(C[Xr].abortController.abort(n),t[Xr].pendingAbortRequest.abort.promise!==void 0)return t[Xr].pendingAbortRequest.abort.promise;let N=!1;S===`erroring`&&(N=!0,n=void 0);let F=Promise.withResolvers();return t[Xr].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[Xr];if(n===`closed`||n===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));t[Xr].closeRequest=Promise.withResolvers();let{promise:F}=t[Xr].closeRequest;return S!==void 0&&C&&n===`writable`&&S[Xr].ready.resolve?.(),writableStreamDefaultControllerClose(N),F}function writableStreamUpdateBackpressure(t,n){let{writer:S}=t[Xr];S!==void 0&&t[Xr].backpressure!==n&&(n?S[Xr].ready=Promise.withResolvers():S[Xr].ready.resolve?.()),t[Xr].backpressure=n}function writableStreamStartErroring(t,n){let{controller:S,writer:C}=t[Xr];t[Xr].state=`erroring`,t[Xr].storedError=n,C!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(C,n),!writableStreamHasOperationMarkedInFlight(t)&&S[Xr].started&&writableStreamFinishErroring(t)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(t){t[Xr].closeRequest.promise!==void 0&&(t[Xr].closeRequest.reject?.(t[Xr].storedError),t[Xr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(t[Xr].close.promise),t[Xr].close.reject?.(t[Xr].storedError);let{writer:n}=t[Xr];n!==void 0&&(setPromiseHandled(n[Xr].close.promise),n[Xr].close.reject?.(t[Xr].storedError))}function writableStreamMarkFirstWriteRequestInFlight(t){let n=t[Xr].writeRequests.shift();t[Xr].inFlightWriteRequest=n}function writableStreamMarkCloseRequestInFlight(t){t[Xr].inFlightCloseRequest=t[Xr].closeRequest,t[Xr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(t){return t[Xr].inFlightWriteRequest.promise!==void 0||t[Xr].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(t,n){t[Xr].inFlightWriteRequest.reject?.(n),t[Xr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightWrite(t){t[Xr].inFlightWriteRequest.resolve?.(),t[Xr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(t,n){t[Xr].inFlightCloseRequest.reject?.(n),t[Xr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Xr].pendingAbortRequest.abort.promise!==void 0&&(t[Xr].pendingAbortRequest.abort.reject?.(n),t[Xr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightClose(t){t[Xr].inFlightCloseRequest.resolve?.(),t[Xr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Xr].state===`erroring`&&(t[Xr].storedError=void 0,t[Xr].pendingAbortRequest.abort.promise!==void 0&&(t[Xr].pendingAbortRequest.abort.resolve?.(),t[Xr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),t[Xr].state=`closed`,t[Xr].writer!==void 0&&t[Xr].writer[Xr].close.resolve?.(),t[Xr].close.resolve?.()}function writableStreamFinishErroring(t){t[Xr].state=`errored`,t[Xr].controller[ni]();let n=t[Xr].storedError;for(let S of t[Xr].writeRequests)S.reject?.(n);if(t[Xr].writeRequests=[],t[Xr].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}let S=t[Xr].pendingAbortRequest;if(t[Xr].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[Xr].controller[ei](S.reason).then(()=>{S.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)},n=>{S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)})}function writableStreamDealWithRejection(t,n){if(t[Xr].state===`writable`){writableStreamStartErroring(t,n);return}writableStreamFinishErroring(t)}function writableStreamCloseQueuedOrInFlight(t){return t[Xr].closeRequest.promise!==void 0||t[Xr].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(t){let{promise:n,resolve:S,reject:C}=Promise.withResolvers();return t[Xr].writeRequests.push({promise:n,resolve:S,reject:C}),n}function writableStreamDefaultWriterWrite(t,n){let{stream:S}=t[Xr],{controller:C}=S[Xr],N=writableStreamDefaultControllerGetChunkSize(C,n);if(S!==t[Xr].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:F}=S[Xr];if(F===`errored`)return Promise.reject(S[Xr].storedError);if(writableStreamCloseQueuedOrInFlight(S)||F===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(F===`erroring`)return Promise.reject(S[Xr].storedError);let I=writableStreamAddWriteRequest(S);return writableStreamDefaultControllerWrite(C,n,N),I}function writableStreamDefaultWriterRelease(t){let{stream:n}=t[Xr],S=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(t,S),writableStreamDefaultWriterEnsureClosedPromiseRejected(t,S),n[Xr].writer=void 0,t[Xr].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(t){let{stream:n}=t[Xr];switch(n[Xr].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(n[Xr].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(t,n){t[Xr].ready.reject?(t[Xr].ready.reject(n),t[Xr].ready.resolve=void 0,t[Xr].ready.reject=void 0):t[Xr].ready={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(t,n){t[Xr].close.reject?(t[Xr].close.reject(n),t[Xr].close.resolve=void 0,t[Xr].close.reject=void 0):t[Xr].close={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(t){let{stream:n}=t[Xr],{state:S}=n[Xr];return writableStreamCloseQueuedOrInFlight(n)||S===`closed`?Promise.resolve():S===`errored`?Promise.reject(n[Xr].storedError):writableStreamDefaultWriterClose(t)}function writableStreamDefaultWriterClose(t){return writableStreamClose(t[Xr].stream)}function writableStreamDefaultWriterAbort(t,n){return writableStreamAbort(t[Xr].stream,n)}function writableStreamDefaultControllerWrite(t,n,S){try{enqueueValueWithSize(t,n,S)}catch(n){writableStreamDefaultControllerErrorIfNeeded(t,n);return}let{stream:C}=t[Xr];!writableStreamCloseQueuedOrInFlight(C)&&C[Xr].state===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerProcessWrite(t,n){let{stream:S,writeAlgorithm:C}=t[Xr];writableStreamMarkFirstWriteRequestInFlight(S),C(n,t).then(()=>{writableStreamFinishInFlightWrite(S);let{state:n}=S[Xr];dequeueValue(t),!writableStreamCloseQueuedOrInFlight(S)&&n===`writable`&&writableStreamUpdateBackpressure(S,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)},n=>{S[Xr].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(t),writableStreamFinishInFlightWriteWithError(S,n)})}function writableStreamDefaultControllerProcessClose(t){let{closeAlgorithm:n,stream:S}=t[Xr];writableStreamMarkCloseRequestInFlight(S),dequeueValue(t);let C=n();writableStreamDefaultControllerClearAlgorithms(t),C.then(()=>writableStreamFinishInFlightClose(S),t=>writableStreamFinishInFlightCloseWithError(S,t))}function writableStreamDefaultControllerGetDesiredSize(t){return t[Xr].highWaterMark-t[Xr].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(t,n){let{sizeAlgorithm:S}=t[Xr];if(S===void 0)return 1;try{return S(n)}catch(n){return writableStreamDefaultControllerErrorIfNeeded(t,n),1}}function writableStreamDefaultControllerErrorIfNeeded(t,n){t[Xr].stream[Xr].state===`writable`&&writableStreamDefaultControllerError(t,n)}function writableStreamDefaultControllerError(t,n){writableStreamDefaultControllerClearAlgorithms(t),writableStreamStartErroring(t[Xr].stream,n)}function writableStreamDefaultControllerClose(t){enqueueValueWithSize(t,ti,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerClearAlgorithms(t){t[Xr].writeAlgorithm=void 0,t[Xr].closeAlgorithm=void 0,t[Xr].abortAlgorithm=void 0,t[Xr].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(t){return writableStreamDefaultControllerGetDesiredSize(t)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(t){let{queue:n,started:S,stream:C}=t[Xr];if(!S||C[Xr].inFlightWriteRequest.promise!==void 0)return;if(C[Xr].state===`erroring`){writableStreamFinishErroring(C);return}if(!n.length)return;let N=peekQueueValue(t);N===ti?writableStreamDefaultControllerProcessClose(t):writableStreamDefaultControllerProcessWrite(t,N)}function setupWritableStreamDefaultControllerFromSink(t,n,S,C){let N=new WritableStreamDefaultController(ri),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[Xr]={abortAlgorithm:F,closeAlgorithm:N,highWaterMark:I,queue:[],queueTotalSize:0,abortController:new $r,sizeAlgorithm:H,started:!1,stream:t,writeAlgorithm:C},t[Xr].controller=n,writableStreamUpdateBackpressure(t,writableStreamDefaultControllerGetBackpressure(n));let W=S();new Promise(t=>t(W)).then(()=>{n[Xr].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{n[Xr].started=!0,writableStreamDealWithRejection(t,S)})}function createWritableStream(t,n,S,C,N=1,F=()=>1){let I=Object.create(WritableStream.prototype);return I[Zr]=`WritableStream`,I[Xr]=createWritableStreamState(),setupWritableStreamDefaultController(I,new WritableStreamDefaultController(ri),t,n,S,C,N,F),I}Ye();const si=Symbol(`kCancel`),ci=Symbol(`kClose`),li=Symbol(`kChunk`),di=Symbol(`kError`),fi=Symbol(`kPull`),pi=Symbol(`kRelease`),mi=Symbol(`kSkipThrow`);let hi,_i;function lazyReadableReleasedError(){return hi||(hi=TypeError(`Reader released`),hi)}function lazyReadableReleasingError(){return _i||(_i=TypeError(`Releasing reader`),_i)}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`)}[Zr]=`ReadableStream`;[Xr];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[Xr]=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(!vi(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(t){return readableStreamFromIterable(t)}cancel(t=void 0){return vi(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,t):Promise.reject(TypeError(`Invalid this`))}getReader(t={}){if(!vi(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(!vi(this))throw TypeError(`Invalid this`);let S=t?.readable;if(!vi(S))throw TypeError(`transform.readable must be a ReadableStream`);let C=t?.writable;if(!ii(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(!vi(this))throw TypeError(`Invalid this`);if(!ii(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(!vi(this))throw TypeError(`Invalid this`);let t=this[Xr].controller;return xi(t)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(t={}){if(!vi(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[Xr].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,{[li](t){C.current=void 0,n({value:t,done:!1})},[ci](){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),n({done:!0,value:void 0})},[di](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[Xr].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}},Qr)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Xr];constructor(){this[Xr]=Promise.withResolvers()}[li](t){this[Xr].resolve?.({value:t,done:!1})}[ci](){this[Xr].resolve?.({value:void 0,done:!0})}[di](t){this[Xr].reject?.(t)}get promise(){return this[Xr].promise}},ReadableStreamDefaultReader=class{[Zr]=`ReadableStreamDefaultReader`;[Xr];constructor(t){if(!vi(t))throw TypeError(`Expected a ReadableStream`);this[Xr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,t)}read(){if(!bi(this))return Promise.reject(TypeError(`Invalid this`));if(this[Xr].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let t=this[Xr].stream,n=t[Xr].controller;if(t[Xr].state===`readable`&&yi(n)&&n[Xr].queue.length>0){t[Xr].disturbed=!0;let S=dequeueValue(n);return n[Xr].closeRequested&&!n[Xr].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(!bi(this))throw TypeError(`Invalid this`);this[Xr].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return bi(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return bi(this)?this[Xr].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{[Zr]=`ReadableStreamDefaultController`;[Xr];constructor(t){if(t!==mi)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)}[si](t){return readableStreamDefaultControllerCancelSteps(this,t)}[fi](t){readableStreamDefaultControllerPullSteps(this,t)}[pi](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const vi=isBrandCheck(`ReadableStream`),yi=isBrandCheck(`ReadableStreamDefaultController`),bi=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(t){return t[Xr].reader!==void 0}function readableStreamCancel(t,n){switch(t[Xr].disturbed=!0,t[Xr].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(t[Xr].storedError)}readableStreamClose(t);let S=t[Xr].reader;if(S!==void 0&&readableStreamHasBYOBReader(t)){let t=S[Xr].readIntoRequests;S[Xr].readIntoRequests=[];for(let n=0;n<t.length;n++)t[n][ci](void 0)}return t[Xr].controller[si](n).then(()=>{})}function readableStreamClose(t){t[Xr].state=`closed`,t[Xr].closedPromise.resolve();let{reader:n}=t[Xr];if(n!==void 0&&(n[Xr].close.resolve?.(),readableStreamHasDefaultReader(t))){for(let t=0;t<n[Xr].readRequests.length;t++)n[Xr].readRequests[t][ci]();n[Xr].readRequests=[]}}function readableStreamError(t,n){t[Xr].state=`errored`,t[Xr].storedError=n,setPromiseHandled(t[Xr].closedPromise.promise),t[Xr].closedPromise.reject(n);let{reader:S}=t[Xr];if(S!==void 0){if(setPromiseHandled(S[Xr].close.promise),S[Xr].close.reject?.(n),readableStreamHasDefaultReader(t)){for(let t=0;t<S[Xr].readRequests.length;t++)S[Xr].readRequests[t][di](n);S[Xr].readRequests=[]}else if(readableStreamHasBYOBReader(t)){for(let t=0;t<S[Xr].readIntoRequests.length;t++)S[Xr].readIntoRequests[t][di](n);S[Xr].readIntoRequests=[]}}}function readableStreamHasDefaultReader(t){let{reader:n}=t[Xr];return n===void 0?!1:n[Xr]!==void 0&&n[Zr]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(t){return t[Xr].reader[Xr].readRequests.length}function readableStreamFulfillReadRequest(t,n,S){let{reader:C}=t[Xr],N=C[Xr].readRequests.shift();S?N[ci]():N[li](n)}function readableStreamAddReadRequest(t,n){t[Xr].reader[Xr].readRequests.push(n)}function readableStreamReaderGenericCancel(t,n){let{stream:S}=t[Xr];return readableStreamCancel(S,n)}function readableStreamReaderGenericInitialize(t,n){switch(t[Xr].stream=n,n[Xr].reader=t,n[Xr].state){case`readable`:t[Xr].close=Promise.withResolvers();break;case`closed`:t[Xr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:t[Xr].close={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise);break}}function readableStreamReaderGenericRelease(t){let{stream:n}=t[Xr],S=lazyReadableReleasedError();n[Xr].state===`readable`?t[Xr].close.reject?.(S):t[Xr].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise),n[Xr].controller[pi](),n[Xr].reader=void 0,t[Xr].stream=void 0}function readableStreamDefaultReaderRelease(t){readableStreamReaderGenericRelease(t),readableStreamDefaultReaderErrorReadRequests(t,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(t,n){for(let S=0;S<t[Xr].readRequests.length;++S)t[Xr].readRequests[S][di](n);t[Xr].readRequests=[]}function readableStreamDefaultReaderRead(t,n){let{stream:S}=t[Xr];switch(S[Xr].disturbed=!0,S[Xr].state){case`closed`:n[ci]();break;case`errored`:n[di](S[Xr].storedError);break;case`readable`:S[Xr].controller[fi](n);break}}function setupReadableStreamDefaultReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(t,n),t[Xr].readRequests=[]}function readableStreamDefaultControllerClose(t){readableStreamDefaultControllerCanCloseOrEnqueue(t)&&(t[Xr].closeRequested=!0,t[Xr].queue.length||(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(t[Xr].stream)))}function readableStreamDefaultControllerEnqueue(t,n){if(!readableStreamDefaultControllerCanCloseOrEnqueue(t))return;let{stream:S}=t[Xr];if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))readableStreamFulfillReadRequest(S,n,!1);else try{enqueueValueWithSize(t,n,t[Xr].sizeAlgorithm(n))}catch(n){throw readableStreamDefaultControllerError(t,n),n}readableStreamDefaultControllerCallPullIfNeeded(t)}function readableStreamDefaultControllerCanCloseOrEnqueue(t){let{stream:n}=t[Xr];return!t[Xr].closeRequested&&n[Xr].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(t){let{stream:n,highWaterMark:S,queueTotalSize:C}=t[Xr];switch(n[Xr].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[Xr];if(!readableStreamDefaultControllerCanCloseOrEnqueue(t)||!t[Xr].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[Xr].pulling){t[Xr].pullAgain=!0;return}t[Xr].pulling=!0,t[Xr].pullAlgorithm(t).then(()=>{t[Xr].pulling=!1,t[Xr].pullAgain&&(t[Xr].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(t))},n=>readableStreamDefaultControllerError(t,n))}}function readableStreamDefaultControllerClearAlgorithms(t){t[Xr].pullAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0,t[Xr].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(t,n){let{stream:S}=t[Xr];S[Xr].state===`readable`&&(resetQueue(t),readableStreamDefaultControllerClearAlgorithms(t),readableStreamError(S,n))}function readableStreamDefaultControllerCancelSteps(t,n){resetQueue(t);let S=t[Xr].cancelAlgorithm?.(n)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(t),S}function readableStreamDefaultControllerPullSteps(t,n){let{stream:S,queue:C}=t[Xr];if(C.length){let N=dequeueValue(t);t[Xr].closeRequested&&!C.length?(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(S)):readableStreamDefaultControllerCallPullIfNeeded(t),n[li](N);return}readableStreamAddReadRequest(S,n),readableStreamDefaultControllerCallPullIfNeeded(t)}function setupReadableStreamDefaultController(t,n,S,C,N,F,I){n[Xr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:I,stream:t},t[Xr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Xr].started=!0,readableStreamDefaultControllerCallPullIfNeeded(n)},t=>readableStreamDefaultControllerError(n,t))}function setupReadableStreamDefaultControllerFromSource(t,n,S,C){let N=new ReadableStreamDefaultController(mi),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[Zr]=`ReadableStream`,F[Xr]=createReadableStreamState(),setupReadableStreamDefaultController(F,new ReadableStreamDefaultController(mi),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[Xr].controller):readableStreamDefaultControllerEnqueue(n[Xr].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[Xr].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[Xr].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[Xr].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[Xr].state===`writable`?writableStreamAbort(n,S):Promise.resolve()),N||I.push(()=>t[Xr].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[Xr].state===`errored`?S(t[Xr].storedError):n.then(void 0,S)}function watchClosed(t,n,S){t[Xr].state===`closed`?S():n.then(S,()=>{})}class PipeToReadRequest{[li](t){ve(()=>{Z.currentWrite=writableStreamDefaultWriterWrite(H,t),setPromiseHandled(Z.currentWrite),ne.resolve(!1)})}[ci](){ne.resolve(!0)}[di](t){ne.reject(t)}}let ne={resolve:null,reject:null};async function step(){if(W||n[Xr].backpressure&&(await H[Xr].ready.promise,W))return!0;let S=t[Xr].controller;if(t[Xr].state===`readable`&&yi(S)&&S[Xr].queue.length>0){for(;S[Xr].queue.length>0;){if(W)return!0;let C=dequeueValue(S);if(S[Xr].closeRequested&&!S[Xr].queue.length&&(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(t)),Z.currentWrite=writableStreamDefaultWriterWrite(H,C),setPromiseHandled(Z.currentWrite),n[Xr].backpressure||n[Xr].state!==`writable`||writableStreamCloseQueuedOrInFlight(n))break}return readableStreamDefaultControllerCallPullIfNeeded(S),t[Xr].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[Xr].close.promise,t=>{if(!C)return shutdownWithAnAction(()=>writableStreamAbort(n,t),!0,t);shutdown(!0,t)}),watchErrored(n,H[Xr].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n);shutdown(!0,n)}),watchClosed(t,I[Xr].close.promise,()=>{if(!S)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(H));shutdown()}),writableStreamCloseQueuedOrInFlight(n)||n[Xr].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,{[li](t){ve(()=>{C=!1;let S=t,I=t;if(!F&&n)try{I=structuredClone(I)}catch{}N||readableStreamDefaultControllerEnqueue(W[Xr].controller,S),F||readableStreamDefaultControllerEnqueue(q[Xr].controller,I)})},[ci](){ve(()=>{C=!1,N||readableStreamDefaultControllerClose(W[Xr].controller),F||readableStreamDefaultControllerClose(q[Xr].controller),(!N||!F)&&Y.resolve(void 0)})},[di](){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[Xr].close.promise.then(void 0,t=>{readableStreamDefaultControllerError(W[Xr].controller,t),readableStreamDefaultControllerError(q[Xr].controller,t),(!N||!F)&&Y.resolve(void 0)}),[W,q]}var BYOBReadIntoRequest=class{[Xr];constructor(){this[Xr]=Promise.withResolvers()}[li](t){this[Xr].resolve?.({value:t,done:!1})}[ci](t){this[Xr].resolve?.({value:t,done:!0})}[di](t){this[Xr].reject?.(t)}get promise(){return this[Xr].promise}},ReadableStreamBYOBReader=class{[Zr]=`ReadableStreamBYOBReader`;[Xr];constructor(t){if(!vi(t))throw TypeError(`Expected a ReadableStream`);this[Xr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,t)}read(t,n={}){if(!Si(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[Xr].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(!Si(this))throw TypeError(`Invalid this`);this[Xr].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return Si(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return Si(this)?this[Xr].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{[Zr]=`ReadableStreamBYOBRequest`;[Xr];constructor(t){if(t!==mi)throw TypeError(`Illegal constructor`)}get view(){if(!Ci(this))throw TypeError(`Invalid this`);return this[Xr].view}respond(t){if(!Ci(this))throw TypeError(`Invalid this`);if(this[Xr].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[Xr].view;if(isDetachedBuffer(n.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Xr].controller,t)}respondWithNewView(t){if(!Ci(this))throw TypeError(`Invalid this`);if(this[Xr].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[Xr].controller,t)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[Zr]=`ReadableByteStreamController`;[Xr];constructor(t){if(t!==mi)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!xi(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!xi(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!xi(this))throw TypeError(`Invalid this`);if(this[Xr].closeRequested)throw TypeError(`Close already requested`);if(this[Xr].stream[Xr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(t){if(!xi(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[Xr].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Xr].stream[Xr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,t)}error(t=void 0){if(!xi(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,t)}[si](t){return readableByteStreamControllerCancelSteps(this,t)}[fi](t){readableByteStreamControllerPullSteps(this,t)}[pi](){if(this[Xr].pendingPullIntos.length>0){let t=this[Xr].pendingPullIntos[0];t.readerType=`none`,this[Xr].pendingPullIntos=[t]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const xi=isBrandCheck(`ReadableByteStreamController`),Si=isBrandCheck(`ReadableStreamBYOBReader`),Ci=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(t){let{reader:n}=t[Xr];return n===void 0?!1:n[Xr]!==void 0&&n[Zr]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(t){return t[Xr].reader[Xr].readIntoRequests.length}function readableStreamAddReadIntoRequest(t,n){t[Xr].reader[Xr].readIntoRequests.push(n)}function readableStreamFulfillReadIntoRequest(t,n,S){let{reader:C}=t[Xr],N=C[Xr].readIntoRequests.shift();S?N[ci](n):N[li](n)}function setupReadableStreamBYOBReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);if(!xi(n[Xr].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(t,n),t[Xr].readIntoRequests=[]}function readableStreamBYOBReaderRead(t,n,S,C){let{stream:N}=t[Xr];N[Xr].disturbed=!0,N[Xr].state===`errored`?C[di](N[Xr].storedError):readableByteStreamControllerPullInto(N[Xr].controller,n,S,C)}function readableStreamBYOBReaderRelease(t){readableStreamReaderGenericRelease(t);let n=TypeError(`Reader was released`);for(let S=0;S<t[Xr].readIntoRequests.length;S++)t[Xr].readIntoRequests[S][di](n);t[Xr].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(t){t[Xr].pullAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(t){readableByteStreamControllerInvalidateBYOBRequest(t),t[Xr].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(t){let n=t[Xr].byobRequest;n!=null&&(n[Xr].controller=void 0,n[Xr].view=null,t[Xr].byobRequest=null)}function readableByteStreamControllerError(t,n){let{stream:S}=t[Xr];S[Xr].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t),readableByteStreamControllerClearAlgorithms(t),readableStreamError(S,n))}function readableByteStreamControllerGetDesiredSize(t){let n=t[Xr].stream[Xr].state;return n===`errored`?null:n===`closed`?0:t[Xr].highWaterMark-t[Xr].queueTotalSize}function readableByteStreamControllerShouldCallPull(t){let{stream:n}=t[Xr];if(n[Xr].state!==`readable`||t[Xr].closeRequested||!t[Xr].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[Xr].pulling){t[Xr].pullAgain=!0;return}t[Xr].pulling=!0,t[Xr].pullAlgorithm(t).then(()=>{t[Xr].pulling=!1,t[Xr].pullAgain&&(t[Xr].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(t))},n=>readableByteStreamControllerError(t,n))}}function readableByteStreamControllerHandleQueueDrain(t){t[Xr].queueTotalSize===0&&t[Xr].closeRequested?(readableByteStreamControllerClearAlgorithms(t),readableStreamClose(t[Xr].stream)):readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerEnqueueChunkToQueue(t,n,S,C){t[Xr].queue.push({buffer:n,byteOffset:S,byteLength:C}),t[Xr].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[Xr].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[Xr].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[Xr].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[Xr].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[Xr].queueTotalSize-=C,readableByteStreamControllerFillHeadPullIntoDescriptor(t,C,n),N-=C}return F}function readableByteStreamControllerFillReadRequestFromQueue(t,n){let S=t[Xr].queue.shift();t[Xr].queueTotalSize-=S.byteLength,readableByteStreamControllerHandleQueueDrain(t);let C=new Uint8Array(S.buffer,S.byteOffset,S.byteLength);n[li](C)}function readableByteStreamControllerProcessReadRequestsUsingQueue(t){let n=t[Xr].stream[Xr].reader;for(;n[Xr].readRequests.length!==0;){if(t[Xr].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(t,n[Xr].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t){for(;t[Xr].pendingPullIntos.length!==0;){if(t[Xr].queueTotalSize===0)return;let n=t[Xr].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n)&&(readableByteStreamControllerShiftPendingPullInto(t),readableByteStreamControllerCommitPullIntoDescriptor(t[Xr].stream,n))}}function readableByteStreamControllerGetBYOBRequest(t){if(t[Xr].byobRequest===null&&t[Xr].pendingPullIntos.length!==0){let n=t[Xr].pendingPullIntos[0],S=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),C=new ReadableStreamBYOBRequest(mi);C[Xr]={controller:t,view:S},t[Xr].byobRequest=C}return t[Xr].byobRequest}function readableByteStreamControllerEnqueue(t,n){let{stream:S}=t[Xr];if(t[Xr].closeRequested||S[Xr].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[Xr].pendingPullIntos.length!==0){let n=t[Xr].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[Xr].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[Xr];if(!(t[Xr].closeRequested||n[Xr].state!==`readable`)){if(t[Xr].queueTotalSize>0){t[Xr].closeRequested=!0;return}if(t[Xr].pendingPullIntos.length!==0){let n=t[Xr].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[Xr].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[di](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[di](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[Xr].pendingPullIntos.length!==0){t[Xr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C);return}if(N[Xr].state===`closed`){let t=new I(te.buffer,te.byteOffset,0);C[ci](t);return}if(t[Xr].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,te)){let n=readableByteStreamControllerConvertPullIntoDescriptor(te);readableByteStreamControllerHandleQueueDrain(t),C[li](n);return}if(t[Xr].closeRequested){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(t,n),C[di](n);return}}t[Xr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespond(t,n){let S=t[Xr].pendingPullIntos[0];if(t[Xr].stream[Xr].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[Xr].pendingPullIntos[0],C=t[Xr].stream[Xr].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[Xr].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(t),t[Xr].stream[Xr].state===`closed`?readableByteStreamControllerRespondInClosedState(t,S):readableByteStreamControllerRespondInReadableState(t,n,S),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespondInClosedState(t,n){n.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(t);let S=t[Xr].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[Xr].stream,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)}function readableByteStreamControllerCancelSteps(t,n){readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t);let S=t[Xr].cancelAlgorithm?.(n)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(t),S}function readableByteStreamControllerPullSteps(t,n){let S=t[Xr].stream;if(t[Xr].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(t,n);return}let C=t[Xr].autoAllocateChunkSize;if(C!==void 0){let S;try{S=new ArrayBuffer(C)}catch(t){n[di](t);return}let N={buffer:S,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};t[Xr].pendingPullIntos.push(N)}readableStreamAddReadRequest(S,n),readableByteStreamControllerCallPullIfNeeded(t)}function setupReadableByteStreamController(t,n,S,C,N,F,I){n[Xr]={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[Xr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Xr].started=!0,readableByteStreamControllerCallPullIfNeeded(n)},t=>readableByteStreamControllerError(n,t))}function setupReadableByteStreamControllerFromSource(t,n,S){let C=new ReadableByteStreamController(mi),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[Xr].controller,X=q[Xr].controller,n.closed.catch(t=>{Y.error(t),X.error(t),(!C||!N)&&H.resolve()}),[W,q]}const wi=Symbol(`kSkipThrow`);var TransformStream=class{[Zr]=`TransformStream`;[Xr];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[Xr].controller))}get readable(){if(!Ti(this))throw TypeError(`Invalid this`);return this[Xr].readable}get writable(){if(!Ti(this))throw TypeError(`Invalid this`);return this[Xr].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[Zr]=`TransformStreamDefaultController`;[Xr];constructor(t){if(t!==wi)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!Ei(this))throw TypeError(`Invalid this`);let{stream:t}=this[Xr],{readable:n}=t[Xr],S=n[Xr].controller;return readableStreamDefaultControllerGetDesiredSize(S)}enqueue(t){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,t)}error(t){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,t)}terminate(){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Ti=isBrandCheck(`TransformStream`),Ei=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[Xr]={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[Xr];readableStreamDefaultControllerError(S[Xr].controller,n),transformStreamErrorWritableAndUnblockWrite(t,n)}function transformStreamErrorWritableAndUnblockWrite(t,n){let{controller:S,writable:C}=t[Xr];transformStreamDefaultControllerClearAlgorithms(S),writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t)}function transformStreamUnblockWrite(t){t[Xr].backpressure&&transformStreamSetBackpressure(t,!1)}function transformStreamSetBackpressure(t,n){t[Xr].backpressureChange.promise!==void 0&&t[Xr].backpressureChange.resolve?.(),t[Xr].backpressureChange=Promise.withResolvers(),t[Xr].backpressure=n}function setupTransformStreamDefaultController(t,n,S,C,N){n[Xr]={stream:t,transformAlgorithm:S,flushAlgorithm:C,cancelAlgorithm:N,finishPromise:void 0},t[Xr].controller=n}function setupTransformStreamDefaultControllerFromTransformer(t,n){let S=new TransformStreamDefaultController(wi),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[Xr].transformAlgorithm=void 0,t[Xr].flushAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(t,n){let{stream:S}=t[Xr],{readable:C}=S[Xr],N=C[Xr].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(N))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(N,n)}catch(t){throw transformStreamErrorWritableAndUnblockWrite(S,t),C[Xr].storedError}readableStreamDefaultControllerHasBackpressure(N)!==S[Xr].backpressure&&transformStreamSetBackpressure(S,!0)}function transformStreamDefaultControllerError(t,n){transformStreamError(t[Xr].stream,n)}async function transformStreamDefaultControllerPerformTransform(t,n){try{let S=t[Xr].transformAlgorithm;if(S===void 0)return;await S(n,t)}catch(n){throw transformStreamError(t[Xr].stream,n),n}}function transformStreamDefaultControllerTerminate(t){let{stream:n}=t[Xr],{readable:S}=n[Xr];readableStreamDefaultControllerClose(S[Xr].controller),transformStreamErrorWritableAndUnblockWrite(n,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(t,n){let{controller:S}=t[Xr];return t[Xr].backpressure?t[Xr].backpressureChange.promise.then(()=>{let{writable:C}=t[Xr];if(C[Xr].state===`erroring`)throw C[Xr].storedError;return transformStreamDefaultControllerPerformTransform(S,n)}):transformStreamDefaultControllerPerformTransform(S,n)}async function transformStreamDefaultSinkAbortAlgorithm(t,n){let{controller:S,readable:C}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Xr].finishPromise=N;let H=S[Xr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Xr].state===`errored`?I(C[Xr].storedError):(readableStreamDefaultControllerError(C[Xr].controller,n),F())},t=>{readableStreamDefaultControllerError(C[Xr].controller,t),I(t)}),S[Xr].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(t){let{readable:n,controller:S}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:C,resolve:N,reject:F}=Promise.withResolvers();S[Xr].finishPromise=C;let I=S[Xr].flushAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(S),I.then(()=>{n[Xr].state===`errored`?F(n[Xr].storedError):(readableStreamDefaultControllerClose(n[Xr].controller),N())},t=>{readableStreamDefaultControllerError(n[Xr].controller,t),F(t)}),S[Xr].finishPromise}function transformStreamDefaultSourcePullAlgorithm(t){return transformStreamSetBackpressure(t,!1),t[Xr].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(t,n){let{controller:S,writable:C}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Xr].finishPromise=N;let H=S[Xr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Xr].state===`errored`?I(C[Xr].storedError):(writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t),F())},n=>{writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t),I(n)}),S[Xr].finishPromise}const Di=Object.defineProperty(t=>t.byteLength,"name",{value:`size`}),Oi=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 Di}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 Oi}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 ki=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),ki)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 Ai=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,ji=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,Mi=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,Ni=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,Pi=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,Fi=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,Ii=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 "${Ri}" 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 Li;if(typeof n!=`number`)throw withCode(TypeError(`The "${Ri}" property must be of type number. Received ${describeType(n)}`),`ERR_INVALID_ARG_TYPE`);if(Number.isNaN(n))return Li;if(!Number.isFinite(n))throw outOfRange(`a finite number`,n);if(n<1||n>Li)throw outOfRange(`>= 1 and <= ${Li}`,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 Li,Ri,zi=__esmMin(()=>{Li=2**53-1,Ri=`options.maxOutputLength`}),Bi,Vi=__esmMin(()=>{Bi=n}),Hi,Ui=__esmMin(()=>{Vi(),Hi=Bi});function getGioFormat(t){switch(t){case`gzip`:return Hi.ZlibCompressorFormat.GZIP;case`deflate`:return Hi.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return Hi.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 Hi.ZlibCompressor({format:getGioFormat(n),level:Math.trunc(S)}),N=new Hi.ConverterOutputStream({base_stream:Hi.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new vt.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=Li,C=0){let N=new Hi.ZlibDecompressor({format:getGioFormat(n)}),F=Hi.MemoryInputStream.new_from_bytes(new vt.Bytes(t)),I=new Hi.ConverterInputStream({base_stream:F,converter:N}),H=[],W=C;try{for(;;){let t=Math.min(Gi,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 Hi.ZlibDecompressor({format:Hi.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0,F=0;for(;;){let I=t.subarray(N,N+Wi);try{let[t,H,W]=S.convert(I,C,Hi.ConverterFlags.NONE);if(N+=H,F+=W,t===Hi.ConverterResult.FINISHED||F>n||H===0&&W===0)return N}catch{return N}}}function gunzipWithGio(t,n=Li){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 Wi,Gi,Ki=__esmMin(()=>{zi(),Ui(),yt(),Wi=256*1024,Gi=1024*1024,__name$1(concat$2,`concat`)}),qi=__esmMin(()=>{Ye()}),Ji,Yi,Xi=__esmMin(()=>{Ji=Object.defineProperty,Yi=__name$1((t,n)=>{let S={};for(var C in t)Ji(S,C,{get:t[C],enumerable:!0});return n||Ji(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function _setPipeImpl(t){Zi=t}var Zi,Stream_,Qi=__esmMin(()=>{on(),Stream_=class extends Jt{constructor(t){super(t)}pipe(t,n){return Zi(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 $i=__esmMin(()=>{Qi(),Ye(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(t){return t?ta:ea}function setDefaultHighWaterMark(t,n){if(typeof n!=`number`||n<0||Number.isNaN(n))throw TypeError(`Invalid highWaterMark: ${n}`);t?ta=n:ea=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 ea,ta,na=__esmMin(()=>{ea=16384,ta=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 ra,ia=__esmMin(()=>{$i(),ra=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 aa,oa,sa,ca=__esmMin(()=>{Qi(),ia(),na(),Ye(),aa=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)}},aa.prototype[ra]=function(){return streamAsyncDispose(this,this.readableEnded)},oa=Object.getOwnPropertyDescriptor(aa.prototype,`on`),sa=Object.getOwnPropertyDescriptor(aa.prototype,`removeListener`),Object.defineProperty(aa.prototype,"addListener",{...oa}),Object.defineProperty(aa.prototype,"off",{...sa})});function writeAfterEndError(){let t=Error(`write after end`);return t.code=`ERR_STREAM_WRITE_AFTER_END`,t}var la=__esmMin(()=>{});function chunkLen$1(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Duplex_,ua=__esmMin(()=>{la(),na(),ca(),Ye(),Duplex_=class extends aa{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;_autoClosed=!1;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),this.destroy()}),!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._closeAfterFinish()),S&&S()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_closeAfterFinish(){this._autoClosed||!this.destroyed&&!this._readableState.endEmitted&&this.readable||(this._autoClosed=!0,this.emit(`close`))}_autoClose(){this._autoClosed||(this._autoClosed=!0,this.emit(`close`))}_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 aa))){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 aa&&(C._pipeDests.push({dest:n,cleanup}),C._readableState.pipes.push(n)),n.emit(`pipe`,C),n}var da=__esmMin(()=>{Qi(),ca(),_setPipeImpl(pipe)});function chunkLen(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var fa,pa=__esmMin(()=>{la(),Qi(),ia(),na(),Ye(),fa=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}},fa.prototype[ra]=function(){return streamAsyncDispose(this,this.writableFinished)}}),ma,ha=__esmMin(()=>{ua(),Ye(),ma=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_,ga=__esmMin(()=>{ha(),PassThrough_=class extends ma{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 _a=__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 va,ya,ba=__esmMin(()=>{Xi(),$i(),_a(),va=Yi({default:()=>ya,finished:()=>finished,pipeline:()=>pipeline}),ya={pipeline,finished}}),xa=__exportAll$5({Duplex:()=>Ta,PassThrough:()=>Da,Readable:()=>Ca,Stream:()=>Sa,Transform:()=>Ea,Writable:()=>wa,addAbortSignal:()=>addAbortSignal,default:()=>Oa,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>Oa,pipeline:()=>pipeline$1,promises:()=>va,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),Sa,Ca,wa,Ta,Ea,Da,Oa,ka=__esmMin(()=>{qi(),Qi(),$i(),na(),ca(),ua(),da(),pa(),ha(),ga(),_a(),ba(),Sa=makeCallable(Stream_),Ca=makeCallable(aa),wa=makeCallable(fa),Ta=makeCallable(Duplex_),Ea=makeCallable(ma),Da=makeCallable(PassThrough_),Oa=Object.assign(Sa,{Stream:Sa,Readable:Ca,Writable:wa,Duplex:Ta,Transform:Ea,PassThrough:Da,pipeline:pipeline$1,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark,promises:va})});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,Aa=__esmMin(()=>{zi(),Ki(),ka(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends Ea{_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 Ea{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends Ea{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends Ea{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 Ea{constructor(){super();let t=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}}}),ja=__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:()=>Na,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>Pa,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>=Li)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`),Ma)}function brotliDecompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliDecompress: Brotli is not supported in this environment`),Ma)}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,Ma)}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,Ma)}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,Ma,Na,Pa,Fa=__esmMin(()=>{zi(),Ki(),Aa(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),Ma=new Uint8Array,Na={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},Pa={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:Na}});const Ia=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(t){if(!Ia.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 Ra=!1,za,Ba,Va,Ha,Ua,Wa;async function loadZlib(){if(Ra)return;let t=await Promise.resolve().then(()=>(Fa(),ja));za=t.gzipSync,Ba=t.gunzipSync,Va=t.deflateSync,Ha=t.inflateSync,Ua=t.deflateRawSync,Wa=t.inflateRawSync,Ra=!0}function getCompressFn(t){switch(t){case`gzip`:return t=>za(t);case`deflate`:return t=>Va(t);case`deflate-raw`:return t=>Ua(t)}}function getDecompressFn(t){switch(t){case`gzip`:return t=>Ba(t);case`deflate`:return t=>Ha(t);case`deflate-raw`:return t=>Wa(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 Ga,Ka;if(La)Ga=globalThis.CompressionStream,Ka=globalThis.DecompressionStream;else{let t=loadZlib();Ga=class CompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new Mi({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}},Ka=class DecompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new Mi({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 qa=globalThis;globalThis.CompressionStream===void 0&&(qa.CompressionStream=Ga),globalThis.DecompressionStream===void 0&&(qa.DecompressionStream=Ka);const Ja=globalThis;globalThis.DOMException===void 0&&(Ja.DOMException=Ar);var Ya,__name,Xa=__esmMin(()=>{Ya=Object.defineProperty,__name=(t,n)=>Ya(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 Za=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 Qa=class Headers{[Za];constructor(t){if(this[Za]=new Map,t!=null){if(t instanceof Headers){for(let[n,S]of t[Za])this[Za].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[Za].get(S);N?N.push(C):this[Za].set(S,[C])}set(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase();this[Za].set(S,[String(n)])}delete(t){this[Za].delete(String(t).toLowerCase())}has(t){return this[Za].has(String(t).toLowerCase())}get(t){let n=this[Za].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[Za].get(String(t).toLowerCase())??[]}getSetCookie(){return this[Za].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[Za].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(Qa.prototype,[`get`,`entries`,`forEach`,`values`].reduce((t,n)=>(t[n]={enumerable:!0},t),{}));var $a=__esmMin(()=>{ht()});$a();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)}};cr();const eo=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[eo]===`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[eo])},isAbortSignal=t=>{if(typeof t!=`object`||!t)return!1;let n=t;return n[eo]===`AbortSignal`||n[eo]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let S=new ar(n).hostname,C=new ar(t).hostname;return S===C||S.endsWith(`.${C}`)},isSameProtocol=(t,n)=>new ar(n).protocol===new ar(t).protocol;var to=__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$1,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 no,ro,lower,noop,MultipartParser,io=__esmMin(()=>{hr(),no=1,ro={PART_BOUNDARY:no,LAST_BOUNDARY:no*=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
+ `)}return S.push(`--${n}--`),new Blob(S,{type:`multipart/form-data; boundary=${n}`})}var fr=__esmMin(()=>{dr()});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 pr,FormData$1,mr=__esmMin(()=>{dr(),pr=Symbol(`FormData.entries`),FormData$1=class{static{__name$1(this,`FormData`)}[pr]=[];constructor(){}append(t,n,S){this[pr].push({name:String(t),value:normalizeValue(t,n,S)})}delete(t){let n=String(t);this[pr]=this[pr].filter(t=>t.name!==n)}get(t){let n=String(t),S=this[pr].find(t=>t.name===n);return S?S.value:null}getAll(t){let n=String(t);return this[pr].filter(t=>t.name===n).map(t=>t.value)}has(t){let n=String(t);return this[pr].some(t=>t.name===n)}set(t,n,S){let C=String(t),N=normalizeValue(C,n,S),F=!1;this[pr]=this[pr].filter(t=>t.name===C?F?!1:(F=!0,t.value=N,!0):!0),F||this[pr].push({name:C,value:N})}forEach(t,n){for(let S of this[pr])t.call(n,S.value,S.name,this)}*entries(){for(let t of this[pr])yield[t.name,t.value]}*keys(){for(let t of this[pr])yield t.name}*values(){for(let t of this[pr])yield t.value}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`FormData`}}}),hr=__esmMin(()=>{fr(),mr()});hr();const gr=globalThis;typeof globalThis.FormData!=`function`&&(gr.FormData=FormData$1);var _r=__exportAll$5({PerformanceEntry:()=>Sr,PerformanceMark:()=>wr,PerformanceMeasure:()=>Tr,PerformanceObserver:()=>br,PerformanceObserverEntryList:()=>Cr,default:()=>Er,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>vr,timerify:()=>timerify});function eventLoopUtilization(t,n){return{idle:0,active:0,utilization:0}}function timerify(t){let wrapped=function(...n){let S=vr.now(),C=t.apply(this,n);return vr.now()-S,C};return Object.defineProperty(wrapped,"name",{value:t.name}),wrapped}function monitorEventLoopDelay(t){let n=t?.resolution??10,S=[],C=0,N,sorted=()=>S.slice().sort((t,n)=>t-n),percentile=t=>{if(S.length===0)return 0;let n=sorted();return n[Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1))]};return{enable(){return N?!1:(N=startLagMonitor({intervalMs:n,thresholdMs:1e3,onSample:t=>{S.push(Math.round((n+t)*1e6)),t>1e3&&(C+=1)}}),!0)},disable(){return N?(N.stop(),N=void 0,!0):!1},reset(){S=[],C=0},percentile,get count(){return S.length},get exceeds(){return C},get min(){return S.length?Math.min(...S):0x8000000000000000},get max(){return S.length?Math.max(...S):0},get mean(){return S.length?S.reduce((t,n)=>t+n,0)/S.length:NaN},get stddev(){if(!S.length)return NaN;let t=S.reduce((t,n)=>t+n,0)/S.length;return Math.sqrt(S.reduce((n,S)=>n+(S-t)**2,0)/S.length)},get percentiles(){let t=new Map;if(!S.length)return t.set(100,0);for(let n of[0,50,75,87.5,93.75,96.875,98.4375,99.21875,100])t.set(n,percentile(n));return t}}}var vr,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,yr,br,Sr,Cr,wr,Tr,Er,Dr=__esmMin(()=>{if(Ue(),globalThis.performance)vr=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();vr={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[]}},yr=globalThis,br=yr.PerformanceObserver||PerformanceObserverStub,Sr=yr.PerformanceEntry||PerformanceEntryStub,Cr=yr.PerformanceObserverEntryList||PerformanceObserverEntryListStub,wr=yr.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},Tr=yr.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Er={performance:vr,PerformanceObserver:br,PerformanceEntry:Sr,PerformanceObserverEntryList:Cr,PerformanceMark:wr,PerformanceMeasure:Tr,eventLoopUtilization,timerify,monitorEventLoopDelay}});Dr();const Or=globalThis;globalThis.performance===void 0&&(Or.performance=vr),typeof Or.PerformanceObserver!=`function`&&(Or.PerformanceObserver=br);const kr={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(kr,this.name)?kr[this.name]:0}};const Ar=globalThis.DOMException??_DOMExceptionPolyfill;_e();const jr=Symbol(`type`),Mr=Symbol(`bubbles`),Nr=Symbol(`cancelable`),Pr=Symbol(`composed`),Fr=Symbol(`target`),Ir=Symbol(`currentTarget`),Lr=Symbol(`eventPhase`),Rr=Symbol(`defaultPrevented`),zr=Symbol(`isTrusted`),Br=Symbol(`timeStamp`),Vr=Symbol(`stop`),Hr=Symbol(`immediateStop`),Ur=Symbol(`dispatching`),Wr=Symbol(`inPassiveListener`);var Event=class{[jr];[Mr];[Nr];[Pr];[Fr]=null;[Ir]=null;[Lr]=0;[Rr]=!1;[zr]=!1;[Br];[Vr]=!1;[Hr]=!1;[Ur]=!1;[Wr]=!1;get type(){return this[jr]}get bubbles(){return this[Mr]}get cancelable(){return this[Nr]}get composed(){return this[Pr]}get target(){return this[Fr]}get currentTarget(){return this[Ir]}get eventPhase(){return this[Lr]}get defaultPrevented(){return this[Rr]}get timeStamp(){return this[Br]}get cancelBubble(){return this[Vr]}set cancelBubble(t){t&&this.stopPropagation()}get returnValue(){return!this[Rr]}set returnValue(t){t||this.preventDefault()}get srcElement(){return this[Fr]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(t,n){this[jr]=t,this[Mr]=n?.bubbles??!1,this[Nr]=n?.cancelable??!1,this[Pr]=n?.composed??!1,this[Br]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[zr],enumerable:!0,configurable:!1})}composedPath(){return this[Ir]?[this[Ir]]:[]}preventDefault(){this[Nr]&&!this[Wr]&&(this[Rr]=!0)}stopPropagation(){this[Vr]=!0}stopImmediatePropagation(){this[Vr]=!0,this[Hr]=!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[Ur])throw new Ar(`The event is already being dispatched.`,`InvalidStateError`);n[Ur]=!0,n[Fr]=this,n[Ir]=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[Hr]||n[Vr])break;S.once&&this.removeEventListener(t.type,S.listener,{capture:S.capture});try{S.passive&&(n[Wr]=!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[Wr]=!1}}}}finally{n[Lr]=Event.NONE,n[Ir]=null,n[Ur]=!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 Gr=Symbol(`abort`),Kr=Symbol(`internal`);var qr=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(t){if(super(),t!==Kr)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}[Gr](t){if(this.#e)return;this.#e=!0,this.#t=t??new Ar(`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(Kr);return n[Gr](t),n}static timeout(t){let n=new AbortSignal(Kr);return setTimeout(()=>{n[Gr](new Ar(`The operation timed out.`,`TimeoutError`))},t),n}static any(t){let n=new AbortSignal(Kr);for(let S of t)if(S.aborted)return n[Gr](S.reason),n;let onAbort=()=>{if(!n.aborted){let S=t.find(t=>t.aborted);n[Gr](S?.reason)}};for(let n of t)n.addEventListener(`abort`,onAbort,{once:!0});return n}},Jr=class AbortController{signal;constructor(){this.signal=new qr(Kr)}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[Gr](t)}};const Yr=globalThis;globalThis.AbortController===void 0&&(Yr.AbortController=Jr),globalThis.AbortSignal===void 0&&(Yr.AbortSignal=qr);const Xr=Symbol(`kState`),Zr=Symbol(`kType`);function isBrandCheck(t){return n=>typeof n==`object`&&!!n&&n[Xr]!==void 0&&n[Zr]===t}function dequeueValue(t){let n=t[Xr].queue.shift();if(n===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:S,size:C}=n;return t[Xr].queueTotalSize=Math.max(0,t[Xr].queueTotalSize-C),S}function resetQueue(t){t[Xr].queue=[],t[Xr].queueTotalSize=0}function peekQueueValue(t){return t[Xr].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[Xr].queue.push({value:n,size:S}),t[Xr].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 Qr={__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 $r=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}},ei=Symbol(`kAbort`),ti=Symbol(`kCloseSentinel`),ni=Symbol(`kError`),ri=Symbol(`kSkipThrow`);var WritableStream=class{[Zr]=`WritableStream`;[Xr];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[Xr]=createWritableStreamState();let C=extractSizeAlgorithm(n?.size),N=extractHighWaterMark(n?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,t,N,C)}get locked(){if(!ii(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(t){return ii(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){return ii(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(!ii(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[Zr]=`WritableStreamDefaultWriter`;[Xr];constructor(t){if(!ii(t))throw TypeError(`Expected a WritableStream`);this[Xr]={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 ai(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!ai(this))throw TypeError(`Invalid this`);if(this[Xr].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return ai(this)?this[Xr].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(t){return ai(this)?this[Xr].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,t):Promise.reject(TypeError(`Invalid this`))}close(){if(!ai(this))return Promise.reject(TypeError(`Invalid this`));let{stream:t}=this[Xr];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(!ai(this))throw TypeError(`Invalid this`);let{stream:t}=this[Xr];t!==void 0&&writableStreamDefaultWriterRelease(this)}write(t){return ai(this)?this[Xr].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{[Zr]=`WritableStreamDefaultController`;[Xr];constructor(t){if(t!==ri)throw TypeError(`Illegal constructor`)}[ei](t){let n=this[Xr].abortAlgorithm(t);return writableStreamDefaultControllerClearAlgorithms(this),n}[ni](){resetQueue(this)}get signal(){if(!oi(this))throw TypeError(`Invalid this`);return this[Xr].abortController.signal}error(t){if(!oi(this))throw TypeError(`Invalid this`);this[Xr].stream[Xr].state===`writable`&&writableStreamDefaultControllerError(this,t)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const ii=isBrandCheck(`WritableStream`),ai=isBrandCheck(`WritableStreamDefaultWriter`),oi=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[Xr].writer!==void 0}function setupWritableStreamDefaultWriter(t,n){if(isWritableStreamLocked(n))throw TypeError(`WritableStream is locked`);switch(t[Xr].stream=n,n[Xr].writer=t,n[Xr].state){case`writable`:!writableStreamCloseQueuedOrInFlight(n)&&n[Xr].backpressure?t[Xr].ready=Promise.withResolvers():t[Xr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Xr].close=Promise.withResolvers();break;case`erroring`:t[Xr].ready={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise),t[Xr].close=Promise.withResolvers();break;case`closed`:t[Xr].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},t[Xr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:t[Xr].ready={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},t[Xr].close={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise),setPromiseHandled(t[Xr].close.promise)}}function writableStreamAbort(t,n){let{state:S,controller:C}=t[Xr];if(S===`closed`||S===`errored`)return Promise.resolve();if(C[Xr].abortController.abort(n),t[Xr].pendingAbortRequest.abort.promise!==void 0)return t[Xr].pendingAbortRequest.abort.promise;let N=!1;S===`erroring`&&(N=!0,n=void 0);let F=Promise.withResolvers();return t[Xr].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[Xr];if(n===`closed`||n===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));t[Xr].closeRequest=Promise.withResolvers();let{promise:F}=t[Xr].closeRequest;return S!==void 0&&C&&n===`writable`&&S[Xr].ready.resolve?.(),writableStreamDefaultControllerClose(N),F}function writableStreamUpdateBackpressure(t,n){let{writer:S}=t[Xr];S!==void 0&&t[Xr].backpressure!==n&&(n?S[Xr].ready=Promise.withResolvers():S[Xr].ready.resolve?.()),t[Xr].backpressure=n}function writableStreamStartErroring(t,n){let{controller:S,writer:C}=t[Xr];t[Xr].state=`erroring`,t[Xr].storedError=n,C!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(C,n),!writableStreamHasOperationMarkedInFlight(t)&&S[Xr].started&&writableStreamFinishErroring(t)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(t){t[Xr].closeRequest.promise!==void 0&&(t[Xr].closeRequest.reject?.(t[Xr].storedError),t[Xr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(t[Xr].close.promise),t[Xr].close.reject?.(t[Xr].storedError);let{writer:n}=t[Xr];n!==void 0&&(setPromiseHandled(n[Xr].close.promise),n[Xr].close.reject?.(t[Xr].storedError))}function writableStreamMarkFirstWriteRequestInFlight(t){let n=t[Xr].writeRequests.shift();t[Xr].inFlightWriteRequest=n}function writableStreamMarkCloseRequestInFlight(t){t[Xr].inFlightCloseRequest=t[Xr].closeRequest,t[Xr].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(t){return t[Xr].inFlightWriteRequest.promise!==void 0||t[Xr].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(t,n){t[Xr].inFlightWriteRequest.reject?.(n),t[Xr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightWrite(t){t[Xr].inFlightWriteRequest.resolve?.(),t[Xr].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(t,n){t[Xr].inFlightCloseRequest.reject?.(n),t[Xr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Xr].pendingAbortRequest.abort.promise!==void 0&&(t[Xr].pendingAbortRequest.abort.reject?.(n),t[Xr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(t,n)}function writableStreamFinishInFlightClose(t){t[Xr].inFlightCloseRequest.resolve?.(),t[Xr].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},t[Xr].state===`erroring`&&(t[Xr].storedError=void 0,t[Xr].pendingAbortRequest.abort.promise!==void 0&&(t[Xr].pendingAbortRequest.abort.resolve?.(),t[Xr].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),t[Xr].state=`closed`,t[Xr].writer!==void 0&&t[Xr].writer[Xr].close.resolve?.(),t[Xr].close.resolve?.()}function writableStreamFinishErroring(t){t[Xr].state=`errored`,t[Xr].controller[ni]();let n=t[Xr].storedError;for(let S of t[Xr].writeRequests)S.reject?.(n);if(t[Xr].writeRequests=[],t[Xr].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(t);return}let S=t[Xr].pendingAbortRequest;if(t[Xr].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[Xr].controller[ei](S.reason).then(()=>{S.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)},n=>{S.abort.reject?.(n),writableStreamRejectCloseAndClosedPromiseIfNeeded(t)})}function writableStreamDealWithRejection(t,n){if(t[Xr].state===`writable`){writableStreamStartErroring(t,n);return}writableStreamFinishErroring(t)}function writableStreamCloseQueuedOrInFlight(t){return t[Xr].closeRequest.promise!==void 0||t[Xr].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(t){let{promise:n,resolve:S,reject:C}=Promise.withResolvers();return t[Xr].writeRequests.push({promise:n,resolve:S,reject:C}),n}function writableStreamDefaultWriterWrite(t,n){let{stream:S}=t[Xr],{controller:C}=S[Xr],N=writableStreamDefaultControllerGetChunkSize(C,n);if(S!==t[Xr].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:F}=S[Xr];if(F===`errored`)return Promise.reject(S[Xr].storedError);if(writableStreamCloseQueuedOrInFlight(S)||F===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(F===`erroring`)return Promise.reject(S[Xr].storedError);let I=writableStreamAddWriteRequest(S);return writableStreamDefaultControllerWrite(C,n,N),I}function writableStreamDefaultWriterRelease(t){let{stream:n}=t[Xr],S=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(t,S),writableStreamDefaultWriterEnsureClosedPromiseRejected(t,S),n[Xr].writer=void 0,t[Xr].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(t){let{stream:n}=t[Xr];switch(n[Xr].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(n[Xr].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(t,n){t[Xr].ready.reject?(t[Xr].ready.reject(n),t[Xr].ready.resolve=void 0,t[Xr].ready.reject=void 0):t[Xr].ready={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(t,n){t[Xr].close.reject?(t[Xr].close.reject(n),t[Xr].close.resolve=void 0,t[Xr].close.reject=void 0):t[Xr].close={promise:Promise.reject(n),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(t){let{stream:n}=t[Xr],{state:S}=n[Xr];return writableStreamCloseQueuedOrInFlight(n)||S===`closed`?Promise.resolve():S===`errored`?Promise.reject(n[Xr].storedError):writableStreamDefaultWriterClose(t)}function writableStreamDefaultWriterClose(t){return writableStreamClose(t[Xr].stream)}function writableStreamDefaultWriterAbort(t,n){return writableStreamAbort(t[Xr].stream,n)}function writableStreamDefaultControllerWrite(t,n,S){try{enqueueValueWithSize(t,n,S)}catch(n){writableStreamDefaultControllerErrorIfNeeded(t,n);return}let{stream:C}=t[Xr];!writableStreamCloseQueuedOrInFlight(C)&&C[Xr].state===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerProcessWrite(t,n){let{stream:S,writeAlgorithm:C}=t[Xr];writableStreamMarkFirstWriteRequestInFlight(S),C(n,t).then(()=>{writableStreamFinishInFlightWrite(S);let{state:n}=S[Xr];dequeueValue(t),!writableStreamCloseQueuedOrInFlight(S)&&n===`writable`&&writableStreamUpdateBackpressure(S,writableStreamDefaultControllerGetBackpressure(t)),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)},n=>{S[Xr].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(t),writableStreamFinishInFlightWriteWithError(S,n)})}function writableStreamDefaultControllerProcessClose(t){let{closeAlgorithm:n,stream:S}=t[Xr];writableStreamMarkCloseRequestInFlight(S),dequeueValue(t);let C=n();writableStreamDefaultControllerClearAlgorithms(t),C.then(()=>writableStreamFinishInFlightClose(S),t=>writableStreamFinishInFlightCloseWithError(S,t))}function writableStreamDefaultControllerGetDesiredSize(t){return t[Xr].highWaterMark-t[Xr].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(t,n){let{sizeAlgorithm:S}=t[Xr];if(S===void 0)return 1;try{return S(n)}catch(n){return writableStreamDefaultControllerErrorIfNeeded(t,n),1}}function writableStreamDefaultControllerErrorIfNeeded(t,n){t[Xr].stream[Xr].state===`writable`&&writableStreamDefaultControllerError(t,n)}function writableStreamDefaultControllerError(t,n){writableStreamDefaultControllerClearAlgorithms(t),writableStreamStartErroring(t[Xr].stream,n)}function writableStreamDefaultControllerClose(t){enqueueValueWithSize(t,ti,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(t)}function writableStreamDefaultControllerClearAlgorithms(t){t[Xr].writeAlgorithm=void 0,t[Xr].closeAlgorithm=void 0,t[Xr].abortAlgorithm=void 0,t[Xr].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(t){return writableStreamDefaultControllerGetDesiredSize(t)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(t){let{queue:n,started:S,stream:C}=t[Xr];if(!S||C[Xr].inFlightWriteRequest.promise!==void 0)return;if(C[Xr].state===`erroring`){writableStreamFinishErroring(C);return}if(!n.length)return;let N=peekQueueValue(t);N===ti?writableStreamDefaultControllerProcessClose(t):writableStreamDefaultControllerProcessWrite(t,N)}function setupWritableStreamDefaultControllerFromSink(t,n,S,C){let N=new WritableStreamDefaultController(ri),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[Xr]={abortAlgorithm:F,closeAlgorithm:N,highWaterMark:I,queue:[],queueTotalSize:0,abortController:new $r,sizeAlgorithm:H,started:!1,stream:t,writeAlgorithm:C},t[Xr].controller=n,writableStreamUpdateBackpressure(t,writableStreamDefaultControllerGetBackpressure(n));let W=S();new Promise(t=>t(W)).then(()=>{n[Xr].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{n[Xr].started=!0,writableStreamDealWithRejection(t,S)})}function createWritableStream(t,n,S,C,N=1,F=()=>1){let I=Object.create(WritableStream.prototype);return I[Zr]=`WritableStream`,I[Xr]=createWritableStreamState(),setupWritableStreamDefaultController(I,new WritableStreamDefaultController(ri),t,n,S,C,N,F),I}Ye();const si=Symbol(`kCancel`),ci=Symbol(`kClose`),li=Symbol(`kChunk`),di=Symbol(`kError`),fi=Symbol(`kPull`),pi=Symbol(`kRelease`),mi=Symbol(`kSkipThrow`);let hi,_i;function lazyReadableReleasedError(){return hi||(hi=TypeError(`Reader released`),hi)}function lazyReadableReleasingError(){return _i||(_i=TypeError(`Releasing reader`),_i)}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`)}[Zr]=`ReadableStream`;[Xr];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[Xr]=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(!vi(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(t){return readableStreamFromIterable(t)}cancel(t=void 0){return vi(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,t):Promise.reject(TypeError(`Invalid this`))}getReader(t={}){if(!vi(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(!vi(this))throw TypeError(`Invalid this`);let S=t?.readable;if(!vi(S))throw TypeError(`transform.readable must be a ReadableStream`);let C=t?.writable;if(!ii(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(!vi(this))throw TypeError(`Invalid this`);if(!ii(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(!vi(this))throw TypeError(`Invalid this`);let t=this[Xr].controller;return xi(t)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(t={}){if(!vi(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[Xr].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,{[li](t){C.current=void 0,n({value:t,done:!1})},[ci](){C.current=void 0,C.done=!0,readableStreamReaderGenericRelease(S),n({done:!0,value:void 0})},[di](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[Xr].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}},Qr)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Xr];constructor(){this[Xr]=Promise.withResolvers()}[li](t){this[Xr].resolve?.({value:t,done:!1})}[ci](){this[Xr].resolve?.({value:void 0,done:!0})}[di](t){this[Xr].reject?.(t)}get promise(){return this[Xr].promise}},ReadableStreamDefaultReader=class{[Zr]=`ReadableStreamDefaultReader`;[Xr];constructor(t){if(!vi(t))throw TypeError(`Expected a ReadableStream`);this[Xr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,t)}read(){if(!bi(this))return Promise.reject(TypeError(`Invalid this`));if(this[Xr].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let t=this[Xr].stream,n=t[Xr].controller;if(t[Xr].state===`readable`&&yi(n)&&n[Xr].queue.length>0){t[Xr].disturbed=!0;let S=dequeueValue(n);return n[Xr].closeRequested&&!n[Xr].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(!bi(this))throw TypeError(`Invalid this`);this[Xr].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return bi(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return bi(this)?this[Xr].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{[Zr]=`ReadableStreamDefaultController`;[Xr];constructor(t){if(t!==mi)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)}[si](t){return readableStreamDefaultControllerCancelSteps(this,t)}[fi](t){readableStreamDefaultControllerPullSteps(this,t)}[pi](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const vi=isBrandCheck(`ReadableStream`),yi=isBrandCheck(`ReadableStreamDefaultController`),bi=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(t){return t[Xr].reader!==void 0}function readableStreamCancel(t,n){switch(t[Xr].disturbed=!0,t[Xr].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(t[Xr].storedError)}readableStreamClose(t);let S=t[Xr].reader;if(S!==void 0&&readableStreamHasBYOBReader(t)){let t=S[Xr].readIntoRequests;S[Xr].readIntoRequests=[];for(let n=0;n<t.length;n++)t[n][ci](void 0)}return t[Xr].controller[si](n).then(()=>{})}function readableStreamClose(t){t[Xr].state=`closed`,t[Xr].closedPromise.resolve();let{reader:n}=t[Xr];if(n!==void 0&&(n[Xr].close.resolve?.(),readableStreamHasDefaultReader(t))){for(let t=0;t<n[Xr].readRequests.length;t++)n[Xr].readRequests[t][ci]();n[Xr].readRequests=[]}}function readableStreamError(t,n){t[Xr].state=`errored`,t[Xr].storedError=n,setPromiseHandled(t[Xr].closedPromise.promise),t[Xr].closedPromise.reject(n);let{reader:S}=t[Xr];if(S!==void 0){if(setPromiseHandled(S[Xr].close.promise),S[Xr].close.reject?.(n),readableStreamHasDefaultReader(t)){for(let t=0;t<S[Xr].readRequests.length;t++)S[Xr].readRequests[t][di](n);S[Xr].readRequests=[]}else if(readableStreamHasBYOBReader(t)){for(let t=0;t<S[Xr].readIntoRequests.length;t++)S[Xr].readIntoRequests[t][di](n);S[Xr].readIntoRequests=[]}}}function readableStreamHasDefaultReader(t){let{reader:n}=t[Xr];return n===void 0?!1:n[Xr]!==void 0&&n[Zr]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(t){return t[Xr].reader[Xr].readRequests.length}function readableStreamFulfillReadRequest(t,n,S){let{reader:C}=t[Xr],N=C[Xr].readRequests.shift();S?N[ci]():N[li](n)}function readableStreamAddReadRequest(t,n){t[Xr].reader[Xr].readRequests.push(n)}function readableStreamReaderGenericCancel(t,n){let{stream:S}=t[Xr];return readableStreamCancel(S,n)}function readableStreamReaderGenericInitialize(t,n){switch(t[Xr].stream=n,n[Xr].reader=t,n[Xr].state){case`readable`:t[Xr].close=Promise.withResolvers();break;case`closed`:t[Xr].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:t[Xr].close={promise:Promise.reject(n[Xr].storedError),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise);break}}function readableStreamReaderGenericRelease(t){let{stream:n}=t[Xr],S=lazyReadableReleasedError();n[Xr].state===`readable`?t[Xr].close.reject?.(S):t[Xr].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(t[Xr].close.promise),n[Xr].controller[pi](),n[Xr].reader=void 0,t[Xr].stream=void 0}function readableStreamDefaultReaderRelease(t){readableStreamReaderGenericRelease(t),readableStreamDefaultReaderErrorReadRequests(t,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(t,n){for(let S=0;S<t[Xr].readRequests.length;++S)t[Xr].readRequests[S][di](n);t[Xr].readRequests=[]}function readableStreamDefaultReaderRead(t,n){let{stream:S}=t[Xr];switch(S[Xr].disturbed=!0,S[Xr].state){case`closed`:n[ci]();break;case`errored`:n[di](S[Xr].storedError);break;case`readable`:S[Xr].controller[fi](n);break}}function setupReadableStreamDefaultReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(t,n),t[Xr].readRequests=[]}function readableStreamDefaultControllerClose(t){readableStreamDefaultControllerCanCloseOrEnqueue(t)&&(t[Xr].closeRequested=!0,t[Xr].queue.length||(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(t[Xr].stream)))}function readableStreamDefaultControllerEnqueue(t,n){if(!readableStreamDefaultControllerCanCloseOrEnqueue(t))return;let{stream:S}=t[Xr];if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))readableStreamFulfillReadRequest(S,n,!1);else try{enqueueValueWithSize(t,n,t[Xr].sizeAlgorithm(n))}catch(n){throw readableStreamDefaultControllerError(t,n),n}readableStreamDefaultControllerCallPullIfNeeded(t)}function readableStreamDefaultControllerCanCloseOrEnqueue(t){let{stream:n}=t[Xr];return!t[Xr].closeRequested&&n[Xr].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(t){let{stream:n,highWaterMark:S,queueTotalSize:C}=t[Xr];switch(n[Xr].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[Xr];if(!readableStreamDefaultControllerCanCloseOrEnqueue(t)||!t[Xr].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[Xr].pulling){t[Xr].pullAgain=!0;return}t[Xr].pulling=!0,t[Xr].pullAlgorithm(t).then(()=>{t[Xr].pulling=!1,t[Xr].pullAgain&&(t[Xr].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(t))},n=>readableStreamDefaultControllerError(t,n))}}function readableStreamDefaultControllerClearAlgorithms(t){t[Xr].pullAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0,t[Xr].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(t,n){let{stream:S}=t[Xr];S[Xr].state===`readable`&&(resetQueue(t),readableStreamDefaultControllerClearAlgorithms(t),readableStreamError(S,n))}function readableStreamDefaultControllerCancelSteps(t,n){resetQueue(t);let S=t[Xr].cancelAlgorithm?.(n)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(t),S}function readableStreamDefaultControllerPullSteps(t,n){let{stream:S,queue:C}=t[Xr];if(C.length){let N=dequeueValue(t);t[Xr].closeRequested&&!C.length?(readableStreamDefaultControllerClearAlgorithms(t),readableStreamClose(S)):readableStreamDefaultControllerCallPullIfNeeded(t),n[li](N);return}readableStreamAddReadRequest(S,n),readableStreamDefaultControllerCallPullIfNeeded(t)}function setupReadableStreamDefaultController(t,n,S,C,N,F,I){n[Xr]={cancelAlgorithm:N,closeRequested:!1,highWaterMark:F,pullAgain:!1,pullAlgorithm:C,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:I,stream:t},t[Xr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Xr].started=!0,readableStreamDefaultControllerCallPullIfNeeded(n)},t=>readableStreamDefaultControllerError(n,t))}function setupReadableStreamDefaultControllerFromSource(t,n,S,C){let N=new ReadableStreamDefaultController(mi),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[Zr]=`ReadableStream`,F[Xr]=createReadableStreamState(),setupReadableStreamDefaultController(F,new ReadableStreamDefaultController(mi),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[Xr].controller):readableStreamDefaultControllerEnqueue(n[Xr].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[Xr].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[Xr].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[Xr].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[Xr].state===`writable`?writableStreamAbort(n,S):Promise.resolve()),N||I.push(()=>t[Xr].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[Xr].state===`errored`?S(t[Xr].storedError):n.then(void 0,S)}function watchClosed(t,n,S){t[Xr].state===`closed`?S():n.then(S,()=>{})}class PipeToReadRequest{[li](t){ve(()=>{Z.currentWrite=writableStreamDefaultWriterWrite(H,t),setPromiseHandled(Z.currentWrite),ne.resolve(!1)})}[ci](){ne.resolve(!0)}[di](t){ne.reject(t)}}let ne={resolve:null,reject:null};async function step(){if(W||n[Xr].backpressure&&(await H[Xr].ready.promise,W))return!0;let S=t[Xr].controller;if(t[Xr].state===`readable`&&yi(S)&&S[Xr].queue.length>0){for(;S[Xr].queue.length>0;){if(W)return!0;let C=dequeueValue(S);if(S[Xr].closeRequested&&!S[Xr].queue.length&&(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(t)),Z.currentWrite=writableStreamDefaultWriterWrite(H,C),setPromiseHandled(Z.currentWrite),n[Xr].backpressure||n[Xr].state!==`writable`||writableStreamCloseQueuedOrInFlight(n))break}return readableStreamDefaultControllerCallPullIfNeeded(S),t[Xr].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[Xr].close.promise,t=>{if(!C)return shutdownWithAnAction(()=>writableStreamAbort(n,t),!0,t);shutdown(!0,t)}),watchErrored(n,H[Xr].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>readableStreamCancel(t,n),!0,n);shutdown(!0,n)}),watchClosed(t,I[Xr].close.promise,()=>{if(!S)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(H));shutdown()}),writableStreamCloseQueuedOrInFlight(n)||n[Xr].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,{[li](t){ve(()=>{C=!1;let S=t,I=t;if(!F&&n)try{I=structuredClone(I)}catch{}N||readableStreamDefaultControllerEnqueue(W[Xr].controller,S),F||readableStreamDefaultControllerEnqueue(q[Xr].controller,I)})},[ci](){ve(()=>{C=!1,N||readableStreamDefaultControllerClose(W[Xr].controller),F||readableStreamDefaultControllerClose(q[Xr].controller),(!N||!F)&&Y.resolve(void 0)})},[di](){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[Xr].close.promise.then(void 0,t=>{readableStreamDefaultControllerError(W[Xr].controller,t),readableStreamDefaultControllerError(q[Xr].controller,t),(!N||!F)&&Y.resolve(void 0)}),[W,q]}var BYOBReadIntoRequest=class{[Xr];constructor(){this[Xr]=Promise.withResolvers()}[li](t){this[Xr].resolve?.({value:t,done:!1})}[ci](t){this[Xr].resolve?.({value:t,done:!0})}[di](t){this[Xr].reject?.(t)}get promise(){return this[Xr].promise}},ReadableStreamBYOBReader=class{[Zr]=`ReadableStreamBYOBReader`;[Xr];constructor(t){if(!vi(t))throw TypeError(`Expected a ReadableStream`);this[Xr]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,t)}read(t,n={}){if(!Si(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[Xr].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(!Si(this))throw TypeError(`Invalid this`);this[Xr].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return Si(this)?this[Xr].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(t=void 0){return Si(this)?this[Xr].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{[Zr]=`ReadableStreamBYOBRequest`;[Xr];constructor(t){if(t!==mi)throw TypeError(`Illegal constructor`)}get view(){if(!Ci(this))throw TypeError(`Invalid this`);return this[Xr].view}respond(t){if(!Ci(this))throw TypeError(`Invalid this`);if(this[Xr].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[Xr].view;if(isDetachedBuffer(n.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Xr].controller,t)}respondWithNewView(t){if(!Ci(this))throw TypeError(`Invalid this`);if(this[Xr].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[Xr].controller,t)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[Zr]=`ReadableByteStreamController`;[Xr];constructor(t){if(t!==mi)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!xi(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!xi(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!xi(this))throw TypeError(`Invalid this`);if(this[Xr].closeRequested)throw TypeError(`Close already requested`);if(this[Xr].stream[Xr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(t){if(!xi(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[Xr].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Xr].stream[Xr].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,t)}error(t=void 0){if(!xi(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,t)}[si](t){return readableByteStreamControllerCancelSteps(this,t)}[fi](t){readableByteStreamControllerPullSteps(this,t)}[pi](){if(this[Xr].pendingPullIntos.length>0){let t=this[Xr].pendingPullIntos[0];t.readerType=`none`,this[Xr].pendingPullIntos=[t]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const xi=isBrandCheck(`ReadableByteStreamController`),Si=isBrandCheck(`ReadableStreamBYOBReader`),Ci=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(t){let{reader:n}=t[Xr];return n===void 0?!1:n[Xr]!==void 0&&n[Zr]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(t){return t[Xr].reader[Xr].readIntoRequests.length}function readableStreamAddReadIntoRequest(t,n){t[Xr].reader[Xr].readIntoRequests.push(n)}function readableStreamFulfillReadIntoRequest(t,n,S){let{reader:C}=t[Xr],N=C[Xr].readIntoRequests.shift();S?N[ci](n):N[li](n)}function setupReadableStreamBYOBReader(t,n){if(isReadableStreamLocked(n))throw TypeError(`ReadableStream is locked`);if(!xi(n[Xr].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(t,n),t[Xr].readIntoRequests=[]}function readableStreamBYOBReaderRead(t,n,S,C){let{stream:N}=t[Xr];N[Xr].disturbed=!0,N[Xr].state===`errored`?C[di](N[Xr].storedError):readableByteStreamControllerPullInto(N[Xr].controller,n,S,C)}function readableStreamBYOBReaderRelease(t){readableStreamReaderGenericRelease(t);let n=TypeError(`Reader was released`);for(let S=0;S<t[Xr].readIntoRequests.length;S++)t[Xr].readIntoRequests[S][di](n);t[Xr].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(t){t[Xr].pullAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(t){readableByteStreamControllerInvalidateBYOBRequest(t),t[Xr].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(t){let n=t[Xr].byobRequest;n!=null&&(n[Xr].controller=void 0,n[Xr].view=null,t[Xr].byobRequest=null)}function readableByteStreamControllerError(t,n){let{stream:S}=t[Xr];S[Xr].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t),readableByteStreamControllerClearAlgorithms(t),readableStreamError(S,n))}function readableByteStreamControllerGetDesiredSize(t){let n=t[Xr].stream[Xr].state;return n===`errored`?null:n===`closed`?0:t[Xr].highWaterMark-t[Xr].queueTotalSize}function readableByteStreamControllerShouldCallPull(t){let{stream:n}=t[Xr];if(n[Xr].state!==`readable`||t[Xr].closeRequested||!t[Xr].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[Xr].pulling){t[Xr].pullAgain=!0;return}t[Xr].pulling=!0,t[Xr].pullAlgorithm(t).then(()=>{t[Xr].pulling=!1,t[Xr].pullAgain&&(t[Xr].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(t))},n=>readableByteStreamControllerError(t,n))}}function readableByteStreamControllerHandleQueueDrain(t){t[Xr].queueTotalSize===0&&t[Xr].closeRequested?(readableByteStreamControllerClearAlgorithms(t),readableStreamClose(t[Xr].stream)):readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerEnqueueChunkToQueue(t,n,S,C){t[Xr].queue.push({buffer:n,byteOffset:S,byteLength:C}),t[Xr].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[Xr].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[Xr].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[Xr].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[Xr].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[Xr].queueTotalSize-=C,readableByteStreamControllerFillHeadPullIntoDescriptor(t,C,n),N-=C}return F}function readableByteStreamControllerFillReadRequestFromQueue(t,n){let S=t[Xr].queue.shift();t[Xr].queueTotalSize-=S.byteLength,readableByteStreamControllerHandleQueueDrain(t);let C=new Uint8Array(S.buffer,S.byteOffset,S.byteLength);n[li](C)}function readableByteStreamControllerProcessReadRequestsUsingQueue(t){let n=t[Xr].stream[Xr].reader;for(;n[Xr].readRequests.length!==0;){if(t[Xr].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(t,n[Xr].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t){for(;t[Xr].pendingPullIntos.length!==0;){if(t[Xr].queueTotalSize===0)return;let n=t[Xr].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,n)&&(readableByteStreamControllerShiftPendingPullInto(t),readableByteStreamControllerCommitPullIntoDescriptor(t[Xr].stream,n))}}function readableByteStreamControllerGetBYOBRequest(t){if(t[Xr].byobRequest===null&&t[Xr].pendingPullIntos.length!==0){let n=t[Xr].pendingPullIntos[0],S=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),C=new ReadableStreamBYOBRequest(mi);C[Xr]={controller:t,view:S},t[Xr].byobRequest=C}return t[Xr].byobRequest}function readableByteStreamControllerEnqueue(t,n){let{stream:S}=t[Xr];if(t[Xr].closeRequested||S[Xr].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[Xr].pendingPullIntos.length!==0){let n=t[Xr].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[Xr].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[Xr];if(!(t[Xr].closeRequested||n[Xr].state!==`readable`)){if(t[Xr].queueTotalSize>0){t[Xr].closeRequested=!0;return}if(t[Xr].pendingPullIntos.length!==0){let n=t[Xr].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[Xr].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[di](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[di](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[Xr].pendingPullIntos.length!==0){t[Xr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C);return}if(N[Xr].state===`closed`){let t=new I(te.buffer,te.byteOffset,0);C[ci](t);return}if(t[Xr].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(t,te)){let n=readableByteStreamControllerConvertPullIntoDescriptor(te);readableByteStreamControllerHandleQueueDrain(t),C[li](n);return}if(t[Xr].closeRequested){let n=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(t,n),C[di](n);return}}t[Xr].pendingPullIntos.push(te),readableStreamAddReadIntoRequest(N,C),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespond(t,n){let S=t[Xr].pendingPullIntos[0];if(t[Xr].stream[Xr].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[Xr].pendingPullIntos[0],C=t[Xr].stream[Xr].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[Xr].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(t),t[Xr].stream[Xr].state===`closed`?readableByteStreamControllerRespondInClosedState(t,S):readableByteStreamControllerRespondInReadableState(t,n,S),readableByteStreamControllerCallPullIfNeeded(t)}function readableByteStreamControllerRespondInClosedState(t,n){n.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(t);let S=t[Xr].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[Xr].stream,S),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(t)}function readableByteStreamControllerCancelSteps(t,n){readableByteStreamControllerClearPendingPullIntos(t),resetQueue(t);let S=t[Xr].cancelAlgorithm?.(n)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(t),S}function readableByteStreamControllerPullSteps(t,n){let S=t[Xr].stream;if(t[Xr].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(t,n);return}let C=t[Xr].autoAllocateChunkSize;if(C!==void 0){let S;try{S=new ArrayBuffer(C)}catch(t){n[di](t);return}let N={buffer:S,bufferByteLength:C,byteOffset:0,byteLength:C,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};t[Xr].pendingPullIntos.push(N)}readableStreamAddReadRequest(S,n),readableByteStreamControllerCallPullIfNeeded(t)}function setupReadableByteStreamController(t,n,S,C,N,F,I){n[Xr]={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[Xr].controller=n;let H=S();new Promise(t=>t(H)).then(()=>{n[Xr].started=!0,readableByteStreamControllerCallPullIfNeeded(n)},t=>readableByteStreamControllerError(n,t))}function setupReadableByteStreamControllerFromSource(t,n,S){let C=new ReadableByteStreamController(mi),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[Xr].controller,X=q[Xr].controller,n.closed.catch(t=>{Y.error(t),X.error(t),(!C||!N)&&H.resolve()}),[W,q]}const wi=Symbol(`kSkipThrow`);var TransformStream=class{[Zr]=`TransformStream`;[Xr];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[Xr].controller))}get readable(){if(!Ti(this))throw TypeError(`Invalid this`);return this[Xr].readable}get writable(){if(!Ti(this))throw TypeError(`Invalid this`);return this[Xr].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[Zr]=`TransformStreamDefaultController`;[Xr];constructor(t){if(t!==wi)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!Ei(this))throw TypeError(`Invalid this`);let{stream:t}=this[Xr],{readable:n}=t[Xr],S=n[Xr].controller;return readableStreamDefaultControllerGetDesiredSize(S)}enqueue(t){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,t)}error(t){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,t)}terminate(){if(!Ei(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Ti=isBrandCheck(`TransformStream`),Ei=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[Xr]={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[Xr];readableStreamDefaultControllerError(S[Xr].controller,n),transformStreamErrorWritableAndUnblockWrite(t,n)}function transformStreamErrorWritableAndUnblockWrite(t,n){let{controller:S,writable:C}=t[Xr];transformStreamDefaultControllerClearAlgorithms(S),writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t)}function transformStreamUnblockWrite(t){t[Xr].backpressure&&transformStreamSetBackpressure(t,!1)}function transformStreamSetBackpressure(t,n){t[Xr].backpressureChange.promise!==void 0&&t[Xr].backpressureChange.resolve?.(),t[Xr].backpressureChange=Promise.withResolvers(),t[Xr].backpressure=n}function setupTransformStreamDefaultController(t,n,S,C,N){n[Xr]={stream:t,transformAlgorithm:S,flushAlgorithm:C,cancelAlgorithm:N,finishPromise:void 0},t[Xr].controller=n}function setupTransformStreamDefaultControllerFromTransformer(t,n){let S=new TransformStreamDefaultController(wi),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[Xr].transformAlgorithm=void 0,t[Xr].flushAlgorithm=void 0,t[Xr].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(t,n){let{stream:S}=t[Xr],{readable:C}=S[Xr],N=C[Xr].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(N))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(N,n)}catch(t){throw transformStreamErrorWritableAndUnblockWrite(S,t),C[Xr].storedError}readableStreamDefaultControllerHasBackpressure(N)!==S[Xr].backpressure&&transformStreamSetBackpressure(S,!0)}function transformStreamDefaultControllerError(t,n){transformStreamError(t[Xr].stream,n)}async function transformStreamDefaultControllerPerformTransform(t,n){try{let S=t[Xr].transformAlgorithm;if(S===void 0)return;await S(n,t)}catch(n){throw transformStreamError(t[Xr].stream,n),n}}function transformStreamDefaultControllerTerminate(t){let{stream:n}=t[Xr],{readable:S}=n[Xr];readableStreamDefaultControllerClose(S[Xr].controller),transformStreamErrorWritableAndUnblockWrite(n,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(t,n){let{controller:S}=t[Xr];return t[Xr].backpressure?t[Xr].backpressureChange.promise.then(()=>{let{writable:C}=t[Xr];if(C[Xr].state===`erroring`)throw C[Xr].storedError;return transformStreamDefaultControllerPerformTransform(S,n)}):transformStreamDefaultControllerPerformTransform(S,n)}async function transformStreamDefaultSinkAbortAlgorithm(t,n){let{controller:S,readable:C}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Xr].finishPromise=N;let H=S[Xr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Xr].state===`errored`?I(C[Xr].storedError):(readableStreamDefaultControllerError(C[Xr].controller,n),F())},t=>{readableStreamDefaultControllerError(C[Xr].controller,t),I(t)}),S[Xr].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(t){let{readable:n,controller:S}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:C,resolve:N,reject:F}=Promise.withResolvers();S[Xr].finishPromise=C;let I=S[Xr].flushAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(S),I.then(()=>{n[Xr].state===`errored`?F(n[Xr].storedError):(readableStreamDefaultControllerClose(n[Xr].controller),N())},t=>{readableStreamDefaultControllerError(n[Xr].controller,t),F(t)}),S[Xr].finishPromise}function transformStreamDefaultSourcePullAlgorithm(t){return transformStreamSetBackpressure(t,!1),t[Xr].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(t,n){let{controller:S,writable:C}=t[Xr];if(S[Xr].finishPromise!==void 0)return S[Xr].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();S[Xr].finishPromise=N;let H=S[Xr].cancelAlgorithm(n);return transformStreamDefaultControllerClearAlgorithms(S),H.then(()=>{C[Xr].state===`errored`?I(C[Xr].storedError):(writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t),F())},n=>{writableStreamDefaultControllerErrorIfNeeded(C[Xr].controller,n),transformStreamUnblockWrite(t),I(n)}),S[Xr].finishPromise}const Di=Object.defineProperty(t=>t.byteLength,"name",{value:`size`}),Oi=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 Di}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 Oi}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 ki=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),ki)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 Ai=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,ji=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,Mi=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,Ni=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,Pi=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,Fi=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,Ii=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 "${Ri}" 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 Li;if(typeof n!=`number`)throw withCode(TypeError(`The "${Ri}" property must be of type number. Received ${describeType(n)}`),`ERR_INVALID_ARG_TYPE`);if(Number.isNaN(n))return Li;if(!Number.isFinite(n))throw outOfRange(`a finite number`,n);if(n<1||n>Li)throw outOfRange(`>= 1 and <= ${Li}`,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 Li,Ri,zi=__esmMin(()=>{Li=2**53-1,Ri=`options.maxOutputLength`}),Bi,Vi=__esmMin(()=>{Bi=n}),Hi,Ui=__esmMin(()=>{Vi(),Hi=Bi});function getGioFormat(t){switch(t){case`gzip`:return Hi.ZlibCompressorFormat.GZIP;case`deflate`:return Hi.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return Hi.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 Hi.ZlibCompressor({format:getGioFormat(n),level:Math.trunc(S)}),N=new Hi.ConverterOutputStream({base_stream:Hi.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new vt.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=Li,C=0){let N=new Hi.ZlibDecompressor({format:getGioFormat(n)}),F=Hi.MemoryInputStream.new_from_bytes(new vt.Bytes(t)),I=new Hi.ConverterInputStream({base_stream:F,converter:N}),H=[],W=C;try{for(;;){let t=Math.min(Gi,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 Hi.ZlibDecompressor({format:Hi.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0,F=0;for(;;){let I=t.subarray(N,N+Wi);try{let[t,H,W]=S.convert(I,C,Hi.ConverterFlags.NONE);if(N+=H,F+=W,t===Hi.ConverterResult.FINISHED||F>n||H===0&&W===0)return N}catch{return N}}}function gunzipWithGio(t,n=Li){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 Wi,Gi,Ki=__esmMin(()=>{zi(),Ui(),yt(),Wi=256*1024,Gi=1024*1024,__name$1(concat$2,`concat`)}),qi=__esmMin(()=>{Ye()}),Ji,Yi,Xi=__esmMin(()=>{Ji=Object.defineProperty,Yi=__name$1((t,n)=>{let S={};for(var C in t)Ji(S,C,{get:t[C],enumerable:!0});return n||Ji(S,Symbol.toStringTag,{value:`Module`}),S},`__exportAll`)});function _setPipeImpl(t){Zi=t}var Zi,Stream_,Qi=__esmMin(()=>{on(),Stream_=class extends Jt{constructor(t){super(t)}pipe(t,n){return Zi(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 $i=__esmMin(()=>{Qi(),Ye(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(t){return t?ta:ea}function setDefaultHighWaterMark(t,n){if(typeof n!=`number`||n<0||Number.isNaN(n))throw TypeError(`Invalid highWaterMark: ${n}`);t?ta=n:ea=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 ea,ta,na=__esmMin(()=>{ea=16384,ta=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 ra,ia=__esmMin(()=>{$i(),ra=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 aa,oa,sa,ca=__esmMin(()=>{Qi(),ia(),na(),Ye(),aa=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)}},aa.prototype[ra]=function(){return streamAsyncDispose(this,this.readableEnded)},oa=Object.getOwnPropertyDescriptor(aa.prototype,`on`),sa=Object.getOwnPropertyDescriptor(aa.prototype,`removeListener`),Object.defineProperty(aa.prototype,"addListener",{...oa}),Object.defineProperty(aa.prototype,"off",{...sa})});function writeAfterEndError(){let t=Error(`write after end`);return t.code=`ERR_STREAM_WRITE_AFTER_END`,t}var la=__esmMin(()=>{});function chunkLen$1(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var Duplex_,ua=__esmMin(()=>{la(),na(),ca(),Ye(),Duplex_=class extends aa{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;_autoClosed=!1;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),this.destroy()}),!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._closeAfterFinish()),S&&S()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_closeAfterFinish(){this._autoClosed||!this.destroyed&&!this._readableState.endEmitted&&this.readable||(this._autoClosed=!0,this.emit(`close`))}_autoClose(){this._autoClosed||(this._autoClosed=!0,this.emit(`close`))}_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 aa))){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 aa&&(C._pipeDests.push({dest:n,cleanup}),C._readableState.pipes.push(n)),n.emit(`pipe`,C),n}var da=__esmMin(()=>{Qi(),ca(),_setPipeImpl(pipe)});function chunkLen(t){if(t==null)return 1;let n=t.length;return typeof n==`number`?n:1}var fa,pa=__esmMin(()=>{la(),Qi(),ia(),na(),Ye(),fa=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}},fa.prototype[ra]=function(){return streamAsyncDispose(this,this.writableFinished)}}),ma,ha=__esmMin(()=>{ua(),Ye(),ma=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_,ga=__esmMin(()=>{ha(),PassThrough_=class extends ma{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 _a=__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 va,ya,ba=__esmMin(()=>{Xi(),$i(),_a(),va=Yi({default:()=>ya,finished:()=>finished,pipeline:()=>pipeline}),ya={pipeline,finished}}),xa=__exportAll$5({Duplex:()=>Ta,PassThrough:()=>Da,Readable:()=>Ca,Stream:()=>Sa,Transform:()=>Ea,Writable:()=>wa,addAbortSignal:()=>addAbortSignal,default:()=>Oa,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>Oa,pipeline:()=>pipeline$1,promises:()=>va,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),Sa,Ca,wa,Ta,Ea,Da,Oa,ka=__esmMin(()=>{qi(),Qi(),$i(),na(),ca(),ua(),da(),pa(),ha(),ga(),_a(),ba(),Sa=makeCallable(Stream_),Ca=makeCallable(aa),wa=makeCallable(fa),Ta=makeCallable(Duplex_),Ea=makeCallable(ma),Da=makeCallable(PassThrough_),Oa=Object.assign(Sa,{Stream:Sa,Readable:Ca,Writable:wa,Duplex:Ta,Transform:Ea,PassThrough:Da,pipeline:pipeline$1,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark,promises:va})});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,Aa=__esmMin(()=>{zi(),Ki(),ka(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends Ea{_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 Ea{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends Ea{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends Ea{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 Ea{constructor(){super();let t=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw t.code=`ERR_UNSUPPORTED_OPERATION`,t}}}),ja=__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:()=>Na,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>Pa,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>=Li)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`),Ma)}function brotliDecompress(t,n,S){(typeof n==`function`?n:S)(Error(`brotliDecompress: Brotli is not supported in this environment`),Ma)}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,Ma)}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,Ma)}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,Ma,Na,Pa,Fa=__esmMin(()=>{zi(),Ki(),Aa(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),Ma=new Uint8Array,Na={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},Pa={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:Na}});const Ia=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(t){if(!Ia.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 Ra=!1,za,Ba,Va,Ha,Ua,Wa;async function loadZlib(){if(Ra)return;let t=await Promise.resolve().then(()=>(Fa(),ja));za=t.gzipSync,Ba=t.gunzipSync,Va=t.deflateSync,Ha=t.inflateSync,Ua=t.deflateRawSync,Wa=t.inflateRawSync,Ra=!0}function getCompressFn(t){switch(t){case`gzip`:return t=>za(t);case`deflate`:return t=>Va(t);case`deflate-raw`:return t=>Ua(t)}}function getDecompressFn(t){switch(t){case`gzip`:return t=>Ba(t);case`deflate`:return t=>Ha(t);case`deflate-raw`:return t=>Wa(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 Ga,Ka;if(La)Ga=globalThis.CompressionStream,Ka=globalThis.DecompressionStream;else{let t=loadZlib();Ga=class CompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new Mi({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}},Ka=class DecompressionStream{readable;writable;constructor(n){let S=validateFormat(n),C=[],N=new Mi({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 qa=globalThis;globalThis.CompressionStream===void 0&&(qa.CompressionStream=Ga),globalThis.DecompressionStream===void 0&&(qa.DecompressionStream=Ka);const Ja=globalThis;globalThis.DOMException===void 0&&(Ja.DOMException=Ar);var Ya,__name,Xa=__esmMin(()=>{Ya=Object.defineProperty,__name=(t,n)=>Ya(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 Za=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 Qa=class Headers{[Za];constructor(t){if(this[Za]=new Map,t!=null){if(t instanceof Headers){for(let[n,S]of t[Za])this[Za].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[Za].get(S);N?N.push(C):this[Za].set(S,[C])}set(t,n){validateHeaderName(t),validateHeaderValue(t,n);let S=String(t).toLowerCase();this[Za].set(S,[String(n)])}delete(t){this[Za].delete(String(t).toLowerCase())}has(t){return this[Za].has(String(t).toLowerCase())}get(t){let n=this[Za].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[Za].get(String(t).toLowerCase())??[]}getSetCookie(){return this[Za].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[Za].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(Qa.prototype,[`get`,`entries`,`forEach`,`values`].reduce((t,n)=>(t[n]={enumerable:!0},t),{}));var $a=__esmMin(()=>{ht()});$a();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)}};cr();const eo=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[eo]===`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[eo])},isAbortSignal=t=>{if(typeof t!=`object`||!t)return!1;let n=t;return n[eo]===`AbortSignal`||n[eo]===`EventTarget`},isDomainOrSubdomain=(t,n)=>{let S=new ar(n).hostname,C=new ar(t).hostname;return S===C||S.endsWith(`.${C}`)},isSameProtocol=(t,n)=>new ar(n).protocol===new ar(t).protocol;var to=__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$1,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 no,ro,lower,noop,MultipartParser,io=__esmMin(()=>{hr(),no=1,ro={PART_BOUNDARY:no,LAST_BOUNDARY:no*=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
15
15
  --`+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|=ro.LAST_BOUNDARY;else if(te!==13)return;H++;break}else if(H-1==F.length-2){if(q&ro.LAST_BOUNDARY&&te===45)W=9,q=0;else if(!(q&ro.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|=ro.PART_BOUNDARY:te===45?q|=ro.LAST_BOUNDARY:H=0;else if(H-1===F.length)if(q&ro.PART_BOUNDARY){if(H=0,te===10){q&=~ro.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),W=1;break}}else q&ro.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(),Xa(),$a(),cr(),ht(),ka(),hr(),__name((t,n)=>new Promise((S,C)=>{pipeline$1(t,n,t=>{t?C(t):S()})}),`pipeline`);const ao=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{[ao]={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[ao].body=null;else if(isURLSearchParameters(t))this[ao].body=ot.from(t.toString());else if(isBlob(t))this[ao].body=t;else if(ot.isBuffer(t))this[ao].body=t;else if(isAnyArrayBuffer$2(t))this[ao].body=ot.from(t);else if(ArrayBuffer.isView(t))this[ao].body=ot.from(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof Ca)this[ao].body=t;else if(typeof ReadableStream<`u`&&t instanceof ReadableStream)this[ao].body=readableStreamToReadable(t);else if(t instanceof FormData$1){let n=formDataToBlob(t);this[ao].body=n,this[ao].boundary=n.type?.split(`boundary=`)?.[1]??``}else typeof t==`string`?this[ao].body=ot.from(t):t instanceof er?this[ao].body=ot.from(t.toString()):(ge.warn(`Unknown body type "${typeof t}", try to parse the body to string!`),this[ao].body=ot.from(String(t)));let S=this[ao].body;ot.isBuffer(S)?this[ao].stream=Ca.from(S):isBlob(S)?this[ao].stream=Ca.from(blobToAsyncIterable(S)):S instanceof Ca&&(this[ao].stream=S),S instanceof Sa&&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[ao].error=n})}get body(){let t=this[ao].stream;if(!t)return null;let n=this[ao].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[ao].webStream=S,S}return null}get _stream(){return this[ao].stream}get _rawBodyBuffer(){let t=this[ao].body;return t===null?null:ot.isBuffer(t)?t:t instanceof Uint8Array?ot.from(t.buffer,t.byteOffset,t.byteLength):null}get bodyUsed(){return this[ao].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$1,n=new er(await this.text());for(let[S,C]of n)t.append(S,C);return t}let{toFormData:n}=await Promise.resolve().then(()=>(io(),to));return n(this.body,t)}async blob(){let t=this.headers?.get(`content-type`)||this[ao].body&&this[ao].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[ao].disturbed)throw TypeError(`body used already for: ${t.url}`);if(t[ao].disturbed=!0,t[ao].error)throw t[ao].error;let{_stream:n}=t;if(n===null||!(n instanceof Sa))return ot.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`)?ot.from(S.join(``)):ot.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[ao];if(t.bodyUsed)throw Error(`cannot clone body after it is used`);return N instanceof Sa&&typeof N.getBoundary!=`function`&&(S=new Da({highWaterMark:n}),C=new Da({highWaterMark:n}),N.pipe(S),N.pipe(C),t[ao].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:ot.isBuffer(t)||isAnyArrayBuffer$2(t)||ArrayBuffer.isView(t)?null:t instanceof FormData$1?`multipart/form-data; boundary=${n[ao].boundary}`:t instanceof Sa?null:`text/plain;charset=UTF-8`,getTotalBytes=t=>{let{body:n}=t[ao];if(n===null)return 0;if(isBlob(n))return n.size;if(ot.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 Ca({async read(){try{let{done:t,value:S}=await n.read();t?this.push(null):this.push(ot.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 oo=new Set([301,302,303,307,308]),isRedirect=t=>oo.has(t);cr(),yt(),Ui();const so=Symbol(`Response internals`);var co=class Response extends Body{[so];_inputStream=null;constructor(t=null,n={}){super(t,n);let S=n.status==null?200:n.status,C=new Qa(n.headers);if(t!==null&&!C.has(`Content-Type`)){let n=extractContentType(t,this);n&&C.append(`Content-Type`,n)}this[so]={type:`default`,url:n.url,status:S,statusText:n.statusText||``,headers:C,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[so].type}get url(){return this[so].url||``}get status(){return this[so].status}get ok(){return this[so].status>=200&&this[so].status<300}get redirected(){return this[so].counter>0}get statusText(){return this[so].statusText}get headers(){return this[so].headers}get highWaterMark(){return this[so].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 ar(t).toString()},status:n})}static error(){let t=new Response(null,{status:0,statusText:``});return t[so].type=`error`,t}static json(t,n){let S=JSON.stringify(t),C={...n},N=new Qa(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=Hi.MemoryOutputStream.new_resizable();await new Promise((n,S)=>{t.splice_async(this._inputStream,Hi.OutputStreamSpliceFlags.CLOSE_TARGET|Hi.OutputStreamSpliceFlags.CLOSE_SOURCE,vt.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(co.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 lo=__esmMin(()=>{}),uo,cli,fo=__esmMin(()=>{yt(),uo=new TextDecoder,cli=t=>{let[n,S,C,N]=vt.spawn_command_line_sync(t);if(C.byteLength)throw Error(uo.decode(C));return uo.decode(S)}}),po,readJSON,mo=__esmMin(()=>{yt(),po=new TextDecoder,readJSON=t=>{let[n,S]=vt.file_get_contents(t);if(n)return JSON.parse(po.decode(S));throw Error(`Error on require "${t}"`)}}),ho,go=__esmMin(()=>{ho=S}),_o,vo=__esmMin(()=>{go(),_o=ho});function existsSync(t){return typeof t!=`string`||t===``?!1:Hi.File.new_for_path(t).query_exists(null)}var yo=__esmMin(()=>{Ui(),vo()});async function readBytesAsync(t,n=4096,S=vt.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(Hi.IOErrorEnum,Hi.IOErrorEnum.PARTIAL_INPUT)||n.matches(Hi.IOErrorEnum,Hi.IOErrorEnum.CONNECTION_CLOSED)||n.matches(Hi.IOErrorEnum,Hi.IOErrorEnum.BROKEN_PIPE)||n.matches(Hi.IOErrorEnum,Hi.IOErrorEnum.CLOSED)))return N(null);F(t)}})})}async function*inputStreamAsyncIterator(t,n=4096,S=vt.PRIORITY_DEFAULT,C=null){let N;for(;(N=await readBytesAsync(t,n,S,C))!==null;)yield N}var bo=__esmMin(()=>{lo(),yt(),Ui()}),xo,So,getPathSeparator,Co=__esmMin(()=>{yt(),Ui(),{File:xo}=Hi,So=__name$1((t,...n)=>{let S=xo.new_for_path(t);for(let t of n)S=S.resolve_relative_path(t);return S},`resolve`),getPathSeparator=()=>vt.get_current_dir().startsWith(`/`)?`/`:`\\`}),wo=__esmMin(()=>{lo(),fo(),ae(),mo(),yo(),bo(),Co()});ka(),yt(),Ui(),wo();async function soupSendAsync(t,n,S=vt.PRIORITY_DEFAULT,C=null){return new Promise((N,F)=>{let I=!1,onCancel=()=>{I||(I=!0,F(new Hi.IOErrorEnum({code:Hi.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(vt.PRIORITY_DEFAULT,null,(S,C)=>{try{t.close_finish(C)}catch{}n()})})}function inputStreamToReadable(t,n={}){let S=new Hi.Cancellable,C=null,close=()=>C||(t.has_pending()?Promise.resolve():(C=closeInputStream(t),C));async function*chunks(){try{yield*inputStreamAsyncIterator(t,4096,vt.PRIORITY_DEFAULT,S)}finally{await close()}}let N=Ca.from(chunks(),n);return N.once(`close`,()=>{t.has_pending()?S.cancel():close()}),N}let To=null;async function loadSoup(){return To??=(await import(`gi://Soup?version=3.0`)).default}function acceptsForServername(t,n,S){return t===S&&(n&S)===0}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}Ui(),yt(),ka(),Ui(),on(),cr();function stripURLForUseAsAReferrer(t,n=!1){if(t==null||t===`no-referrer`)return`no-referrer`;let S=new ar(t);return/^(about|blob|data):$/.test(S.protocol)?`no-referrer`:(S.username=``,S.password=``,S.hash=``,n&&(S.pathname=``,S.search=``),S)}const Eo=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(!Eo.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 ar(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 ar(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 ar(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&&Eo.has(t)&&(S=t);return S}cr(),yt(),Ui();const Do=Symbol(`Request internals`);let Oo=null;function envPositiveInt(t,n){let S=vt.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:vt.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 ko=class Request extends Body{cache;credentials;destination;get headers(){return this[Do].headers}integrity;keepalive;get method(){return this[Do].method}mode;get redirect(){return this[Do].redirect}get referrer(){if(this[Do].referrer===`no-referrer`)return``;if(this[Do].referrer===`client`)return`about:client`;if(this[Do].referrer)return this[Do].referrer.toString()}get referrerPolicy(){return this[Do].referrerPolicy}set referrerPolicy(t){this[Do].referrerPolicy=validateReferrerPolicy(t)}get signal(){return this[Do].signal}get url(){return this[Do].parsedURL.toString()}get _uri(){return vt.Uri.parse(this.url,vt.UriFlags.ENCODED)}get _session(){return this[Do].session}get _message(){return this[Do].message}get _inputStream(){return this[Do].inputStream}get[Symbol.toStringTag](){return`Request`}[Do];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;servername;constructor(t,n){let S=t,C=n||{},N,F={};if(isRequest(t)?(N=new ar(S.url),F=S):N=new ar(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 Qa(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 ar(Y);Y=/^about:(\/\/)?client$/.test(t.toString())?`client`:t}else Y=void 0;this[Do]={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.servername=C.servername??S.servername,this.referrerPolicy=n?.referrerPolicy||S.referrerPolicy||``}async _send(t){let{signal:n,parsedURL:S}=this[Do],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[Do].method,uri:vt.Uri.parse(S.toString(),vt.UriFlags.ENCODED)});this[Do].session=F,this[Do].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 vt.Bytes(H))}if(S.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&I.connect(`accept-certificate`,(t,n,S)=>!0),S.protocol===`https:`&&this.servername&&!shouldAcceptAnyCert(this.rejectUnauthorized)){let t=this.servername,n=Number(S.port)||443;I.connect(`accept-certificate`,(S,C,N)=>acceptsForServername(N,C.verify(Hi.NetworkAddress.new(t,n),null),Hi.TlsCertificateFlags.BAD_IDENTITY))}let W=new Hi.Cancellable;return n&&(n.aborted?W.cancel():n.addEventListener(`abort`,()=>W.cancel(),{once:!0})),this[Do].inputStream=await soupSendAsync(F,I,vt.PRIORITY_DEFAULT,W),this[Do].readable=inputStreamToReadable(this[Do].inputStream),{inputStream:this[Do].inputStream,readable:this[Do].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(ko.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[Do],S=new Qa(t[Do].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[Do].referrer=determineRequestsReferrer(t):t[Do].referrer=`no-referrer`,t[Do].referrer instanceof ar&&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}}Ye();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(),$a(),cr(),ka(),yt();const Ao=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 ko(t,n),{parsedURL:C,options:N}=getSoupRequestOptions(S);if(!Ao.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 co(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=vt.filename_from_uri(S.url)[0];t&&ge.log(`[fetch] file:// path=${n}`);let[C,N]=vt.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 co(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=Qa._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 ar(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 Qa(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 Oa.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 ko(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 co(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 co(I,ne).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(t));return finalize(),new co(n,ne)}}return finalize(),new co(I,ne)}__name$1(fetch$1,`fetch`);const jo=globalThis;globalThis.fetch===void 0&&(jo.fetch=fetch$1),globalThis.Headers===void 0&&(jo.Headers=Qa),globalThis.Request===void 0&&(jo.Request=ko),globalThis.Response===void 0&&(jo.Response=co);const Mo=globalThis;globalThis.ByteLengthQueuingStrategy===void 0&&(Mo.ByteLengthQueuingStrategy=Ni),globalThis.CountQueuingStrategy===void 0&&(Mo.CountQueuingStrategy=Pi);const No=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`)||(No.ReadableStream=Ai),No.ReadableStreamBYOBReader===void 0&&(No.ReadableStreamBYOBReader=ReadableStreamBYOBReader),No.ReadableStreamBYOBRequest===void 0&&(No.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest),No.ReadableByteStreamController===void 0&&(No.ReadableByteStreamController=ReadableByteStreamController),No.ReadableStreamDefaultController===void 0&&(No.ReadableStreamDefaultController=ReadableStreamDefaultController),No.ReadableStreamDefaultReader===void 0&&(No.ReadableStreamDefaultReader=ReadableStreamDefaultReader);const Po=globalThis;globalThis.TextEncoderStream===void 0&&(Po.TextEncoderStream=Fi),globalThis.TextDecoderStream===void 0&&(Po.TextDecoderStream=Ii);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=Mi}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=ji}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 Fo=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=Fo.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]!==Fo[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 Io={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function toNodeHashName(t){let n=Io[t.toUpperCase()]||Io[t];if(!n)throw new Ar(`Unrecognized hash name: ${t}`,`NotSupportedError`);return n}const Lo={"P-256":`prime256v1`,"P-384":`secp384r1`,"P-521":`secp521r1`};function toNodeCurveName(t){let n=Lo[t];if(!n)throw new Ar(`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 Ar(`Unsupported hash: ${t}`,`NotSupportedError`)}}__name$1(hashSize$1,`hashSize`);function validateUsages(t,n){for(let S of t)if(!n.includes(S))throw new Ar(`Invalid key usage: ${S}`,`SyntaxError`);if(t.length===0)throw new Ar(`Key usages must not be empty`,`SyntaxError`)}function checkUsage(t,n){if(!t.usages.includes(n))throw new Ar(`Key does not support the '${n}' usage`,`InvalidAccessError`)}const Ro=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,zo=new Uint8Array(128);for(let t=0;t<64;t++)zo[Ro.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+=Ro[N>>2&63],n+=Ro[(N<<4|F>>4)&63],n+=C+1<S?Ro[(F<<2|I>>6)&63]:`=`,n+=C+2<S?Ro[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|zo[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 Ar(`Key algorithm mismatch`,`InvalidAccessError`)}const Bo={Ed25519:{public:[`verify`],private:[`sign`]},X25519:{public:[],private:[`deriveKey`,`deriveBits`]}},Vo={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 Ar(`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,[...Bo[n].public,...Bo[n].private]);let N=C.filter(t=>Bo[n].private.includes(t));if(N.length===0)throw new Ar(`Usages cannot be empty when creating a key.`,`SyntaxError`);let F=C.filter(t=>Bo[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 Ar(`Invalid keyData`,`DataError`);if(t.kty!==`OKP`)throw new Ar(`Invalid JWK "kty" Parameter`,`DataError`);if(t.crv!==n)throw new Ar(`JWK "crv" Parameter and algorithm name mismatch`,`DataError`);if(n===`Ed25519`&&t.alg!==void 0&&t.alg!==`Ed25519`&&t.alg!==`EdDSA`)throw new Ar(`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 Ar(`Invalid JWK "use" Parameter`,`DataError`);if(t.key_ops!==void 0){if(!Array.isArray(t.key_ops))throw new Ar(`Invalid JWK "key_ops" Parameter`,`DataError`);for(let n of C)if(!t.key_ops.includes(n))throw new Ar(`Key operations and usage mismatch`,`DataError`)}if(t.ext===!1&&S)throw new Ar(`JWK "ext" Parameter and extractable mismatch`,`DataError`);if(typeof t.x!=`string`||t.d!==void 0&&typeof t.d!=`string`)throw new Ar(`Invalid keyData`,`DataError`)}function cfrgImportKey(t,n,S,C,N,F){let I,H,importOrDataError=t=>{try{return t()}catch(t){throw new Ar(`Invalid keyData: ${t.message}`,`DataError`)}};switch(n){case`raw`:{assertUsages(F,Bo[C].public);let n=toUint8Array(S);if(n.length!==32)throw new Ar(`Invalid keyData`,`DataError`);let N=new Uint8Array(44);N.set(Vo[C],0),N.set(n,12),I=importOrDataError(()=>t.createPublicKey({key:N,format:`der`,type:`spki`})),H=`public`;break}case`spki`:{assertUsages(F,Bo[C].public);let n=toUint8Array(S);I=importOrDataError(()=>t.createPublicKey({key:n,format:`der`,type:`spki`})),H=`public`;break}case`pkcs8`:{assertUsages(F,Bo[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,Bo[C][H]),H===`private`){if(I=importOrDataError(()=>t.createPrivateKey({key:n,format:`jwk`})),t.createPublicKey(I).export({format:`jwk`}).x!==n.x)throw new Ar(`Invalid JWK: "x" does not match "d"`,`DataError`)}else{if(base64urlDecode(n.x).length!==32)throw new Ar(`Invalid keyData`,`DataError`);I=importOrDataError(()=>t.createPublicKey({key:n,format:`jwk`}))}break}default:throw new Ar(`Unsupported format: ${n}`,`NotSupportedError`)}if(I.asymmetricKeyType!==C.toLowerCase())throw new Ar(`Invalid key type`,`DataError`);if(H===`private`&&F.length===0)throw new Ar(`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 Ar(`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 Ar(`Unsupported export format: ${t}`,`NotSupportedError`)}}function ed25519Sign$1(t,n,S){if(n.type!==`private`)throw new Ar(`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 Ar(`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 Ar(`baseKey must be a private key`,`InvalidAccessError`);if(!(S instanceof CryptoKey)||S.type!==`public`)throw new Ar(`algorithm.public must be a public key`,`InvalidAccessError`);if(S.algorithm.name!==n.algorithm.name)throw new Ar(`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 Ar(`Deriving bits failed: ${t.message}`,`OperationError`)}if(C==null)return toArrayBuffer(N);if(C>N.length*8)throw new Ar(`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 Ho,Uo=__esmMin(()=>{Ho={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 Wo=__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([Go[S[1]]^qo[t/n-1],Go[S[2]],Go[S[3]],Go[S[0]]]):n>6&&t%n===4&&(S=new Uint8Array([Go[S[0]],Go[S[1]],Go[S[2]],Go[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]=Go[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]=Go[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]=Ko[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]=Ko[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 Go,Ko,qo,Jo=__esmMin(()=>{Go=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]),Ko=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]),qo=[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`?ot.from(t,n||`utf8`):ot.from(t)}function encodeOutput(t,n){return n?ot.from(t).toString(n):ot.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 Yo=__esmMin(()=>{ht(),__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`?ot.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?ot.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`?ot.from(n):new Uint8Array(n),S==null?null:typeof S==`string`?ot.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,Xo=__esmMin(()=>{Jo(),Yo(),ht(),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 ot.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=ot.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=ot.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 ot.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=ot.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,$o))return`ed25519`;if(oidsEqual(t,Qo))return`x25519`}function oidForOkpCurve(t){return t===`ed25519`?$o:Qo}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,Zo))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,Zo))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(Zo),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(Zo),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=ot.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(`
16
16
  `)}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,Zo)&&(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 ts[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=es[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 Zo,Qo,$o,es,ts,ns=__esmMin(()=>{ht(),Zo=new Uint8Array([42,134,72,134,247,13,1,1,1]),Qo=new Uint8Array([43,101,110]),$o=new Uint8Array([43,101,112]),__name$1(modInverse$2,`modInverse`),es={"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`},ts={"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=rs[n];if(S===void 0)throw Error(`Unknown hash algorithm: ${t}`);return S}function toBuffer$1(t,n){return typeof t==`string`?ot.from(t,n||`utf8`):t instanceof DataView?ot.from(t.buffer,t.byteOffset,t.byteLength):(t instanceof ArrayBuffer,ot.from(t))}function codedError(t,n,S=Error){let C=new S(n);return C.code=t,C}var rs,is,as,os=__esmMin(()=>{ht(),rs={md5:16,sha1:20,sha256:32,sha384:48,sha512:64},is={md5:64,sha1:64,sha256:64,sha384:128,sha512:128},as=new Set([`md5`,`sha1`,`sha256`,`sha384`,`sha512`]),__name$1(toBuffer$1,`toBuffer`)});function fromBig(t,n=!1){return n?{h:Number(t&ss),l:Number(t>>cs&ss)}:{h:Number(t>>cs&ss)|0,l:Number(t&ss)|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 ss,cs,fromNumH,fromNumL,shrSH,shrSL,rotrSH,rotrSL,rotrBH,rotrBL,add3L,add3H,add4L,add4H,add5L,add5H,ls=__esmMin(()=>{ss=BigInt(2**32-1),cs=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(us(n)+`expected number, got `+typeof t);if(!Number.isSafeInteger(t)||t<0)throw RangeError(us(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=us(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$2(...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),fs)return t.toHex();let n=``;for(let S=0;S<t.length;S++)n+=ps[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(fs)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 us,ds,aopts,fs,ps,oidNist,ms=__esmMin(()=>{__name$1(isBytes$1,`isBytes`),us=__name$1(t=>t?`"${t}" `:``,`atitle`),__name$1(anumber$1,`anumber`),__name$1(abytes$1,`abytes`),ds=__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)=>{ds(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`)},__name$1(clean$2,`clean`),fs=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ps=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,hs,gs=__esmMin(()=>{ls(),ms(),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()}},hs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])}),_s,vs,ys,bs,xs,SHA2_64B,_SHA512,Ss,Cs=__esmMin(()=>{gs(),ls(),ms(),_s=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))),vs=_s[0],ys=_s[1],bs=new Uint32Array(80),xs=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)bs[S]=t.getUint32(n),xs[S]=t.getUint32(n+=4);for(let t=16;t<80;t++){let n=bs[t-15]|0,S=xs[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=bs[t-2]|0,I=xs[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,xs[t-7],xs[t-16]),Y=add4H(q,C,H,bs[t-7],bs[t-16]);bs[t]=Y|0,xs[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,ys[t],xs[t]),le=add5H(ce,ie,n,Q,vs[t],bs[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$2(bs,xs)}destroy(){this.destroyed=!0,clean$2(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,hs)}},Ss=createHasher(()=>new _SHA512,oidNist(3))});
17
17
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
@@ -146,7 +146,7 @@ fi
146
146
  `)}`:``;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=>{!Bp.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=>{Bp.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 Bp,Vp=__esmMin(()=>{Dp(),Cp(),zp(),Mp(),Bp=[`$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,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,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,YargsInstance,sh=__esmMin(()=>{_e(),jp(),Cp(),Vl(),Pp(),Dp(),Rp(),Vp(),Mp(),Wl(),Op(),wp(),kp(),Np(),__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)},wm=Symbol(`copyDoubleDash`),Tm=Symbol(`copyDoubleDash`),Em=Symbol(`deleteFromParserHintObject`),Dm=Symbol(`emitWarning`),Om=Symbol(`freeze`),km=Symbol(`getDollarZero`),Am=Symbol(`getParserConfiguration`),jm=Symbol(`getUsageConfiguration`),Mm=Symbol(`guessLocale`),Nm=Symbol(`guessVersion`),Pm=Symbol(`parsePositionalNumbers`),Fm=Symbol(`pkgUp`),Im=Symbol(`populateParserHintArray`),Lm=Symbol(`populateParserHintSingleValueDictionary`),Rm=Symbol(`populateParserHintArrayDictionary`),zm=Symbol(`populateParserHintDictionary`),Bm=Symbol(`sanitizeKey`),Vm=Symbol(`setKey`),Hm=Symbol(`unfreeze`),Um=Symbol(`validateAsync`),Wm=Symbol(`getCommandInstance`),Gm=Symbol(`getContext`),Km=Symbol(`getHasOutput`),qm=Symbol(`getLoggerInstance`),Jm=Symbol(`getParseContext`),Ym=Symbol(`getUsageInstance`),Xm=Symbol(`getValidationInstance`),Zm=Symbol(`hasParseCallback`),Qm=Symbol(`isGlobalContext`),$m=Symbol(`postProcess`),eh=Symbol(`rebase`),th=Symbol(`reset`),nh=Symbol(`runYargsParserAndExecuteCommands`),rh=Symbol(`runValidation`),ih=Symbol(`setHasOutput`),ah=Symbol(`kTrackManuallySetKeys`),oh=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,Hp.set(this,void 0),Up.set(this,void 0),Wp.set(this,{commands:[],fullCommands:[]}),Gp.set(this,null),Kp.set(this,null),qp.set(this,`show-hidden`),Jp.set(this,null),Yp.set(this,!0),Xp.set(this,{}),Zp.set(this,!0),Qp.set(this,[]),$p.set(this,void 0),em.set(this,{}),tm.set(this,!1),nm.set(this,null),im.set(this,!0),am.set(this,void 0),om.set(this,``),sm.set(this,void 0),cm.set(this,void 0),lm.set(this,{}),um.set(this,null),dm.set(this,null),fm.set(this,{}),pm.set(this,{}),mm.set(this,void 0),hm.set(this,!1),gm.set(this,void 0),_m.set(this,!1),vm.set(this,!1),ym.set(this,!1),bm.set(this,void 0),xm.set(this,{}),Sm.set(this,null),Cm.set(this,void 0),__classPrivateFieldSet(this,gm,C,`f`),__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldSet(this,Up,n,`f`),__classPrivateFieldSet(this,cm,S,`f`),__classPrivateFieldSet(this,$p,new GlobalMiddleware(this),`f`),this.$0=this[km](),this[th](),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`),`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`),`f`),__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`),`f`),__classPrivateFieldGet(this,sm,`f`).showHiddenOpt=__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldSet(this,am,this[Tm](),`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(oh)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,nm,`f`)&&(this[Em](__classPrivateFieldGet(this,nm,`f`)),__classPrivateFieldSet(this,nm,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,nm,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,nm,`f`)),this.describe(__classPrivateFieldGet(this,nm,`f`),n||__classPrivateFieldGet(this,bm,`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,qp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,sm,`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[Rm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`array`,t),this[ah](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`boolean`,t),this[ah](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,bm,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,bm,`f`).fail(__classPrivateFieldGet(this,gm,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,bm,`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[Rm](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 Bl(`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 Bl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,sm,`f`).key[S]=!0,__classPrivateFieldGet(this,$p,`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 Bl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`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,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,sm,`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,Kp,t||__classPrivateFieldGet(this,Kp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,Kp,`f`),n),S&&__classPrivateFieldGet(this,Gp,`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,Hp,`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,cm,`f`)||__classPrivateFieldGet(this,gm,`f`).require;return __classPrivateFieldGet(this,Hp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,gm,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`count`,t),this[ah](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=__classPrivateFieldGet(this,bm,`f`).functionDescription(n)),n=n.call()),this[Lm](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,sm,`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,gm,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`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[Lm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Vm](t,!0),__classPrivateFieldGet(this,bm,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,sm,`f`).envPrefix:__classPrivateFieldGet(this,sm,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`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,bm,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldSet(this,Jp,n,`f`),__classPrivateFieldGet(this,Zp,`f`)&&__classPrivateFieldGet(this,gm,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Zp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new Bl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,bm,`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,Gp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,Gp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Yp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Zp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,em,`f`),__classPrivateFieldGet(this,pm,`f`))}getHelp(){if(__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}let t=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,bm,`f`).help())}getOptions(){return __classPrivateFieldGet(this,sm,`f`)}getStrict(){return __classPrivateFieldGet(this,_m,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,vm,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,ym,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,sm,`f`).local.includes(t)||__classPrivateFieldGet(this,sm,`f`).local.push(t)}):__classPrivateFieldGet(this,sm,`f`).local=__classPrivateFieldGet(this,sm,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,pm,`f`)[n]||__classPrivateFieldGet(this,em,`f`)[n];__classPrivateFieldGet(this,pm,`f`)[n]&&delete __classPrivateFieldGet(this,pm,`f`)[n];let C={};return __classPrivateFieldGet(this,em,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,sm,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[Mm](),__classPrivateFieldGet(this,gm,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,$p,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[Lm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`number`,t),this[ah](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[ah](t),__classPrivateFieldGet(this,Sm,`f`)&&(t===`version`||n?.alias===`version`)&&this[Dm]([`"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(`
147
147
  `),void 0,`versionWarning`),__classPrivateFieldGet(this,sm,`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,sm,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,bm,`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[Om](),t===void 0&&(t=__classPrivateFieldGet(this,mm,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,dm,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,um,n,`f`),n=!1),n||__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldSet(this,Zp,!1,`f`);let C=this[nh](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,Gp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),t,__classPrivateFieldGet(this,om,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,om,`f`)),t}).finally(()=>{this[Hm](),this.parsed=N}):(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),C,__classPrivateFieldGet(this,om,`f`)),this[Hm](),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 Bl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,lm,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[Fm](n||__classPrivateFieldGet(this,Up,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`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,Wp,`f`).fullCommands[__classPrivateFieldGet(this,Wp,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,Hp,`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,bm,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,hm,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,sm,`f`).narg[t]||this[Lm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,am,`f`).log(__classPrivateFieldGet(this,Gp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,Kp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,bm,`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,bm,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,_m,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,vm,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,ym,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`string`,t),this[ah](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,gm,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`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,gm,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new Bl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,bm,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,xm,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Sm,`f`)&&(this[Em](__classPrivateFieldGet(this,Sm,`f`)),__classPrivateFieldGet(this,bm,`f`).version(void 0),__classPrivateFieldSet(this,Sm,null,`f`)),arguments.length===0)S=this[Nm](),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,Sm,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,bm,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Sm,`f`)),this.describe(__classPrivateFieldGet(this,Sm,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).wrap(t),this}[(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=new WeakMap,tm=new WeakMap,nm=new WeakMap,im=new WeakMap,am=new WeakMap,om=new WeakMap,sm=new WeakMap,cm=new WeakMap,lm=new WeakMap,um=new WeakMap,dm=new WeakMap,fm=new WeakMap,pm=new WeakMap,mm=new WeakMap,hm=new WeakMap,gm=new WeakMap,_m=new WeakMap,vm=new WeakMap,ym=new WeakMap,bm=new WeakMap,xm=new WeakMap,Sm=new WeakMap,Cm=new WeakMap,wm)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[Tm](){return{log:(...t)=>{this[Zm]()||ge.log(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
148
148
  `,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Zm]()||ge.error(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
149
- `,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](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[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`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,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`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,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Bl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Bl(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Bl)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Bl(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.53`,"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 dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__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):ph}function parseNpmrc(t){let n={registry:ph,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 ph,mh=__esmMin(()=>{ph=`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 hh=__esmMin(()=>{fh(),__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 gh=__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 vh=__esmMin(()=>{dh(),fh(),mh(),hh()});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 yh=__esmMin(()=>{dh(),fh(),hh(),gh()});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 bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});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 Sh===void 0&&(Sh=`0.64.53`),Sh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(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=Hn(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 Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(eu(),__toCommonJS(Xl)),N=(af(),__toCommonJS(nf)),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)})),Ph=__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})),Fh=__commonJSMin(((t,n)=>{let S=Ph();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}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(iu(),__toCommonJS(tu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();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)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(Uu(),__toCommonJS(zu)),C=Lh(),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
+ `,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](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[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`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,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`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,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Bl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Bl(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Bl)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Bl(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.55`,"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 dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__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):ph}function parseNpmrc(t){let n={registry:ph,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 ph,mh=__esmMin(()=>{ph=`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 hh=__esmMin(()=>{fh(),__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 gh=__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 vh=__esmMin(()=>{dh(),fh(),mh(),hh()});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 yh=__esmMin(()=>{dh(),fh(),hh(),gh()});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 bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});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 Sh===void 0&&(Sh=`0.64.55`),Sh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(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=Hn(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 Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(eu(),__toCommonJS(Xl)),N=(af(),__toCommonJS(nf)),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)})),Ph=__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})),Fh=__commonJSMin(((t,n)=>{let S=Ph();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}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(iu(),__toCommonJS(tu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();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)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(Uu(),__toCommonJS(zu)),C=Lh(),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(`
150
150
  `)},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(`
151
151
  `)},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})),zh=__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=`
152
152
  `,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{}}})),Bh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
@@ -951,7 +951,7 @@ Add @gjsify/node-gi as a dependency to run it on Node, e.g.:
951
951
  echo "gjsify: got: node $*" >&2
952
952
  exit 127 ;;
953
953
  esac
954
- `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Xz,Zz,Qz,$z=__esmMin(()=>{gl(),af(),o_(),Xn(),cr(),P_(),NR(),gL(),ZR(),Yz(),qI(),Xz=!1,Zz=!1,Qz=`node-shim`});function markDaemonCommand(){eB=!0}function isDaemonCommand(){return eB}var eB,tB=__esmMin(()=>{eB=!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(zn(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=In(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||Un(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=zn(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=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(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(Jn),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(()=>(FX(),PX));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 nB,rB=__esmMin(()=>{_e(),af(),Xn(),TR(),hv(),VR(),UR(),YR(),XR(),$z(),qI(),sR(),tB(),GI(),P_(),vv(),nB={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:gv,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: ${gv.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(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(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)}}}),iB,aB=__esmMin(()=>{_e(),Xn(),gL(),iB={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?In(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>`)}}}),oB,sB=__esmMin(()=>{_e(),dL(),oB={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
954
+ `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Xz,Zz,Qz,$z=__esmMin(()=>{gl(),af(),o_(),Xn(),cr(),P_(),NR(),gL(),ZR(),Yz(),qI(),Xz=!1,Zz=!1,Qz=`node-shim`});function markDaemonCommand(){eB=!0}function isDaemonCommand(){return eB}var eB,tB=__esmMin(()=>{eB=!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(zn(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=In(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||Un(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=zn(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=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(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(Jn),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(()=>(VX(),BX));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 nB,rB=__esmMin(()=>{_e(),af(),Xn(),TR(),hv(),VR(),UR(),YR(),XR(),$z(),qI(),sR(),tB(),GI(),P_(),vv(),nB={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:gv,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: ${gv.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(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(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)}}}),iB,aB=__esmMin(()=>{_e(),Xn(),gL(),iB={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?In(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>`)}}}),oB,sB=__esmMin(()=>{_e(),dL(),oB={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
955
955
  `);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(`
956
956
  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(`
957
957
  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(`
@@ -972,7 +972,7 @@ No install command available for your package manager. Install manually.`),proce
972
972
  bunx @gjsify/cli@latest showcase <name>
973
973
  deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,kB={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:gv,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:
974
974
  `);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: ${gv.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:
975
- `);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(()=>(FX(),PX));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=Hn(fileURLToPath(import.meta.url)),n=[zn(t,`..`,`dist-templates`),zn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,zn(Hn(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=zn(t,S),N=zn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=jB[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 jB,MB=__esmMin(()=>{af(),eu(),Xn(),cr(),jB={"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,...PB[t]].join(` `)}function runScriptCommand(t){return FB[t]}function packageManagersForRuntime(t){return IB[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 NB,PB,FB,IB,LB,RB=__esmMin(()=>{NB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],PB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},FB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},IB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},LB={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 zB=__esmMin(()=>{RB()});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=In(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=[[BB,n],[VB,applicationIdFor(n)]];renameSentinelPaths(t,S),substituteSentinelContents(t,S)}function renameSentinelPaths(t,n){for(let S of readdirSync(t,{withFileTypes:!0})){let C=S.name;for(let[t,S]of n)C=C.replaceAll(t,S);let N=zn(t,S.name),F=zn(t,C);F!==N&&renameSync(N,F),S.isDirectory()&&renameSentinelPaths(F,n)}}function substituteSentinelContents(t,n){let S=new Set([`node_modules`,`dist`,`lib`]),C=[t];for(;C.length>0;){let t=C.pop();for(let N of readdirSync(t,{withFileTypes:!0})){let F=zn(t,N.name);if(N.isDirectory()){S.has(N.name)||C.push(F);continue}if(!N.isFile())continue;let I=N.name.lastIndexOf(`.`),H=I>=0?N.name.slice(I):``;if(!HB.has(H)&&!UB.has(N.name))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,S]of n)q=q.replaceAll(t,S);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(``)}I.ship&&(ge.log(`Package it for a machine without gjsify:`),ge.log(` ${F} ship -- darwin`),ge.log(``))}function templateManifest(t){try{return JSON.parse(readFileSync(zn(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 BB,VB,HB,UB,WB=__esmMin(()=>{_e(),cv(),af(),Xn(),MB(),RB(),zB(),BB=`new-gjsify-app`,VB=`org.gjsify.example`,HB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),UB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===KB}function render(t,n,S){S||xn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${GB.cyan}❯${GB.reset}`:` `,F=S===n?`${GB.bold}${GB.green}${C.label}${GB.reset}`:C.label,I=C.description?` ${GB.dim}${C.description}${GB.reset}`:``;xn.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;xn.write(`${GB.bold}${t}${GB.reset} ${GB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${GB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
975
+ `);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(()=>(VX(),BX));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=Hn(fileURLToPath(import.meta.url)),n=[zn(t,`..`,`dist-templates`),zn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,zn(Hn(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=zn(t,S),N=zn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=jB[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 jB,MB=__esmMin(()=>{af(),eu(),Xn(),cr(),jB={"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,...PB[t]].join(` `)}function runScriptCommand(t){return FB[t]}function packageManagersForRuntime(t){return IB[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 NB,PB,FB,IB,LB,RB=__esmMin(()=>{NB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],PB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},FB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},IB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},LB={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 zB=__esmMin(()=>{RB()});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=In(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=[[BB,n],[VB,applicationIdFor(n)]];renameSentinelPaths(t,S),substituteSentinelContents(t,S)}function renameSentinelPaths(t,n){for(let S of readdirSync(t,{withFileTypes:!0})){let C=S.name;for(let[t,S]of n)C=C.replaceAll(t,S);let N=zn(t,S.name),F=zn(t,C);F!==N&&renameSync(N,F),S.isDirectory()&&renameSentinelPaths(F,n)}}function substituteSentinelContents(t,n){let S=new Set([`node_modules`,`dist`,`lib`]),C=[t];for(;C.length>0;){let t=C.pop();for(let N of readdirSync(t,{withFileTypes:!0})){let F=zn(t,N.name);if(N.isDirectory()){S.has(N.name)||C.push(F);continue}if(!N.isFile())continue;let I=N.name.lastIndexOf(`.`),H=I>=0?N.name.slice(I):``;if(!HB.has(H)&&!UB.has(N.name))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,S]of n)q=q.replaceAll(t,S);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(``)}I.ship&&(ge.log(`Package it for a machine without gjsify:`),ge.log(` ${F} ship -- darwin`),ge.log(``))}function templateManifest(t){try{return JSON.parse(readFileSync(zn(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 BB,VB,HB,UB,WB=__esmMin(()=>{_e(),cv(),af(),Xn(),MB(),RB(),zB(),BB=`new-gjsify-app`,VB=`org.gjsify.example`,HB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),UB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===KB}function render(t,n,S){S||xn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${GB.cyan}❯${GB.reset}`:` `,F=S===n?`${GB.bold}${GB.green}${C.label}${GB.reset}`:C.label,I=C.description?` ${GB.dim}${C.description}${GB.reset}`:``;xn.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;xn.write(`${GB.bold}${t}${GB.reset} ${GB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${GB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
976
976
  `),N(Error(KB));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))}};Sn.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:LB[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 GB,KB,qB=__esmMin(()=>{_e(),Cn(),Xd(),RB(),zB(),GB={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},KB=`Cancelled by user`}),JB,YB=__esmMin(()=>{_e(),WB(),qB(),JB={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:NB})},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=Un(t,Wn(t));return In(Hn(t),n)}var XB,ZB,QB=__esmMin(()=>{_e(),cv(),Vd(),Xn(),Uu(),XB=promisify(execFile),ZB={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=In(t.xml),S=t.target?In(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?In(t.sourcedir):Hn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(Hn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await XB(`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=zn(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 $B=__esmMin(()=>{cv(),Xn()});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=zn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(zn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Un(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:zn(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=zn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${zn(n,t.filename)}`,zn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await eV(`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?Un(S.replace(/\.in$/,``)):`${t}.xml`}}var eV,tV,nV=__esmMin(()=>{_e(),cv(),Vd(),o_(),Xn(),Uu(),$B(),eV=promisify(execFile),tV={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=In(t.poDir),S=In(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?In(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}}}}),rV,iV,aV=__esmMin(()=>{_e(),cv(),Vd(),Xn(),Uu(),rV=promisify(execFile),iV={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=In(t.schemadir),S=t.targetdir?In(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 rV(`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=In(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 oV,sV=__esmMin(()=>{af(),Xn(),oV=`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`?`51`:`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 cV,lV,uV=__esmMin(()=>{cV=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],lV=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of fV){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 scalableAppIconCleanup(t){return`/share/icons/hicolor/scalable/apps/${t}.svg`}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`?lV:cV),cleanup:[...new Set([...W??[],...t.kind===`app`?[scalableAppIconCleanup(t.appId)]:[]])]},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 ${dV}. 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 dV,fV,pV=__esmMin(()=>{uV(),dV=`1.0.0`,fV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return mV}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,...(t.desktopExecArgs??[]).map(n=>quoteExecArg(n,t.configKey))].join(` `)+execFieldCode(N),APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function quoteExecArg(t,n){if(/[\r\n]/.test(t))throw Error(`${n}.desktopExecArgs contains ${JSON.stringify(t)}: a newline cannot appear in a desktop entry's Exec= line.`);let S=t.replace(/%/g,`%%`);return S===``?`""`:hV.test(S)?`"${S.replace(/(["`$\\])/g,`\\$1`).replace(/\\/g,`\\\\`)}"`:S}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>`);for(let[n,S]of Object.entries(t.localizedUrls??{}))F.push(` <image xml:lang="${escapeXml(n)}">${escapeXml(S)}</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&&channelAllowsDonations(t.channel)&&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(`
977
977
  `)+`
978
978
  `}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 mV,hV,gV=__esmMin(()=>{kh(),mV=`[Desktop Entry]
@@ -1173,55 +1173,55 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
1173
1173
  `).map(t=>t.trim()===``?` .`:` ${t}`).join(`
1174
1174
  `);return[`Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/`,`Upstream-Name: ${t.name}`,...t.homepage?[`Source: ${t.homepage}`]:[],``,`Files: *`,`Copyright: ${t.maintainer}`,`License: ${t.license}`,S,``].join(`
1175
1175
  `)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=Wn(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${_H.icons}/${F}/apps/${I}${N}`,W=S.get(H);if(W!==void 0)throw Error(`gjsify ship: ${C} and ${W} both install as ${H}. An icon is keyed on its context and its size: \`symbolic\` is read from a \`symbolic/\` path component or a \`-symbolic\` filename, the size from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`). Give them distinguishable sizes, or point \`gjsify.ship.icon\` at a single file.`);S.set(H,C),n.push({path:H,mode:420,source:{kind:`file`,path:C}})}return n}function assertInsidePrefix(t){let n=On.normalize(t);if(On.isAbsolute(n)||n===`..`||n.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${t}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return n}function isExecutableAsset(t){return/\.(so|node|dylib)(\.\d+)*$/.test(t)}function normalise(t){let n=new Map;for(let S of t)n.set(S.path,S);return[...n.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var KU=__esmMin(()=>{GU(),gH(),wH(),TU(),vH(),Vd(),Xn()});function isGtkRuntimeTarget(t){return qU.includes(t)}function gtkRuntimePackageName(t){return`@gjsify/gtk-runtime-${t}`}function resolveGtkRuntime(t,n={}){let S=n.env??process.env,C=t.startsWith(`win32-`)?`bin`:`lib`,N=[],F=S.GJSIFY_GTK_RUNTIME;F&&N.push({source:`GJSIFY_GTK_RUNTIME`,dir:F});let I=resolveNodeGiRoot(n);I!==null&&(N.push({source:`${YU}/prebuilds/${t}`,dir:zn(I,`prebuilds`,t,`gtk`)}),N.push({source:`${YU} sibling`,dir:zn(I,`..`,`gtk-runtime-${t}`,`gtk`)}));let H=gtkRuntimePackageName(t),W=resolveStagedPackage(H,n);W!==null&&N.push({source:H,dir:zn(Hn(W),`gtk`)}),n.fetchedGtkRuntimeDir!==void 0&&N.push({source:`${H} (fetched for this ship run)`,dir:zn(n.fetchedGtkRuntimeDir,`gtk`)});for(let t of N){let n=zn(t.dir,C),S=zn(t.dir,`girepository-1.0`);if(!(!existsSync(n)||!existsSync(S)))return{source:t.source,dir:t.dir,libDir:n,typelibDir:S}}return null}function resolveNodeGiAddon(t,n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=zn(S,`prebuilds`,t,JU);return existsSync(C)?{source:YU,addonPath:C}:null}function resolveNodeGiRoot(t){let n=resolveStagedPackage(YU,t);return n===null?null:Hn(n)}function resolveStagedPackage(t,n,{fromCli:S=!0}={}){let C=S?{bundleUrl:import.meta.url}:{};return n.cwd!==void 0&&(C.cwd=n.cwd),n.resolve!==void 0&&(C.resolve=n.resolve),resolveInstalledPackage(t,C)}function quartzBridgePackageName(t){return`${XU}-${t}`}function resolveQuartzBridge(t,n={}){if(!t.startsWith(`darwin-`))return null;let S=quartzBridgePackageName(t),dirOf=(t,n)=>{let S=resolveStagedPackage(`${t}/package.json`,n,{fromCli:!1});return S===null?null:Hn(S)},C=dirOf(S,n),N=null;if(C===null){if(N=dirOf(XU,n),N===null){let t=resolveStagedPackage(`@gjsify/adwaita-app`,n,{fromCli:!1}),S=t===null?null:packageRootOf(t);S!==null&&(N=dirOf(XU,{...n,cwd:S}))}N!==null&&(C=dirOf(S,{...n,cwd:N}))}if(C===null)return N===null?null:{unpopulated:`${S} is not installed`};let F=zn(C,`prebuilds`,t),I=zn(F,ZU),H=zn(F,QU);return!existsSync(I)||!existsSync(H)?{unpopulated:`${S} holds no prebuilds/${t}/{${ZU},${QU}}`}:{source:S,typelibPath:I,libraryPath:H}}function packageRootOf(t){let n=Hn(t);for(;;){if(existsSync(zn(n,`package.json`)))return n;let t=Hn(n);if(t===n)return null;n=t}}function resolveNodeGiPackage(t={}){let n=resolveNodeGiRoot(t);if(n===null)return null;let S=[`package.json`];for(let t of readdirSync(n,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1))t.isFile()&&t.name.endsWith(`.js`)&&S.push(t.name);let C=zn(n,`overrides`);if(existsSync(C))for(let t of listFilesRecursive(C))S.push(On.join(`overrides`,t));return S.length>1?{source:YU,root:n,files:S.sort()}:null}function appRuntimePaths(t,n,S){let C=t.dirs(n),N=On.join(C.native,`node-gi`),F=On.join(N,`prebuilds`,S);return{nodeGiRoot:N,nodeGiPackageDir:On.join(C.bundle,`node_modules`,YU),prebuildDir:F,gtkDir:On.join(F,`gtk`),addonPath:On.join(F,JU),interpreterPath:C.helpers===``?On.join(C.launcher,nodeRuntimeBinaryName(S)):On.join(C.helpers,assertUsableAsHelperName(n.name)),interpreterLicensePath:On.join(C.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(t){let n=appRuntimePaths(t.layout,t.identity,t.target),S=[],C={},N=[],F=[];t.interpreter===null?F.push(`no bundled interpreter — install \`@gjsify/node-runtime-${t.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(S.push({path:n.interpreterPath,mode:493,source:{kind:`file`,path:t.interpreter.nodePath}}),S.push({path:n.interpreterLicensePath,mode:420,source:{kind:`file`,path:t.interpreter.licensePath}}),C.interpreter=n.interpreterPath,N.push(`interpreter from ${t.interpreter.source}`));let I=resolveGtkRuntime(t.target,discoveryOptions(t));if(I!==null){for(let t of listFilesRecursive(I.dir)){let C=zn(I.dir,t.split(`/`).join(qn));S.push({path:On.join(n.gtkDir,t),mode:stagedMode(t,C),source:{kind:`file`,path:C}})}C.gtkRuntimeDir=n.gtkDir,N.push(`GTK closure from ${I.source}`);let H=resolveQuartzBridge(t.target,discoveryOptions(t));H!==null&&`unpopulated`in H?F.push(`Dock-click reopen bridge not carried — ${H.unpopulated}`):H!==null&&(S.push({path:On.join(n.gtkDir,`girepository-1.0`,ZU),mode:420,source:{kind:`file`,path:H.typelibPath}}),S.push({path:On.join(n.gtkDir,nativeSubdirOf(t.target),QU),mode:493,source:{kind:`file`,path:H.libraryPath}}),N.push(`Dock-click reopen bridge from ${H.source}`))}else{let n=t.target.startsWith(`win32-`)?`bin`:`lib`,S=t.gtkFetchFailure===void 0?``:` — fetching it failed: ${t.gtkFetchFailure}`;F.push(`no GTK closure${S} — point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${n}/\` and \`girepository-1.0/\`, or install \`${gtkRuntimePackageName(t.target)}\` where the build can reach it`)}let H=resolveNodeGiPackage(discoveryOptions(t));if(H!==null){for(let t of H.files)S.push({path:On.join(n.nodeGiPackageDir,t),mode:420,source:{kind:`file`,path:zn(H.root,t.split(`/`).join(qn))}});N.push(`node-gi runtime (${H.files.length} file(s)) from ${H.source}`)}else F.push(`no node-gi JavaScript — install \`${YU}\`; a \`--app node\` bundle keeps \`@gjsify/node-gi/*\` external, so the staged bundle would \`require\` a package the artifact does not carry`);let W=resolveNodeGiAddon(t.target,discoveryOptions(t));return W===null?F.push(`no node-gi addon — install \`${YU}\`, whose \`prebuilds/${t.target}/${JU}\` is the binary built against that closure`):(S.push({path:n.addonPath,mode:493,source:{kind:`file`,path:W.addonPath}}),C.nodeGiAddon=n.addonPath,N.push(`node-gi addon from ${W.source}`)),{files:S,launcher:C,found:N,missing:F}}function nativeSubdirOf(t){return t.startsWith(`win32-`)?`bin`:`lib`}function discoveryOptions(t){let n={};return t.cwd!==void 0&&(n.cwd=t.cwd),t.env!==void 0&&(n.env=t.env),t.resolve!==void 0&&(n.resolve=t.resolve),t.fetchedGtkRuntimeDir!==void 0&&(n.fetchedGtkRuntimeDir=t.fetchedGtkRuntimeDir),n}function stagedMode(t,n){if(isExecutableAsset(t)||t.startsWith(`libexec/`)||t.startsWith(`bin/`))return 493;try{if(statSync(n).mode&73)return 493}catch{}return 420}var qU,JU,YU,XU,ZU,QU,$U=__esmMin(()=>{af(),Xn(),zU(),oU(),VU(),KU(),YI(),qU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`],JU=`node_gi.node`,YU=`@gjsify/node-gi`,XU=`@gjsify/gtk-quartz-native`,ZU=`GjsifyQuartz-1.0.typelib`,QU=`libgjsifyquartz.dylib`});function stageSubordinates(t){let n=t.layout.dirs(t.identity),S=[],C=[],N=[];for(let N of t.nestedBundles){if(n.plugins===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/PlugIns\` equivalent, so the nested bundle "${N.name}" has nowhere to go. \`gjsify.ship.nestedBundles\` is darwin-only; \`resolveShipNestedBundles\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.plugins,N.name);for(let t of listFilesRecursive(N.source)){let n=zn(N.source,...t.split(On.sep));S.push({path:On.join(F,t),mode:/^Contents\/MacOS\/[^/]+$/.test(t)?493:stagedMode(t,n),source:{kind:`file`,path:n}})}C.push({path:F,entitlements:N.entitlements})}for(let C of t.helperExecutables){if(n.helpers===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/Helpers\` equivalent, so the helper executable "${C.name}" has nowhere to go. \`gjsify.ship.helperExecutables\` is darwin-only; \`resolveShipHelperExecutables\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.helpers,C.name);S.push({path:F,mode:493,source:{kind:`file`,path:C.source}}),N.push({path:F,entitlements:C.entitlements})}if(t.mainExecutable!==void 0){if(t.layout.name!==`darwin`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` is darwin-only, but the ${t.layout.name} layout was asked to stage it — report this as a gjsify bug.`);S.push({path:mainExecutablePath(t.layout,t.identity),mode:493,source:{kind:`file`,path:t.mainExecutable}})}return{files:S,nestedBundles:C,helperExecutables:N}}function signedSubordinatesFor(t,n,S){let C=t.dirs(n);return{nestedBundles:S.nestedBundles.map(t=>({path:On.join(C.plugins,t.name),entitlements:t.entitlements})),helperExecutables:S.helperExecutables.map(t=>({path:On.join(C.helpers,t.name),entitlements:t.entitlements}))}}function plistStringValue(t,n){return RegExp(`<key>${n}</key>\\s*<string>([^<]*)</string>`).exec(t)?.[1]}function nestedBundlePlist(t,n){let S=t.find(t=>t.path===On.join(n,`Contents`,`Info.plist`));return S===void 0?void 0:new TextDecoder().decode(S.data)}function recordedNestedBundles(t,n){return n.map(n=>{let S=On.basename(n.path),C=nestedBundlePlist(t,n.path);if(C===void 0)return{name:S};let N=plistStringValue(C,`CFBundleIdentifier`),F=plistStringValue(C,`NSExtensionPointIdentifier`);return{name:S,...N===void 0?{}:{bundleId:N},...F===void 0?{}:{extensionPoint:F}}})}var eW=__esmMin(()=>{Xn(),zU(),$U(),oU()});function readManifest(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf-8`))}catch{return null}}function findInstalled(t,n){let S=n;for(;;){let n=zn(S,`node_modules`,...t.split(`/`));if(existsSync(zn(n,`package.json`)))return n;let C=Hn(S);if(C===S)return null;S=C}}function allows(t,n){let S=typeof t==`string`?[t]:t??[];if(S.includes(`!${n}`))return!1;let C=S.filter(t=>!t.startsWith(`!`));return C.length===0||C.includes(n)}function destinationOf(t){let n=t.split(qn),S=n.indexOf(`node_modules`);return S===-1||S===n.length-1?null:n.slice(S+1).join(`/`)}function resolveNodeModulesClosure(t,n,S={}){let{target:C,exclude:N=[]}=S,F=new Map,I=[],H=[],W=[],visit=(t,n,S,q)=>{if(t===tW)return;if(S.length>0&&N.includes(t)){W.includes(t)||W.push(t);return}let Y=findInstalled(t,n);if(Y===null){if(q){I.includes(t)||I.push(t);return}throw Error(`gjsify ship: \`${t}\` is not installed${S.length>0?` (needed by ${S.join(` > `)})`:``}. `+(S.length===0?"`gjsify.ship.nodeModules` names it, so the artifact must carry it — install it, or remove the entry.":`A package without its required dependency is an artifact that fails at its first import.`))}let X=destinationOf(Y);if(X===null)throw Error(`gjsify ship: ${Y} is not inside a node_modules directory, so it has no place to be staged.`);let Z=realpathSync(Y),te=readManifest(Z);if(te===null)throw Error(`gjsify ship: ${zn(Z,`package.json`)} is unreadable.`);if(S.length>0&&C!==void 0&&!(allows(te.os,C.os)&&allows(te.cpu,C.cpu))){H.includes(t)||H.push(t);return}let ne=F.get(X);if(ne!==void 0){if(ne.dir!==Z)throw Error(`gjsify ship: two installed copies of \`${t}\` would both be staged at node_modules/${X} (${ne.dir} and ${Z}).`);return}F.set(X,{name:t,version:te.version??`0.0.0`,dir:Z,dest:X});let re=[...S,t];for(let t of Object.keys(te.dependencies??{}))visit(t,Y,re,!1);for(let t of Object.keys(te.optionalDependencies??{}))visit(t,Y,re,!0)};for(let S of t)visit(S,n,[],!1);return{packages:[...F.values()].sort((t,n)=>t.dest<n.dest?-1:1),skippedOptional:I.sort(),skippedForTarget:H.sort(),excluded:W.sort(),target:C}}function prebuildPlatformOf(t){let n=/^(?:.*\/)?prebuilds\/([a-z0-9]+)-([a-z0-9_]+)(?:[-+][a-z0-9]+)?$/.exec(t);return n===null?null:[n[1],n[2]]}function listPackageFiles(t,n,S){let C=[],walk=N=>{for(let F of readdirSync(N,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let I=zn(N,F.name);if(F.isDirectory()){if(F.name===`node_modules`)continue;let C=n===void 0?null:prebuildPlatformOf(On.join(...Bn(t,I).split(qn)));if(C!==null&&(C[0]!==n.os||C[1]!==n.cpu)){S?.push(On.join(...Bn(t,I).split(qn)));continue}walk(I)}else if(F.isSymbolicLink())throw Error(`gjsify ship: ${I} is a symlink. The payload has to be self-contained — a package that links inside itself needs the link replaced by the file.`);else F.isFile()&&C.push(On.join(...Bn(t,I).split(qn)))}};return walk(t),C}function modeOf(t,n){return isExecutableAsset(t)||statSync(n).mode&73?493:420}function stageNodeModules(t,n){let S=[],C=[];t.skippedPrebuilds=C;for(let N of t.packages){let F=C.length;for(let F of listPackageFiles(N.dir,t.target,C)){let t=zn(N.dir,...F.split(`/`));S.push({path:On.join(n,`node_modules`,N.dest,F),mode:modeOf(F,t),source:{kind:`file`,path:t}})}for(let t=F;t<C.length;t++)C[t]=`${N.name}/${C[t]}`}return S}var tW,nW=__esmMin(()=>{af(),Xn(),KU(),tW=`@gjsify/node-gi`});async function acquireGtkRuntime(t){let n=t.discovery??{};if(resolveGtkRuntime(t.target,n)!==null)return{kind:`present`};let S=gtkRuntimePackageName(t.target),C=`${S}@${t.version}`;if((n.env??process.env).GJSIFY_GTK_RUNTIME_FETCH===`0`)return{kind:`failed`,reason:`GJSIFY_GTK_RUNTIME_FETCH=0 turned off the fetch of ${C}`};t.log?.(`${S} is not installed here, and is not meant to be — fetching ${C} into the cache (about 100 MB, once)`);let N;try{N=await t.ensure(C)}catch(t){return{kind:`failed`,reason:t instanceof Error?t.message:String(t)}}return resolveGtkRuntime(t.target,{...n,fetchedGtkRuntimeDir:N})===null?{kind:`failed`,reason:`${C} was fetched to ${N} but holds no complete gtk/ closure`}:{kind:`fetched`,dir:N}}var rW=__esmMin(()=>{$U()});function appDirFor(t){return zn(t,`appimage`,cW)}function appImageHostRequirements(t){let n=interpreterFloor(t),S=new Set(t.optionalNamespaces??[]);return[`${t.app} (>= ${n})`,...hostProvidedNamespaces(t.namespaces,t.bundledTypelibs).map(t=>S.has(t)?`the ${t} typelib (optional)`:`the ${t} typelib`)]}function interpreterFloor(t){return t.app===`node`?t.minNodeVersion??`24`:t.minGjsVersion??`1.86`}function renderAppRun(t,n){let S=rU.linux.dirs(t).launcher,C=interpreterFloor(t),[N=`0`,F=`0`]=C.split(`.`);return[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(dirname "$(readlink -f "$0")")`,`if ! command -v ${t.app} >/dev/null 2>&1; then`,` echo "${shellSafe(t.name)} needs ${t.app}, and this system has none." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 127`,`fi`,`found=$(${t.app} --version 2>/dev/null | sed -n 's/[^0-9]*\\([0-9][0-9]*\\)\\.\\([0-9][0-9]*\\).*/\\1 \\2/p' | head -n 1 || true)`,"major=${found% *}","minor=${found#* }",`if [ -n "$major" ]; then`,` if [ "$major" -lt ${N} ] || { [ "$major" -eq ${N} ] && [ "$minor" -lt ${F} ]; }; then`,` echo "${shellSafe(t.name)} needs ${t.app} ${C} or newer, and this system has $major.$minor." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 126`,` fi`,`fi`,`exec "$here/usr/${S}/${t.binaryName}" "$@"`,``].join(`
1176
- `)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${sW}/runtime-${t} (or point ${oW} at a directory holding it).`:`the AppImage runtime is pinned: ${n} — this pack needs no network`}function selectAppDirIcon(t,n){let S;for(let C of t){let t=rootIconRank(C.path,n);t!==void 0&&(S===void 0||t>S.rank)&&(S={entry:C,rank:t})}return S?.entry}function rootIconRank(t,n){if(dW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${_H.icons}/`)||t.includes(`/symbolic/`))return;if(t.includes(`/scalable/`))return 2**53-1;let S=/\/(\d+)x\1\//.exec(t);return S===null?1:Number(S[1])}function assertAppImageIsPackable(t,n,S){let C=`${_H.applications}/${n.appId}.desktop`;if(!t.some(t=>t.path===C))throw Error(`gjsify ship: an AppImage needs a desktop entry and this payload has no ${C}. appimagetool refuses an AppDir without one, and the AppImage runtime has nothing to tell a desktop about the application it just mounted. A \`kind: "cli"\` project stages no entry by design — set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`);if(selectAppDirIcon(t,n.appId)===void 0)throw Error(`gjsify ship: an AppImage needs an icon called ${n.appId} beside its desktop entry, and this payload stages none under ${_H.icons}/. The entry's \`Icon=\` names the app id, so a file keeping its own basename is an icon nothing looks up — point \`gjsify.ship.icon\` at a PNG or an SVG and it is renamed into the theme for you.`);if(S===void 0&&t.some(t=>isSchemaSource(t.path)))throw Error(`gjsify ship: this payload stages GSettings schema sources under ${_H.schemas}/ and no ${uU} was compiled for it. An AppImage has NO INSTALL STEP — that is the whole point of the format — so the \`.deb\`/\`.rpm\` postinst that compiles the system schema directory never runs, and GSettings aborts on a directory holding only sources. The AppDir must carry ${uU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${_H.applications}/${t.appId}.desktop`,I=n.find(t=>t.path===F);return[...[...n,...C===void 0?[]:[C]].map(t=>({...t,path:`usr/${t.path}`})),{path:lW,mode:493,data:encodeUtf8(renderAppRun(t,S))},{path:`${t.appId}.desktop`,mode:420,data:I.data},{path:N.path.slice(N.path.lastIndexOf(`/`)+1),mode:420,data:N.data},{path:uW,mode:420,data:N.data}]}function appImageToolArgs(t){return[`--no-appstream`,`--comp`,`zstd`,...t.runtimeFile===void 0?[]:[`--runtime-file`,t.runtimeFile],t.appDir,t.target]}function appImageToolEnv(t){return{ARCH:t,[aW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${iW} fetches it from github.com/AppImage/type2-runtime when no runtime is pinned, so this pack needs a network and an offline host fails here having written nothing; or `:`the pinned runtime at ${n} is not an AppImage runtime — it is passed through to \`--runtime-file\` unread, so a truncated or wrong-architecture file fails here; or `;return`gjsify ship: ${iW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${iW} requires file(1) and says so, even though this pack already tells it the architecture; or FUSE is unavailable and the tool on PATH is a wrapper that dropped ${aW}=1, which this pack sets so the extract path is taken instead of a mount; or the work directory is full — the AppDir is copied into a squashfs image beside it.`}async function buildAppImage(t){let n=appImageToolArgs(t),S=appImageToolEnv(t.archLabel);t.verbose&&ge.log(`[gjsify ship] ${Object.entries(S).map(([t,n])=>`${t}=${n}`).join(` `)} ${iW} ${n.join(` `)}`);let C=await spawnToCompletion(iW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${iW} is not on PATH. Unlike flatpak-builder and msitools it is not packaged by Fedora or Debian: take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`${iW}\`. \`gjsify ship linux --stage\` needs none of this — the payload is assembled by this CLI and only the container needs the tool.`)});if(C.code!==0)throw Error(appImageToolFailureMessage(describeExit(C),t.runtimeFile));if(!existsSync(t.target))throw Error(`gjsify ship: ${iW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var iW,aW,oW,sW,cW,lW,uW,dW,fW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),hH(),oU(),dU(),vH(),iW=`appimagetool`,aW=`APPIMAGE_EXTRACT_AND_RUN`,oW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,sW=`/usr/local/share/gjsify/appimage-runtime`,cW=`AppDir`,lW=`AppRun`,uW=`.DirIcon`,dW=[`.png`,`.svg`]});function dmgVolumeName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(mW.test(n))throw Error(`gjsify ship: the macOS image would mount a volume called "${n}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return n}function hdiutilCreateArgs(t){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,t.volumeName,`-srcfolder`,t.sourceDir,`-ov`,`-quiet`,t.target]}async function buildDmgImage(t){let n=hdiutilCreateArgs(t);t.verbose&&ge.log(`[gjsify ship] ${pW} ${n.join(` `)}`);let S=await spawnToCompletion(pW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${pW} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(S.code!==0)throw Error(`gjsify ship: ${pW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(hW.target,zn(t,hW.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${gW} ${n.join(` `)}`);let S=await spawnToCompletion(gW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${gW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${gW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var pW,mW,hW,gW,_W=__esmMin(()=>{_e(),af(),Xn(),hv(),pW=`hdiutil`,mW=/[/:]/,hW={name:`Applications`,target:`/Applications`},gW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var vW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var yW=__esmMin(()=>{cv(),af(),o_(),Xn(),$B()});function base64Encode(t){let n=``,S=32768;for(let C=0;C<t.length;C+=S)n+=String.fromCharCode(...t.subarray(C,C+S));return btoa(n)}function base64Decode(t){let n=atob(t),S=new Uint8Array(n.length);for(let t=0;t<n.length;t++)S[t]=n.charCodeAt(t);return S}var bW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,xW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${xW}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify ship: ${n} is not readable JSON (${t.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`gjsify ship: ${n} is not a JSON object. Re-run the \`--stage\` phase.`);let C=S,N=C.schema;if(typeof N!=`number`||!Number.isInteger(N))throw Error(`gjsify ship: ${n} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(N>6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(N<6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=t=>`${n} → ${t}`,F=record(C.tool,at(`tool`)),I=record(C.target,at(`target`)),H={schema:N,tool:{name:expectString(F.name,at(`tool.name`)),version:expectString(F.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(I.os,at(`target.os`)),at(`target.os`)),arch:expectString(I.arch,at(`target.arch`))},formats:expectArray(C.formats,at(`formats`)).map((t,n)=>{let S=expectString(t,at(`formats[${n}]`));if(!JW.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${JW.join(`, `)}.`);return S}),mtime:expectInteger(C.mtime,at(`mtime`)),namespaces:expectArray(C.namespaces,at(`namespaces`)).map((t,n)=>expectString(t,at(`namespaces[${n}]`))),...C.optionalNamespaces===void 0?{}:{optionalNamespaces:expectArray(C.optionalNamespaces,at(`optionalNamespaces`)).map((t,n)=>expectString(t,at(`optionalNamespaces[${n}]`)))},settings:readPackSettings(record(C.settings,at(`settings`)),at(`settings`)),staged:expectArray(C.staged,at(`staged`)).map((t,n)=>{let S=record(t,at(`staged[${n}]`));return{path:expectString(S.path,at(`staged[${n}].path`)),mode:expectInteger(S.mode,at(`staged[${n}].mode`)),bytes:expectInteger(S.bytes,at(`staged[${n}].bytes`))}}),overlay:{}};if(H.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let W=record(C.overlay,at(`overlay`));for(let t of H.formats)H.overlay[t]=expectArray(W[t],at(`overlay.${t}`)).map((n,S)=>{let C=record(n,at(`overlay.${t}[${S}]`)),N=at(`overlay.${t}[${S}]`);if(C.text===void 0==(C.base64===void 0))throw Error(`gjsify ship: ${N} must carry exactly one of \`text\` and \`base64\`. An overlay entry is either rendered text or rendered bytes; an entry with neither would pack an empty file at a path the format requires content at.`);return{path:expectString(C.path,at(`overlay.${t}[${S}].path`)),mode:expectInteger(C.mode,at(`overlay.${t}[${S}].mode`)),...C.text===void 0?{base64:expectString(C.base64,at(`overlay.${t}[${S}].base64`))}:{text:expectString(C.text,at(`overlay.${t}[${S}].text`))}}});return H}function expectLayoutOs(t,n){try{return layoutForOs(t).os}catch{let S=iU.map(t=>rU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var xW,SW=__esmMin(()=>{af(),Xn(),bW(),Ch(),XW(),oU(),xW=`.gjsify-ship-stage.json`});function writeStage(t,n){for(let t of n)if(t.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${xW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var CW=__esmMin(()=>{af(),Xn(),zU(),SW()});function isSnapName(t){return t.length<=AW&&kW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${AW} characters, at least one letter)`),n.version.length>jW&&S.push(`the version "${n.version}" is longer than ${jW} characters`),n.summary.length>MW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${MW}`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${_H.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${OW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${OW}/${snapDesktopPath(n)}`,"common-id":n.appId},C={name:n.binaryName,title:n.name,base:TW,version:n.version,summary:n.summary,description:n.description.join(`
1176
+ `)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${sW}/runtime-${t} (or point ${oW} at a directory holding it).`:`the AppImage runtime is pinned: ${n} — this pack needs no network`}function selectAppDirIcon(t,n){let S;for(let C of t){let t=rootIconRank(C.path,n);t!==void 0&&(S===void 0||t>S.rank)&&(S={entry:C,rank:t})}return S?.entry}function rootIconRank(t,n){if(dW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${_H.icons}/`)||t.includes(`/symbolic/`))return;if(t.includes(`/scalable/`))return 2**53-1;let S=/\/(\d+)x\1\//.exec(t);return S===null?1:Number(S[1])}function assertAppImageIsPackable(t,n,S){let C=`${_H.applications}/${n.appId}.desktop`;if(!t.some(t=>t.path===C))throw Error(`gjsify ship: an AppImage needs a desktop entry and this payload has no ${C}. appimagetool refuses an AppDir without one, and the AppImage runtime has nothing to tell a desktop about the application it just mounted. A \`kind: "cli"\` project stages no entry by design — set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`);if(selectAppDirIcon(t,n.appId)===void 0)throw Error(`gjsify ship: an AppImage needs an icon called ${n.appId} beside its desktop entry, and this payload stages none under ${_H.icons}/. The entry's \`Icon=\` names the app id, so a file keeping its own basename is an icon nothing looks up — point \`gjsify.ship.icon\` at a PNG or an SVG and it is renamed into the theme for you.`);if(S===void 0&&t.some(t=>isSchemaSource(t.path)))throw Error(`gjsify ship: this payload stages GSettings schema sources under ${_H.schemas}/ and no ${uU} was compiled for it. An AppImage has NO INSTALL STEP — that is the whole point of the format — so the \`.deb\`/\`.rpm\` postinst that compiles the system schema directory never runs, and GSettings aborts on a directory holding only sources. The AppDir must carry ${uU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${_H.applications}/${t.appId}.desktop`,I=n.find(t=>t.path===F);return[...[...n,...C===void 0?[]:[C]].map(t=>({...t,path:`usr/${t.path}`})),{path:lW,mode:493,data:encodeUtf8(renderAppRun(t,S))},{path:`${t.appId}.desktop`,mode:420,data:I.data},{path:N.path.slice(N.path.lastIndexOf(`/`)+1),mode:420,data:N.data},{path:uW,mode:420,data:N.data}]}function appImageToolArgs(t){return[`--no-appstream`,`--comp`,`zstd`,...t.runtimeFile===void 0?[]:[`--runtime-file`,t.runtimeFile],t.appDir,t.target]}function appImageToolEnv(t){return{ARCH:t,[aW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${iW} fetches it from github.com/AppImage/type2-runtime when no runtime is pinned, so this pack needs a network and an offline host fails here having written nothing; or `:`the pinned runtime at ${n} is not an AppImage runtime — it is passed through to \`--runtime-file\` unread, so a truncated or wrong-architecture file fails here; or `;return`gjsify ship: ${iW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${iW} requires file(1) and says so, even though this pack already tells it the architecture; or FUSE is unavailable and the tool on PATH is a wrapper that dropped ${aW}=1, which this pack sets so the extract path is taken instead of a mount; or the work directory is full — the AppDir is copied into a squashfs image beside it.`}async function buildAppImage(t){let n=appImageToolArgs(t),S=appImageToolEnv(t.archLabel);t.verbose&&ge.log(`[gjsify ship] ${Object.entries(S).map(([t,n])=>`${t}=${n}`).join(` `)} ${iW} ${n.join(` `)}`);let C=await spawnToCompletion(iW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${iW} is not on PATH. Unlike flatpak-builder and msitools it is not packaged by Fedora or Debian: take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`${iW}\`. \`gjsify ship linux --stage\` needs none of this — the payload is assembled by this CLI and only the container needs the tool.`)});if(C.code!==0)throw Error(appImageToolFailureMessage(describeExit(C),t.runtimeFile));if(!existsSync(t.target))throw Error(`gjsify ship: ${iW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var iW,aW,oW,sW,cW,lW,uW,dW,fW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),hH(),oU(),dU(),vH(),iW=`appimagetool`,aW=`APPIMAGE_EXTRACT_AND_RUN`,oW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,sW=`/usr/local/share/gjsify/appimage-runtime`,cW=`AppDir`,lW=`AppRun`,uW=`.DirIcon`,dW=[`.png`,`.svg`]});function dmgVolumeName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(mW.test(n))throw Error(`gjsify ship: the macOS image would mount a volume called "${n}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return n}function hdiutilCreateArgs(t){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,t.volumeName,`-srcfolder`,t.sourceDir,`-ov`,`-quiet`,t.target]}async function buildDmgImage(t){let n=hdiutilCreateArgs(t);t.verbose&&ge.log(`[gjsify ship] ${pW} ${n.join(` `)}`);let S=await spawnToCompletion(pW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${pW} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(S.code!==0)throw Error(`gjsify ship: ${pW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(hW.target,zn(t,hW.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${gW} ${n.join(` `)}`);let S=await spawnToCompletion(gW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${gW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${gW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var pW,mW,hW,gW,_W=__esmMin(()=>{_e(),af(),Xn(),hv(),pW=`hdiutil`,mW=/[/:]/,hW={name:`Applications`,target:`/Applications`},gW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var vW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function resolveHandMetainfo(t){let n=(t.configReleases?.length??0)>0,S,C;if(t.shipMetainfo!==void 0){if(S=`gjsify.ship.metainfo`,C=t.shipMetainfo,n)throw Error(`gjsify ship: \`gjsify.ship.metainfo\` and \`gjsify.ship.releases\` both describe the releases. The file is staged verbatim, so the config entries would be dropped without a word — keep the \`<releases>\` in ${C} and remove \`releases\` from the config.`)}else if(t.siteMetainfo!==void 0&&!n)S=`gjsify.site.metainfo`,C=t.siteMetainfo;else return;let N=In(t.projectDir,C);if(!existsSync(N))throw Error(`gjsify ship: \`${S}\` points at ${C}, which does not exist (${N}).`);return{path:C,xml:readFileSync(N,`utf-8`),key:S}}function readFacts(t){let n={releaseVersions:[]},S=[],C=``;for(let N of scanXml(t))if(N.kind===`open`){let t=N.name;t===`release`&&N.attributes.version!==void 0&&n.releaseVersions.push(N.attributes.version),t===`launchable`&&N.attributes.type===`desktop-id`&&!N.selfClosing?(S.push(`launchable`),C=``):t===`id`&&S.length===0&&n.id===void 0&&!N.selfClosing&&(S.push(`id`),C=``)}else if(N.kind===`text`)S.length>0&&(C+=N.text);else if(S.length>0){let t=S.pop();t===`id`?n.id=C.trim():t===`launchable`&&(n.launchable=C.trim())}return n}function checkHandMetainfo(t,n){let S=readFacts(t.xml);if(S.id!==n.appId)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <id>${S.id??``}</id>, but the package's application id is "${n.appId}" (\`gjsify.ship.appId\`). Stores resolve the component by the <id> inside the file, so one of the two is wrong.`);if(n.kind===`app`&&S.launchable!==void 0&&S.launchable!==`${n.appId}.desktop`)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <launchable type="desktop-id">${S.launchable}</launchable>, but \`ship\` stages the desktop entry as ${n.appId}.desktop.`);let C=[];return S.releaseVersions.includes(n.version)||C.push(`${t.path} has no <release version="${n.version}"> — the shipped component will not list the version it is packaged as.`),C}var yW=__esmMin(()=>{af(),Xn(),Ye()});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var bW=__esmMin(()=>{cv(),af(),o_(),Xn(),$B()});function base64Encode(t){let n=``,S=32768;for(let C=0;C<t.length;C+=S)n+=String.fromCharCode(...t.subarray(C,C+S));return btoa(n)}function base64Decode(t){let n=atob(t),S=new Uint8Array(n.length);for(let t=0;t<n.length;t++)S[t]=n.charCodeAt(t);return S}var xW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,SW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${SW}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify ship: ${n} is not readable JSON (${t.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`gjsify ship: ${n} is not a JSON object. Re-run the \`--stage\` phase.`);let C=S,N=C.schema;if(typeof N!=`number`||!Number.isInteger(N))throw Error(`gjsify ship: ${n} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(N>6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(N<6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=t=>`${n} → ${t}`,F=record(C.tool,at(`tool`)),I=record(C.target,at(`target`)),H={schema:N,tool:{name:expectString(F.name,at(`tool.name`)),version:expectString(F.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(I.os,at(`target.os`)),at(`target.os`)),arch:expectString(I.arch,at(`target.arch`))},formats:expectArray(C.formats,at(`formats`)).map((t,n)=>{let S=expectString(t,at(`formats[${n}]`));if(!XW.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${XW.join(`, `)}.`);return S}),mtime:expectInteger(C.mtime,at(`mtime`)),namespaces:expectArray(C.namespaces,at(`namespaces`)).map((t,n)=>expectString(t,at(`namespaces[${n}]`))),...C.optionalNamespaces===void 0?{}:{optionalNamespaces:expectArray(C.optionalNamespaces,at(`optionalNamespaces`)).map((t,n)=>expectString(t,at(`optionalNamespaces[${n}]`)))},settings:readPackSettings(record(C.settings,at(`settings`)),at(`settings`)),staged:expectArray(C.staged,at(`staged`)).map((t,n)=>{let S=record(t,at(`staged[${n}]`));return{path:expectString(S.path,at(`staged[${n}].path`)),mode:expectInteger(S.mode,at(`staged[${n}].mode`)),bytes:expectInteger(S.bytes,at(`staged[${n}].bytes`))}}),overlay:{}};if(H.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let W=record(C.overlay,at(`overlay`));for(let t of H.formats)H.overlay[t]=expectArray(W[t],at(`overlay.${t}`)).map((n,S)=>{let C=record(n,at(`overlay.${t}[${S}]`)),N=at(`overlay.${t}[${S}]`);if(C.text===void 0==(C.base64===void 0))throw Error(`gjsify ship: ${N} must carry exactly one of \`text\` and \`base64\`. An overlay entry is either rendered text or rendered bytes; an entry with neither would pack an empty file at a path the format requires content at.`);return{path:expectString(C.path,at(`overlay.${t}[${S}].path`)),mode:expectInteger(C.mode,at(`overlay.${t}[${S}].mode`)),...C.text===void 0?{base64:expectString(C.base64,at(`overlay.${t}[${S}].base64`))}:{text:expectString(C.text,at(`overlay.${t}[${S}].text`))}}});return H}function expectLayoutOs(t,n){try{return layoutForOs(t).os}catch{let S=iU.map(t=>rU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var SW,CW=__esmMin(()=>{af(),Xn(),xW(),Ch(),QW(),oU(),SW=`.gjsify-ship-stage.json`});function writeStage(t,n){for(let t of n)if(t.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${SW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var wW=__esmMin(()=>{af(),Xn(),zU(),CW()});function isSnapName(t){return t.length<=MW&&jW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${MW} characters, at least one letter)`),n.version.length>NW&&S.push(`the version "${n.version}" is longer than ${NW} characters`),n.summary.length>PW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${PW}`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${_H.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${AW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${AW}/${snapDesktopPath(n)}`,"common-id":n.appId,environment:{GI_TYPELIB_PATH:OW}},C={name:n.binaryName,title:n.name,base:EW,version:n.version,summary:n.summary,description:n.description.join(`
1177
1177
 
1178
- `),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:DW}}};return n.homepage!==void 0&&(C.website=n.homepage),C}function renderSnapcraftYaml(t){return`${JSON.stringify(renderSnapcraftManifest(t),null,2)}\n`}function snapcraftArgs(t){let n=[`pack`,`--build-for=${t.archLabel}`,`--output`,t.target];return t.destructive&&n.push(`--destructive-mode`),n}function writeSnapProject(t){assertSnapIsPackable(t.payload,t.settings),rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(zn(t.workDir,`snap`),{recursive:!0}),writePayload(zn(t.workDir,DW),t.payload.map(t=>({...t,path:`${OW}/${t.path}`})),``),writeFileSync(zn(t.workDir,`snap`,`snapcraft.yaml`),encodeUtf8(renderSnapcraftYaml(t)))}async function buildSnap(t){writeSnapProject(t);let n=process.env[EW]===`1`,S=zn(t.workDir,`out.snap`),C=snapcraftArgs({target:S,archLabel:t.archLabel,destructive:n});t.verbose&&ge.log(`[gjsify ship] ${wW} ${C.join(` `)}`);let N=await spawnToCompletion(wW,C,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${wW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(N.code!==0)throw Error(`gjsify ship: ${wW} failed with ${describeExit(N)}.`);if(!existsSync(S))throw Error(`gjsify ship: ${wW} exited 0 but wrote no snap at ${S}.`);renameSync(S,t.target)}var wW,TW,EW,DW,OW,kW,AW,jW,MW,NW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),vH(),CW(),wW=`snapcraft`,TW=`core26`,EW=`GJSIFY_SNAP_DESTRUCTIVE`,DW=`payload`,OW=`usr`,kW=/^(?=.*[a-z])[a-z0-9]+(-[a-z0-9]+)*$/,AW=40,jW=32,MW=78});function lookupArch(t,n,S){let C=t[n];if(!C)throw Error(`gjsify ship: no ${S} architecture is known for \`process.arch\` "${n}". Known: ${Object.keys(t).join(`, `)}.`);return C}function debArch(t,n){return n?`all`:lookupArch(PW,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(FW,t,`RPM`)}function flatpakArch(t,n){return lookupArch(IW,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(LW,t,`AppImage`)}function snapArch(t,n){return lookupArch(RW,t,`Snap`)}function linuxTarArch(t,n){return lookupArch(zW,t,`Linux tarball`)}function macosArch(t,n){return lookupArch(BW,t,`macOS`)}function windowsArch(t,n){return lookupArch(VW,t,`Windows`)}function windowsNameIsUnusable(t){return HW.test(t)||UW.test(t)||/[. ]$/.test(t)?!0:[...t].some(t=>(t.codePointAt(0)??0)<32)}function windowsProgramDirName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(n))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${n}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
1178
+ `),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:kW}}};return n.homepage!==void 0&&(C.website=n.homepage),C}function renderSnapcraftYaml(t){return`${JSON.stringify(renderSnapcraftManifest(t),null,2)}\n`}function snapcraftArgs(t){let n=[`pack`,`--build-for=${t.archLabel}`,`--output`,t.target];return t.destructive&&n.push(`--destructive-mode`),n}function writeSnapProject(t){assertSnapIsPackable(t.payload,t.settings),rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(zn(t.workDir,`snap`),{recursive:!0}),writePayload(zn(t.workDir,kW),t.payload.map(t=>({...t,path:`${AW}/${t.path}`})),``),writeFileSync(zn(t.workDir,`snap`,`snapcraft.yaml`),encodeUtf8(renderSnapcraftYaml(t)))}async function buildSnap(t){writeSnapProject(t);let n=process.env[DW]===`1`,S=zn(t.workDir,`out.snap`),C=snapcraftArgs({target:S,archLabel:t.archLabel,destructive:n});t.verbose&&ge.log(`[gjsify ship] ${TW} ${C.join(` `)}`);let N=await spawnToCompletion(TW,C,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(N.code!==0)throw Error(`gjsify ship: ${TW} failed with ${describeExit(N)}.`);if(!existsSync(S))throw Error(`gjsify ship: ${TW} exited 0 but wrote no snap at ${S}.`);renameSync(S,t.target)}var TW,EW,DW,OW,kW,AW,jW,MW,NW,PW,FW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),vH(),wW(),TW=`snapcraft`,EW=`core26`,DW=`GJSIFY_SNAP_DESTRUCTIVE`,OW=`$SNAP/gnome-platform/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/gjs/girepository-1.0`,kW=`payload`,AW=`usr`,jW=/^(?=.*[a-z])[a-z0-9]+(-[a-z0-9]+)*$/,MW=40,NW=32,PW=78});function lookupArch(t,n,S){let C=t[n];if(!C)throw Error(`gjsify ship: no ${S} architecture is known for \`process.arch\` "${n}". Known: ${Object.keys(t).join(`, `)}.`);return C}function debArch(t,n){return n?`all`:lookupArch(IW,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(LW,t,`RPM`)}function flatpakArch(t,n){return lookupArch(RW,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(zW,t,`AppImage`)}function snapArch(t,n){return lookupArch(BW,t,`Snap`)}function linuxTarArch(t,n){return lookupArch(VW,t,`Linux tarball`)}function macosArch(t,n){return lookupArch(HW,t,`macOS`)}function windowsArch(t,n){return lookupArch(UW,t,`Windows`)}function windowsNameIsUnusable(t){return WW.test(t)||GW.test(t)||/[. ]$/.test(t)?!0:[...t].some(t=>(t.codePointAt(0)??0)<32)}function windowsProgramDirName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(n))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${n}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
1179
1179
  The artifact would assemble here and be unextractable — or extract under a different name than
1180
- the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return JW.filter(n=>qW[n].layoutOs===t&&qW[n].host.finishOn===`any`)}function formatIdsFor(t){return JW.filter(n=>qW[n].layoutOs===t)}function assertHostCanFinish(t,n=process.platform){let{finishOn:S}=t.host;if(!(S===`any`||S.includes(n)))throw Error(`gjsify ship: a ${t.id} artifact is packed on ${S.join(` or `)} and this host is ${n} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${S.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${t.id}\`.`)}function assertToolsInstalled(t,n=isOnPath,S=process.platform){let C=requiredToolsOn(t.host.requiredTools,S),N=C.filter(t=>!n(t));if(N.length===0)return;let F=t.host.installHint;throw Error(`gjsify ship: packing a ${t.id} on ${S} needs ${C.join(` and `)}, and ${N.join(`, `)} ${N.length>1?`are`:`is`} not on PATH. ${F===void 0?`Install it`:`Install it (${F})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${N.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(t,n){let S=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t.length>0),C=S.filter(t=>!Object.hasOwn(qW,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${JW.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${JW.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>qW[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>qW[t].layoutOs))];throw Error(`gjsify ship: ${C.join(`, `)} ${C.length>1?`wrap`:`wraps`} the ${S.join(`/`)} layout and this run assembles the ${n.name} one. `+(t.length===0?`No format wraps the ${n.name} layout — \`gjsify ship ${n.name} --stage\` assembles it and stops.`:`Formats for this layout: ${t.join(`, `)}.`)+` To build ${C.join(`, `)}, name the layout each wraps: ${S.map(t=>`\`gjsify ship ${YW[t]??t} --target ${C.filter(n=>qW[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>qW[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>qW[t].layoutOs===n.os).map(t=>qW[t]),dropped:S.filter(t=>qW[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var PW,FW,IW,LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,SHARE_LICENSE_DEST,WRITTEN_HERE,qW,JW,YW,XW=__esmMin(()=>{dL(),fW(),NW(),_W(),oU(),dU(),PW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},FW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},IW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},LW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},RW={x64:`amd64`,arm64:`arm64`},zW={x64:`x86_64`,arm64:`aarch64`},BW={x64:`x86_64`,arm64:`arm64`},VW={x64:`x64`,arm64:`arm64`},HW=/[<>:"/\\|?*]/,UW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,WW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,GW='a `.app` a stranger downloads has to CARRY its interpreter, and there is no relocatable GJS to put in one — `packages/node-gi/scripts/build-gtk-runtime-darwin.mjs` records "GJS ships no relocation", which is why ADR 0024 § 4 derives Node on macOS and stage 7 is what would change it',KW="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=t=>`share/licenses/${t}/LICENSE`,WRITTEN_HERE=t=>({finishOn:`any`,requiredTools:[],oracle:{readWith:t,readOn:[`linux`],selfReading:!1}}),qW={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:WW,licenseDest:t=>`share/doc/${t}/copyright`,licenseKind:`debian-copyright`,changelogDest:t=>`share/doc/${t}/changelog.Debian.gz`,archName:debArch,fileName:(t,n)=>`${t.binaryName}_${t.version}-${t.release}_${n}.deb`,artifactKind:`file`},rpm:{id:`rpm`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`rpm`,`rpm2cpio`,`cpio`]),depends:`rpm`,interpreters:[`gjs`,`node`],interpreterGap:WW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:rpmArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.rpm`,artifactKind:`file`},flatpak:{id:`flatpak`,layoutOs:`linux`,prefix:`/app`,host:{finishOn:[`linux`],requiredTools:[`flatpak-builder`,`flatpak`],installHint:"Fedora: `sudo dnf install flatpak flatpak-builder`, Debian/Ubuntu: `sudo apt install flatpak flatpak-builder`",oracle:{readWith:[`flatpak`,`ostree`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a Flatpak runs against `org.gnome.Platform`, which ships `gjs` and no `node`. Node exists only as `org.freedesktop.Sdk.Extension.node2x`, and that extension puts node on the BUILD path, not in the runtime — so the artifact would install and then fail at `exec node`",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:flatpakArch,fileName:(t,n)=>`${t.appId}-${t.version}-${t.release}.${n}.flatpak`,artifactKind:`file`},appimage:{id:`appimage`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[iW,cU],installHint:`no distribution packages appimagetool — take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`appimagetool\`; or assemble here with \`gjsify ship linux --stage\` and pack where it is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[wW,cU],installHint:`\`sudo snap install ${wW} --classic\` (snapcraft is a snap; ${TW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[cU],installHint:`The schema compiler is packaged: ${lU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:GW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:t=>`${t.name}.app`,artifactKind:`directory`},"macos-app-zip":{id:`macos-app-zip`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:GW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.macos.${n}.zip`,artifactKind:`file`},"macos-app-dmg":{id:`macos-app-dmg`,layoutOs:`darwin`,prefix:``,host:{finishOn:[`darwin`],requiredTools:[pW],installHint:"`hdiutil` is part of macOS and cannot be installed elsewhere — on a Mac it is /usr/bin/hdiutil, so an absent one means a broken installation rather than a missing package",oracle:{readWith:[`7z`,`dmg2img`,`fsck.hfsplus`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:GW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.dmg`,artifactKind:`file`},"windows-dir":{id:`windows-dir`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:KW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:t=>windowsProgramDirName(t),artifactKind:`directory`},"windows-dir-zip":{id:`windows-dir-zip`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:KW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.windows.${n}.zip`,artifactKind:`file`},msi:{id:`msi`,layoutOs:`win32`,prefix:``,host:{finishOn:[`linux`,`win32`],requiredTools:{linux:[cU,`wixl`],win32:[cU,`candle.exe`,`light.exe`]},installHint:`${lU}; the MSI compiler is Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 (https://github.com/wixtoolset/wix3/releases) with its \`bin\` directory on PATH`,oracle:{readWith:[`msiexec`,`msiinfo`],readOn:[`win32`,`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:KW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},JW=Object.keys(qW),YW=Object.fromEntries(iU.map(t=>[rU[t].os,t]))});function uuid5(t,n){let S=t.replace(/-/g,``),C=new Uint8Array(16);for(let t=0;t<16;t+=1)C[t]=Number.parseInt(S.slice(t*2,t*2+2),16);let N=createHash(`sha1`).update(C).update(new TextEncoder().encode(n)).digest(),F=Uint8Array.from(N.subarray(0,16));F[6]=(F[6]??0)&15|80,F[8]=(F[8]??0)&63|128;let I=[...F].map(t=>t.toString(16).padStart(2,`0`)).join(``);return[I.slice(0,8),I.slice(8,12),I.slice(12,16),I.slice(16,20),I.slice(20)].join(`-`)}function msiUpgradeCode(t){return uuid5(ZW,`upgrade\n${t.appId}`).toUpperCase()}function msiProductCode(t,n){let S=`product\n${t.appId}\n${t.version}\n${t.release}\n${n}`;return uuid5(ZW,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(ZW,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
1180
+ the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return XW.filter(n=>YW[n].layoutOs===t&&YW[n].host.finishOn===`any`)}function formatIdsFor(t){return XW.filter(n=>YW[n].layoutOs===t)}function assertHostCanFinish(t,n=process.platform){let{finishOn:S}=t.host;if(!(S===`any`||S.includes(n)))throw Error(`gjsify ship: a ${t.id} artifact is packed on ${S.join(` or `)} and this host is ${n} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${S.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${t.id}\`.`)}function assertToolsInstalled(t,n=isOnPath,S=process.platform){let C=requiredToolsOn(t.host.requiredTools,S),N=C.filter(t=>!n(t));if(N.length===0)return;let F=t.host.installHint;throw Error(`gjsify ship: packing a ${t.id} on ${S} needs ${C.join(` and `)}, and ${N.join(`, `)} ${N.length>1?`are`:`is`} not on PATH. ${F===void 0?`Install it`:`Install it (${F})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${N.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(t,n){let S=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t.length>0),C=S.filter(t=>!Object.hasOwn(YW,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${XW.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${XW.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>YW[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>YW[t].layoutOs))];throw Error(`gjsify ship: ${C.join(`, `)} ${C.length>1?`wrap`:`wraps`} the ${S.join(`/`)} layout and this run assembles the ${n.name} one. `+(t.length===0?`No format wraps the ${n.name} layout — \`gjsify ship ${n.name} --stage\` assembles it and stops.`:`Formats for this layout: ${t.join(`, `)}.`)+` To build ${C.join(`, `)}, name the layout each wraps: ${S.map(t=>`\`gjsify ship ${ZW[t]??t} --target ${C.filter(n=>YW[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>YW[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>YW[t].layoutOs===n.os).map(t=>YW[t]),dropped:S.filter(t=>YW[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var IW,LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,SHARE_LICENSE_DEST,WRITTEN_HERE,YW,XW,ZW,QW=__esmMin(()=>{dL(),fW(),FW(),_W(),oU(),dU(),IW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},LW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},RW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},zW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},BW={x64:`amd64`,arm64:`arm64`},VW={x64:`x86_64`,arm64:`aarch64`},HW={x64:`x86_64`,arm64:`arm64`},UW={x64:`x64`,arm64:`arm64`},WW=/[<>:"/\\|?*]/,GW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,KW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,qW='a `.app` a stranger downloads has to CARRY its interpreter, and there is no relocatable GJS to put in one — `packages/node-gi/scripts/build-gtk-runtime-darwin.mjs` records "GJS ships no relocation", which is why ADR 0024 § 4 derives Node on macOS and stage 7 is what would change it',JW="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=t=>`share/licenses/${t}/LICENSE`,WRITTEN_HERE=t=>({finishOn:`any`,requiredTools:[],oracle:{readWith:t,readOn:[`linux`],selfReading:!1}}),YW={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:KW,licenseDest:t=>`share/doc/${t}/copyright`,licenseKind:`debian-copyright`,changelogDest:t=>`share/doc/${t}/changelog.Debian.gz`,archName:debArch,fileName:(t,n)=>`${t.binaryName}_${t.version}-${t.release}_${n}.deb`,artifactKind:`file`},rpm:{id:`rpm`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`rpm`,`rpm2cpio`,`cpio`]),depends:`rpm`,interpreters:[`gjs`,`node`],interpreterGap:KW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:rpmArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.rpm`,artifactKind:`file`},flatpak:{id:`flatpak`,layoutOs:`linux`,prefix:`/app`,host:{finishOn:[`linux`],requiredTools:[`flatpak-builder`,`flatpak`],installHint:"Fedora: `sudo dnf install flatpak flatpak-builder`, Debian/Ubuntu: `sudo apt install flatpak flatpak-builder`",oracle:{readWith:[`flatpak`,`ostree`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a Flatpak runs against `org.gnome.Platform`, which ships `gjs` and no `node`. Node exists only as `org.freedesktop.Sdk.Extension.node2x`, and that extension puts node on the BUILD path, not in the runtime — so the artifact would install and then fail at `exec node`",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:flatpakArch,fileName:(t,n)=>`${t.appId}-${t.version}-${t.release}.${n}.flatpak`,artifactKind:`file`},appimage:{id:`appimage`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[iW,cU],installHint:`no distribution packages appimagetool — take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`appimagetool\`; or assemble here with \`gjsify ship linux --stage\` and pack where it is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[TW,cU],installHint:`\`sudo snap install ${TW} --classic\` (snapcraft is a snap; ${EW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[cU],installHint:`The schema compiler is packaged: ${lU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:t=>`${t.name}.app`,artifactKind:`directory`},"macos-app-zip":{id:`macos-app-zip`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.macos.${n}.zip`,artifactKind:`file`},"macos-app-dmg":{id:`macos-app-dmg`,layoutOs:`darwin`,prefix:``,host:{finishOn:[`darwin`],requiredTools:[pW],installHint:"`hdiutil` is part of macOS and cannot be installed elsewhere — on a Mac it is /usr/bin/hdiutil, so an absent one means a broken installation rather than a missing package",oracle:{readWith:[`7z`,`dmg2img`,`fsck.hfsplus`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.dmg`,artifactKind:`file`},"windows-dir":{id:`windows-dir`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:t=>windowsProgramDirName(t),artifactKind:`directory`},"windows-dir-zip":{id:`windows-dir-zip`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.windows.${n}.zip`,artifactKind:`file`},msi:{id:`msi`,layoutOs:`win32`,prefix:``,host:{finishOn:[`linux`,`win32`],requiredTools:{linux:[cU,`wixl`],win32:[cU,`candle.exe`,`light.exe`]},installHint:`${lU}; the MSI compiler is Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 (https://github.com/wixtoolset/wix3/releases) with its \`bin\` directory on PATH`,oracle:{readWith:[`msiexec`,`msiinfo`],readOn:[`win32`,`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},XW=Object.keys(YW),ZW=Object.fromEntries(iU.map(t=>[rU[t].os,t]))});function uuid5(t,n){let S=t.replace(/-/g,``),C=new Uint8Array(16);for(let t=0;t<16;t+=1)C[t]=Number.parseInt(S.slice(t*2,t*2+2),16);let N=createHash(`sha1`).update(C).update(new TextEncoder().encode(n)).digest(),F=Uint8Array.from(N.subarray(0,16));F[6]=(F[6]??0)&15|80,F[8]=(F[8]??0)&63|128;let I=[...F].map(t=>t.toString(16).padStart(2,`0`)).join(``);return[I.slice(0,8),I.slice(8,12),I.slice(12,16),I.slice(16,20),I.slice(20)].join(`-`)}function msiUpgradeCode(t){return uuid5($W,`upgrade\n${t.appId}`).toUpperCase()}function msiProductCode(t,n){let S=`product\n${t.appId}\n${t.version}\n${t.release}\n${n}`;return uuid5($W,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5($W,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
1181
1181
  Dropping the suffix is not an option this command will take silently: \`1.2.0~rc.1\` and \`1.2.0\` would
1182
1182
  become the same version, \`MajorUpgrade\` could not tell them apart, and installing one over the other
1183
1183
  would leave both on the machine. Set \`gjsify.ship.version\` to a plain \`x.y.z\`, or drop \`msi\` from the targets.`);let[S,C,N]=[Number(n[1]),Number(n[2]),Number(n[3]??`0`)];if(S>255||C>255||N>65535)throw Error(`gjsify ship: version "${t}" is outside what Windows Installer compares — \`major\` and \`minor\` are at most 255 and \`build\` at most 65535. A field over the limit is not rejected by the installer, it is
1184
- TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||QW.test(t))throw Error(`gjsify ship: the payload holds "${n}", and Windows Installer cannot address the path segment "${t}". A \`FileName\` or \`DefaultDir\` cell reserves < > : " / \\ | ? * and ; (its own list separator), and
1184
+ TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||eG.test(t))throw Error(`gjsify ship: the payload holds "${n}", and Windows Installer cannot address the path segment "${t}". A \`FileName\` or \`DefaultDir\` cell reserves < > : " / \\ | ? * and ; (its own list separator), and
1185
1185
  \`.\` and \`..\` are not names. The \`.msi\` would build and install the file somewhere else, or not at all.`);if(t.length>255)throw Error(`gjsify ship: the payload holds "${n}", whose segment "${t.slice(0,40)}…" is ${t.length} characters. Windows Installer's \`FileName\` column is 255.`)}function directoryTree(t){let n={path:``,name:``,children:new Map,files:[]};for(let S of[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))){let t=S.path.split(`/`),C=t.pop();if(C===void 0)throw Error(`gjsify ship: the payload holds an empty path.`);let N=n;for(let n of t){assertNameIsAddressable(n,S.path);let t=N.children.get(n)??{path:N.path===``?n:`${N.path}/${n}`,name:n,children:new Map,files:[]};N.children.set(n,t),N=t}assertNameIsAddressable(C,S.path),N.files.push(S)}return n}function renderWxs(t){let{settings:n,programDirName:S,archLabel:C}=t,N=C!==`x86`,F=C===`arm64`?500:200,I=msiProductVersion(n.version),H=n.maintainer.replace(/\s*<[^>]*>\s*$/,``).trim()||n.maintainer,W=windowsGuiLauncherPath(n),q=new Map,claim=(t,n)=>{let S=q.get(t);if(S!==void 0)throw Error(`gjsify ship: the MSI identifier "${t}" would be shared by ${S} and ${n}. Two rows cannot carry one id — one would silently replace the other.`);return q.set(t,n),t},Y=claim(msiIdentifier(`i`,W,`.exe`),`the launcher icon`),X=[],Z=[],te=!1,ne,emitDir=(t,S)=>{for(let C of t.files){let t=claim(msiIdentifier(`c`,C.path),C.path),F=claim(msiIdentifier(`f`,C.path),C.path);Z.push(t);let I=msiComponentGuid(n,C.path),H=xmlEscape(On.basename(C.path));X.push(`${S}<Component Id="${t}" Guid="${I}" Win64="${N?`yes`:`no`}">`),C.path===W?(te=!0,ne=C.source,X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes">`),X.push(`${S} <Shortcut Id="${claim(`s_startmenu`,`the Start-Menu shortcut`)}" Directory="ProgramMenuFolder" Name="${xmlEscape(n.name)}" WorkingDirectory="INSTALLDIR" Description="${xmlEscape(n.summary)}" Icon="${Y}" IconIndex="0" Advertise="yes" />`),X.push(`${S} </File>`)):X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes" />`),X.push(`${S}</Component>`)}for(let n of[...t.children.values()].sort((t,n)=>t.name<n.name?-1:1)){let t=claim(msiIdentifier(`d`,n.path),`the directory ${n.path}`);X.push(`${S}<Directory Id="${t}" Name="${xmlEscape(n.name)}">`),emitDir(n,`${S} `),X.push(`${S}</Directory>`)}};if(emitDir(directoryTree(t.files),` `),Z.length===0)throw Error("gjsify ship: the windows payload is empty, so there is nothing for an `.msi` to install.");if(!te||ne===void 0)throw Error(`gjsify ship: the windows payload carries no "${W}" at the root of the program directory, so the installer would have nothing to point a Start-Menu shortcut at — an application a user installs and
1186
1186
  cannot start. \`windows-dir\` puts the launcher there; a payload without one is a stage assembled for another layout.`);let re=n.homepage===void 0?[]:[` <Property Id="ARPURLINFOABOUT" Value="${xmlEscape(n.homepage)}" />`];return[`<?xml version="1.0" encoding="utf-8"?>`,"<!-- Generated by `gjsify ship` (ADR 0024 stage 5). Do not edit; edit utils/ship/msi.ts. -->",`<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">`,` <Product Id="${msiProductCode(n,C)}" Name="${xmlEscape(n.name)}" Language="1033" Version="${I}" Manufacturer="${xmlEscape(H)}" UpgradeCode="${msiUpgradeCode(n)}">`,` <Package InstallerVersion="${F}" Compressed="yes" InstallScope="perMachine" Manufacturer="${xmlEscape(H)}" Description="${xmlEscape(n.summary)}" />`,` <MajorUpgrade DowngradeErrorMessage="A newer version of ${xmlEscape(n.name)} is already installed." />`,` <Media Id="1" Cabinet="app.cab" EmbedCab="yes" />`,` <Icon Id="${Y}" SourceFile="${xmlEscape(ne)}" />`,` <Property Id="ARPPRODUCTICON" Value="${Y}" />`,...re,` <Directory Id="TARGETDIR" Name="SourceDir">`,` <Directory Id="ProgramFiles64Folder">`,` <Directory Id="INSTALLDIR" Name="${xmlEscape(S)}">`,...X,` <Component Id="AddToPathComponent" Guid="${msiComponentGuid(n,`:path`)}" Win64="${N?`yes`:`no`}">`,` <CreateFolder />`,` <Environment Id="GjsifyPath" Name="PATH" Action="set" Part="last" System="yes" Permanent="no" Value="[INSTALLDIR]" />`,` </Component>`,` </Directory>`,` </Directory>`,` <Directory Id="ProgramMenuFolder" />`,` </Directory>`,` <Feature Id="Main" Title="${xmlEscape(n.name)}" Level="1">`,...Z.map(t=>` <ComponentRef Id="${t}" />`),` </Feature>`,` <Feature Id="AddToPath" Title="Add ${xmlEscape(n.name)} to PATH" Level="2">`,` <ComponentRef Id="AddToPathComponent" />`,` <Condition Level="1">ADDTOPATH=1</Condition>`,` </Feature>`,` </Product>`,`</Wix>`,``].join(`
1187
- `)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var ZW,QW,$W,eG=__esmMin(()=>{_e(),gl(),af(),Xn(),hv(),oU(),CU(),ZW=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,QW=/[<>:"/\\|?*;]/,$W=`root`});function tarballTopDir(t,n){return`${t.binaryName}-${t.version}-linux-${n}`}function inDeclaredClosure(t,n){return n.some(n=>t.startsWith(`${n}/`)?!t.slice(n.length+1).split(`/`).includes(`node_modules`):!1)}function assertTarballHygiene(t,n){let S=[];for(let C of t){let t=C.path.split(`/`),N=t[t.length-1];N===`.env`||N.startsWith(`.env.`)?S.push(`${C.path} (environment file)`):t.includes(`.git`)?S.push(`${C.path} (version-control data)`):N.endsWith(`.log`)?S.push(`${C.path} (log file)`):t.includes(`node_modules`)&&n.app!==`node`&&!inDeclaredClosure(C.path,n.nodeModulesDirs??[])&&S.push(`${C.path} (node_modules in a non-Node payload)`)}if(S.length!==0)throw Error(`gjsify ship: refusing to pack a tarball that would contain ${S.slice(0,5).join(`, `)}${S.length>5?` and ${S.length-5} more`:``}.`)}async function buildLinuxTarball(t){assertTarballHygiene(t.payload,t.settings);let n=tarballTopDir(t.settings,t.archLabel),S=new Set([`${n}/`]);for(let C of t.payload){let t=On.dirname(C.path),N=t===`.`?[]:t.split(`/`),F=n;for(let t of N)F=`${F}/${t}`,S.add(`${F}/`)}return gzipDeterministic(createTarball([...[...S].sort().map(n=>({name:n,mode:493,mtime:t.mtime,directory:!0})),...t.payload.map(S=>({name:`${n}/${S.path}`,body:S.data,mode:S.mode,mtime:t.mtime}))]))}var tG=__esmMin(()=>{Xn(),oz(),gH()});function getCrcTable(){if(cG!==null)return cG;let t=new Uint32Array(256);for(let n=0;n<256;n++){let S=n;for(let t=0;t<8;t++)S=S&1?3988292384^S>>>1:S>>>1;t[n]=S>>>0}return cG=t,t}function crc32(t){let n=getCrcTable(),S=4294967295;for(let C=0;C<t.length;C++)S=n[(S^t[C])&255]^S>>>8;return(S^4294967295)>>>0}function dosDateTime(t){let n=new Date(Math.max(t,315532800)*1e3);return{date:(n.getUTCFullYear()-1980&127)<<9|n.getUTCMonth()+1<<5|n.getUTCDate(),time:n.getUTCHours()<<11|n.getUTCMinutes()<<5|Math.floor(n.getUTCSeconds()/2)}}function buildZip(t,n){let S=[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path)),{date:C,time:N}=dosDateTime(n),F=new TextEncoder;if(S.length>65535)throw Error(`gjsify ship: this archive would hold ${S.length} entries and a non-ZIP64 central directory records the count in 16 bits, so it would silently wrap. Nothing here writes ZIP64 yet; the payload has to shrink, or this writer has to grow the ZIP64 records.`);let I=new Writer,H=new Writer,W=0;for(let t of S){let n=F.encode(t.path),S=crc32(t.data),q=t.data.byteLength,Y=I.offset;if(Y>4294967295||q>4294967295)throw Error(`gjsify ship: ${t.path} would push this archive past 4 GiB, which a non-ZIP64 header records in 32 bits and therefore truncates. Nothing here writes ZIP64 yet.`);I.u32(nG),I.u16(sG),I.u16(2048),I.u16(aG),I.u16(N),I.u16(C),I.u32(S),I.u32(q),I.u32(q),I.u16(n.byteLength),I.u16(0),I.bytes(n),I.bytes(t.data),H.u32(rG),H.u16(oG),H.u16(sG),H.u16(2048),H.u16(aG),H.u16(N),H.u16(C),H.u32(S),H.u32(q),H.u32(q),H.u16(n.byteLength),H.u16(0),H.u16(0),H.u16(0),H.u16(0),H.u32(((32768|t.mode&4095)>>>0)*65536),H.u32(Y),H.bytes(n),W+=1}let q=H.finish(),Y=new Writer;Y.bytes(I.finish());let X=Y.offset;return Y.bytes(q),Y.u32(iG),Y.u16(0),Y.u16(0),Y.u16(W),Y.u16(W),Y.u32(q.byteLength),Y.u32(X),Y.u16(0),Y.finish()}function zipEntriesFromPayload(t,n=``){let S=n===``?``:`${n}/`;return t.map(t=>({path:`${S}${t.path}`,mode:t.mode,data:t.data}))}var nG,rG,iG,aG,oG,sG,cG,Writer,lG=__esmMin(()=>{nG=67324752,rG=33639248,iG=101010256,aG=0,oG=788,sG=20,cG=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(t){this.push(new Uint8Array([t&255,t>>>8&255]))}u32(t){this.push(new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255]))}bytes(t){this.push(t)}push(t){this.parts.push(t),this.length+=t.byteLength}finish(){let t=new Uint8Array(this.length),n=0;for(let S of this.parts)t.set(S,n),n+=S.byteLength;return t}}});function entryEvidence(t){let n=new Set,S=new Set;return walkModuleAst(t,t=>{let C=importedSpecifier(t);C!==null&&(C.startsWith(`gi://`)||uG.has(C)?n.add(C):C.startsWith(`node:`)&&t.type!==`ImportExpression`&&S.add(C))}),{gi:[...n].sort(),node:[...S].sort()}}function assertEntryRunsUnder(t){let n=entryEvidence(t.source),S=t.interpreter===`node`?n.gi:n.node;if(S.length===0)return;let C=t.interpreter===`node`?`gjs`:`node`,N=t.interpreter===`gjs`?`GJS's loader refuses it: ImportError, "Unsupported URI scheme for importing: node"`:S.some(t=>t.startsWith(`gi://`))?`node's ESM loader refuses it: ERR_UNSUPPORTED_ESM_URL_SCHEME, "Only URLs with a scheme in: file, data, and node are supported by the default ESM loader"`:`node's ESM loader refuses it: ERR_MODULE_NOT_FOUND — a GJS built-in is not a package`,F=S.slice(0,3).join(`, `),I=S.length>3?`, and ${S.length-3} more`:``;throw Error(`gjsify ship: this target execs \`${t.interpreter}\` (\`${t.appKey}\`), and the entry it would ship — ${t.entry} (\`${t.bundleKey}\`) — imports ${F}${I}.\n ${N}, before a line of application code runs.\n The artifact would be built, reported as built, and fail at launch on every machine.
1188
- Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var uG,dG=__esmMin(()=>{fP(),uG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${fG}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var fG,pG=__esmMin(()=>{gl(),af(),Xn(),fG=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=mG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=hG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${t.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(t.flag===void 0||t.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${n.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(t.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:t.flag,notary:n}}async function notarizeArtifact(t){let{notary:n,credential:S}=t.plan,C=process.platform;if(!n.notarizeOn.includes(C))throw Error(`gjsify ship: notarising the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.notarizeOn.join(`, `)} and this host is ${C}.`);let N=n.args(S,t.artifact);t.verbose&&t.log(`${n.tool} ${N.join(` `)}`);let F=await spawnToCompletion(n.tool,N,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.tool}\` is not on PATH — ${n.installHint}.`)});if(F.code!==0)throw Error(`gjsify ship: ${n.tool} notarytool failed with ${describeExit(F)}.`);t.log(`${n.tool} notarytool accepted ${t.artifact}.`)}async function stapleArtifact(t){let n=[`stapler`,`staple`,t.artifact];t.verbose&&t.log(`${t.notary.tool} ${n.join(` `)}`);let S=await spawnToCompletion(t.notary.tool,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${t.notary.tool}\` is not on PATH — ${t.notary.installHint}.`)});if(S.code!==0)throw Error(`gjsify ship: ${t.notary.tool} stapler failed with ${describeExit(S)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);t.log(`${t.notary.tool} stapler attached the ticket to ${t.artifact}.`)}var mG,hG,gG=__esmMin(()=>{af(),Xn(),dL(),hv(),zU(),xU(),eU(),CW(),mG={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},hG={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(_H.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
1187
+ `)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var $W,eG,tG,nG=__esmMin(()=>{_e(),gl(),af(),Xn(),hv(),oU(),CU(),$W=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,eG=/[<>:"/\\|?*;]/,tG=`root`});function tarballTopDir(t,n){return`${t.binaryName}-${t.version}-linux-${n}`}function inDeclaredClosure(t,n){return n.some(n=>t.startsWith(`${n}/`)?!t.slice(n.length+1).split(`/`).includes(`node_modules`):!1)}function assertTarballHygiene(t,n){let S=[];for(let C of t){let t=C.path.split(`/`),N=t[t.length-1];N===`.env`||N.startsWith(`.env.`)?S.push(`${C.path} (environment file)`):t.includes(`.git`)?S.push(`${C.path} (version-control data)`):N.endsWith(`.log`)?S.push(`${C.path} (log file)`):t.includes(`node_modules`)&&n.app!==`node`&&!inDeclaredClosure(C.path,n.nodeModulesDirs??[])&&S.push(`${C.path} (node_modules in a non-Node payload)`)}if(S.length!==0)throw Error(`gjsify ship: refusing to pack a tarball that would contain ${S.slice(0,5).join(`, `)}${S.length>5?` and ${S.length-5} more`:``}.`)}async function buildLinuxTarball(t){assertTarballHygiene(t.payload,t.settings);let n=tarballTopDir(t.settings,t.archLabel),S=new Set([`${n}/`]);for(let C of t.payload){let t=On.dirname(C.path),N=t===`.`?[]:t.split(`/`),F=n;for(let t of N)F=`${F}/${t}`,S.add(`${F}/`)}return gzipDeterministic(createTarball([...[...S].sort().map(n=>({name:n,mode:493,mtime:t.mtime,directory:!0})),...t.payload.map(S=>({name:`${n}/${S.path}`,body:S.data,mode:S.mode,mtime:t.mtime}))]))}var rG=__esmMin(()=>{Xn(),oz(),gH()});function getCrcTable(){if(uG!==null)return uG;let t=new Uint32Array(256);for(let n=0;n<256;n++){let S=n;for(let t=0;t<8;t++)S=S&1?3988292384^S>>>1:S>>>1;t[n]=S>>>0}return uG=t,t}function crc32(t){let n=getCrcTable(),S=4294967295;for(let C=0;C<t.length;C++)S=n[(S^t[C])&255]^S>>>8;return(S^4294967295)>>>0}function dosDateTime(t){let n=new Date(Math.max(t,315532800)*1e3);return{date:(n.getUTCFullYear()-1980&127)<<9|n.getUTCMonth()+1<<5|n.getUTCDate(),time:n.getUTCHours()<<11|n.getUTCMinutes()<<5|Math.floor(n.getUTCSeconds()/2)}}function buildZip(t,n){let S=[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path)),{date:C,time:N}=dosDateTime(n),F=new TextEncoder;if(S.length>65535)throw Error(`gjsify ship: this archive would hold ${S.length} entries and a non-ZIP64 central directory records the count in 16 bits, so it would silently wrap. Nothing here writes ZIP64 yet; the payload has to shrink, or this writer has to grow the ZIP64 records.`);let I=new Writer,H=new Writer,W=0;for(let t of S){let n=F.encode(t.path),S=crc32(t.data),q=t.data.byteLength,Y=I.offset;if(Y>4294967295||q>4294967295)throw Error(`gjsify ship: ${t.path} would push this archive past 4 GiB, which a non-ZIP64 header records in 32 bits and therefore truncates. Nothing here writes ZIP64 yet.`);I.u32(iG),I.u16(lG),I.u16(2048),I.u16(sG),I.u16(N),I.u16(C),I.u32(S),I.u32(q),I.u32(q),I.u16(n.byteLength),I.u16(0),I.bytes(n),I.bytes(t.data),H.u32(aG),H.u16(cG),H.u16(lG),H.u16(2048),H.u16(sG),H.u16(N),H.u16(C),H.u32(S),H.u32(q),H.u32(q),H.u16(n.byteLength),H.u16(0),H.u16(0),H.u16(0),H.u16(0),H.u32(((32768|t.mode&4095)>>>0)*65536),H.u32(Y),H.bytes(n),W+=1}let q=H.finish(),Y=new Writer;Y.bytes(I.finish());let X=Y.offset;return Y.bytes(q),Y.u32(oG),Y.u16(0),Y.u16(0),Y.u16(W),Y.u16(W),Y.u32(q.byteLength),Y.u32(X),Y.u16(0),Y.finish()}function zipEntriesFromPayload(t,n=``){let S=n===``?``:`${n}/`;return t.map(t=>({path:`${S}${t.path}`,mode:t.mode,data:t.data}))}var iG,aG,oG,sG,cG,lG,uG,Writer,dG=__esmMin(()=>{iG=67324752,aG=33639248,oG=101010256,sG=0,cG=788,lG=20,uG=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(t){this.push(new Uint8Array([t&255,t>>>8&255]))}u32(t){this.push(new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255]))}bytes(t){this.push(t)}push(t){this.parts.push(t),this.length+=t.byteLength}finish(){let t=new Uint8Array(this.length),n=0;for(let S of this.parts)t.set(S,n),n+=S.byteLength;return t}}});function entryEvidence(t){let n=new Set,S=new Set;return walkModuleAst(t,t=>{let C=importedSpecifier(t);C!==null&&(C.startsWith(`gi://`)||fG.has(C)?n.add(C):C.startsWith(`node:`)&&t.type!==`ImportExpression`&&S.add(C))}),{gi:[...n].sort(),node:[...S].sort()}}function assertEntryRunsUnder(t){let n=entryEvidence(t.source),S=t.interpreter===`node`?n.gi:n.node;if(S.length===0)return;let C=t.interpreter===`node`?`gjs`:`node`,N=t.interpreter===`gjs`?`GJS's loader refuses it: ImportError, "Unsupported URI scheme for importing: node"`:S.some(t=>t.startsWith(`gi://`))?`node's ESM loader refuses it: ERR_UNSUPPORTED_ESM_URL_SCHEME, "Only URLs with a scheme in: file, data, and node are supported by the default ESM loader"`:`node's ESM loader refuses it: ERR_MODULE_NOT_FOUND — a GJS built-in is not a package`,F=S.slice(0,3).join(`, `),I=S.length>3?`, and ${S.length-3} more`:``;throw Error(`gjsify ship: this target execs \`${t.interpreter}\` (\`${t.appKey}\`), and the entry it would ship — ${t.entry} (\`${t.bundleKey}\`) — imports ${F}${I}.\n ${N}, before a line of application code runs.\n The artifact would be built, reported as built, and fail at launch on every machine.
1188
+ Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var fG,pG=__esmMin(()=>{fP(),fG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${mG}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var mG,hG=__esmMin(()=>{gl(),af(),Xn(),mG=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=gG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=_G[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${t.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(t.flag===void 0||t.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${n.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(t.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:t.flag,notary:n}}async function notarizeArtifact(t){let{notary:n,credential:S}=t.plan,C=process.platform;if(!n.notarizeOn.includes(C))throw Error(`gjsify ship: notarising the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.notarizeOn.join(`, `)} and this host is ${C}.`);let N=n.args(S,t.artifact);t.verbose&&t.log(`${n.tool} ${N.join(` `)}`);let F=await spawnToCompletion(n.tool,N,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.tool}\` is not on PATH — ${n.installHint}.`)});if(F.code!==0)throw Error(`gjsify ship: ${n.tool} notarytool failed with ${describeExit(F)}.`);t.log(`${n.tool} notarytool accepted ${t.artifact}.`)}async function stapleArtifact(t){let n=[`stapler`,`staple`,t.artifact];t.verbose&&t.log(`${t.notary.tool} ${n.join(` `)}`);let S=await spawnToCompletion(t.notary.tool,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${t.notary.tool}\` is not on PATH — ${t.notary.installHint}.`)});if(S.code!==0)throw Error(`gjsify ship: ${t.notary.tool} stapler failed with ${describeExit(S)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);t.log(`${t.notary.tool} stapler attached the ticket to ${t.artifact}.`)}var gG,_G,vG=__esmMin(()=>{af(),Xn(),dL(),hv(),zU(),xU(),eU(),wW(),gG={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},_G={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(_H.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
1189
1189
  `)}function renderAppBundleLauncher(t,n,S,C){let N=`${S.root(t)}/Contents`,F=S.dirs(t),under=t=>On.relative(N,t),beside=t=>On.relative(F.launcher,t),I=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(cd -- "$(dirname -- "$0")" && pwd)`,`contents=$(dirname -- "$here")`,`XDG_DATA_DIRS="$contents/${under(F.data)}"\${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}`,`export XDG_DATA_DIRS`];C.gtkRuntimeDir!==void 0&&I.push(`GJSIFY_GTK_RUNTIME="$contents/${under(C.gtkRuntimeDir)}"`,`export GJSIFY_GTK_RUNTIME`),C.nodeGiAddon!==void 0&&I.push(`NODE_GI_NATIVE="$contents/${under(C.nodeGiAddon)}"`,`export NODE_GI_NATIVE`),t.typelibFiles.length>0&&(I.push(`GI_TYPELIB_PATH="$contents/${under(F.native)}"\${GI_TYPELIB_PATH:+:$GI_TYPELIB_PATH}`,`export GI_TYPELIB_PATH`),I.push(`GJSIFY_GI_LIBRARY_PATH="$contents/${under(F.native)}"\${GJSIFY_GI_LIBRARY_PATH:+:$GJSIFY_GI_LIBRARY_PATH}`,`export GJSIFY_GI_LIBRARY_PATH`)),t.localeFiles.length>0&&I.push(`GJSIFY_LOCALE_DIR="$contents/${under(F.data)}/locale"`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&I.push(`GJSIFY_FONT_DIR="$contents/${stagedFontDir(under(F.data),t.appId)}"`,`export GJSIFY_FONT_DIR`);let H=C.interpreter===void 0?void 0:`"$here/${beside(C.interpreter)}"`;return I.push(`exec ${execLine(S,`"$contents/${under(F.bundle)}/${n}"`,t,H)} "$@"`,``),I.join(`
1190
1190
  `)}function renderWindowsLauncher(t,n,S,C){let N=S.dirs(t),at=t=>`%HERE%${windowsPath(t)}`,F=[`@echo off`,`rem Generated by "gjsify ship" - do not edit.`,`setlocal`,`set "HERE=%~dp0"`,prependVar(`XDG_DATA_DIRS`,at(N.data))];C.gtkRuntimeDir!==void 0&&F.push(`set "GJSIFY_GTK_RUNTIME=${at(C.gtkRuntimeDir)}"`),C.nodeGiAddon!==void 0&&F.push(`set "NODE_GI_NATIVE=${at(C.nodeGiAddon)}"`),t.typelibFiles.length>0&&F.push(prependVar(`GI_TYPELIB_PATH`,at(N.native)),prependVar(`PATH`,at(N.native))),t.localeFiles.length>0&&F.push(`set "GJSIFY_LOCALE_DIR=${at(N.data)}\\locale"`),t.fontFiles.length>0&&F.push(`set "GJSIFY_FONT_DIR=${at(stagedFontDir(N.data,t.appId))}"`);let I=C.interpreter===void 0?void 0:`"${at(C.interpreter)}"`;return F.push(`${execLine(S,`"${at(N.bundle)}\\${windowsPath(n)}"`,t,I)} %*`,``),F.join(`\r
1191
- `)}function prependVar(t,n){return`if defined ${t} (set "${t}=${n};%${t}%") else (set "${t}=${n}")`}function windowsPath(t){return t.split(`/`).filter(t=>t.length>0).join(`\\`)}function execLine(t,n,S,C){let N=t.name===`windows`?cmdQuote:shellQuote,F=S.execArgs.map(N).join(` `),I=C??(S.app===`node`?`node`:`gjs`);return`${S.app===`node`?I:`${I} -m`} ${n}${F?` ${F}`:``}`}var _G=__esmMin(()=>{Xn(),vH()});function createCpioArchive(t){let n=[],S=0;t.forEach((t,C)=>{let N=t.linkTarget===void 0?t.data??new Uint8Array:encodeUtf8(t.linkTarget),F=encodeUtf8(`${t.name}\0`),I=buildHeader({ino:t.ino??C+1,mode:t.mode,nlink:t.nlink??1,mtime:t.mtime??0,filesize:N.byteLength,namesize:F.byteLength});S=push(n,I,S),S=push(n,F,S),S=padTo4(n,S),S=push(n,N,S),S=padTo4(n,S)});let C=encodeUtf8(`TRAILER!!!\0`);return S=push(n,buildHeader({ino:0,mode:0,nlink:1,mtime:0,filesize:0,namesize:C.byteLength}),S),S=push(n,C,S),padTo4(n,S),concatBytes(n)}function buildHeader(t){let n=vG+hex8(t.ino)+hex8(t.mode)+hex8(0)+hex8(0)+hex8(t.nlink)+hex8(t.mtime)+hex8(t.filesize)+hex8(0)+hex8(0)+hex8(0)+hex8(0)+hex8(t.namesize)+hex8(0);if(n.length!==yG)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${yG}.`);return encodeUtf8(n)}function hex8(t){if(t<0||!Number.isInteger(t))throw Error(`gjsify ship: cpio header field must be a non-negative integer, got ${t}.`);let n=t.toString(16).toUpperCase();if(n.length>8)throw Error(`gjsify ship: cpio header field ${t} does not fit in 8 hex digits.`);return n.padStart(8,`0`)}function push(t,n,S){return n.byteLength>0&&t.push(n),S+n.byteLength}function padTo4(t,n){let S=n%4;if(S===0)return n;let C=4-S;return t.push(new Uint8Array(C)),n+C}var vG,yG,bG,xG,SG=__esmMin(()=>{rH(),vG=`070701`,yG=110,bG=32768,xG=16384});function buildRpmHeader(t,n){let S=[...t].sort((t,n)=>t.tag-n.tag),C=[],N=[],F=0;for(let t of S){if(t.tag<100)throw Error(`gjsify ship: rpm tag ${t.tag} is below 100 and would be rejected by hdrchkTag.`);let{data:n,count:S}=encodeValue(t.type,t.value,t.tag),I=EG[t.type],H=(I-F%I)%I;H>0&&(N.push(new Uint8Array(H)),F+=H),C.push({tag:t.tag,type:t.type,offset:F,count:S}),N.push(n),F+=n.byteLength}let I=F,H=C.length+1;N.push(indexEntry(n,7,-(wG*H),TG)),F+=wG;let W=new Uint8Array(CG.byteLength+8+H*wG+F),q=new DataView(W.buffer);W.set(CG,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,TG),Y),Y+=wG;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=wG;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(wG),F=new DataView(N.buffer);return F.setInt32(0,t),F.setInt32(4,n),F.setInt32(8,S),F.setInt32(12,C),N}function encodeValue(t,n,S){let C=new TextEncoder;switch(t){case 6:if(typeof n!=`string`)throw typeMismatch(S,`a string`);return{data:C.encode(`${n}\0`),count:1};case 8:case 9:{let t=typeof n==`string`?[n]:n;if(!Array.isArray(t))throw typeMismatch(S,`a string array`);if(t.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);return{data:C.encode(t.map(t=>`${t}\0`).join(``)),count:t.length}}case 7:if(!(n instanceof Uint8Array))throw typeMismatch(S,`binary data`);return{data:n,count:n.byteLength};case 3:case 4:{let C=typeof n==`number`?[n]:n;if(!Array.isArray(C))throw typeMismatch(S,`a number array`);if(C.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);let N=t===3?2:4,F=new Uint8Array(C.length*N),I=new DataView(F.buffer);return C.forEach((n,S)=>{t===3?I.setUint16(S*N,n&65535):I.setUint32(S*N,n>>>0)}),{data:F,count:C.length}}}}function typeMismatch(t,n){return Error(`gjsify ship: internal error — rpm tag ${t} expects ${n}.`)}function buildRpmLead(t){let n=new Uint8Array(96),S=new DataView(n.buffer);n.set([237,171,238,219],0),n[4]=3,n[5]=0,S.setInt16(6,0),S.setInt16(8,0);let C=new TextEncoder().encode(t).slice(0,65);return n.set(C,10),S.setInt16(76,0),S.setInt16(78,5),n}function padToEight(t){let n=(8-t.byteLength%8)%8;if(n===0)return t;let S=new Uint8Array(t.byteLength+n);return S.set(t,0),S}var CG,wG,TG,EG,DG=__esmMin(()=>{CG=Uint8Array.from([142,173,232,1,0,0,0,0]),wG=16,TG=16,EG={3:2,4:4,6:1,7:1,8:1,9:1}});async function buildRpm(t){let{settings:n,mtime:S}=t,C=collectFiles(t,`/${t.prefix.replace(/^\/+|\/+$/g,``)}`),N=createCpioArchive(C.map((t,n)=>({name:`.${t.path}`,mode:t.mode,data:t.data,mtime:S,ino:n+1}))),F=await gzipDeterministic(N),I=buildRpmHeader(mainHeaderEntries(t,C,N,F),63),H=concatBytes([I,F]),W=padToEight(buildRpmHeader([{tag:kG.SHA1HEADER,type:6,value:hashHex(`sha1`,I)},{tag:kG.SHA256HEADER,type:6,value:hashHex(`sha256`,I)},{tag:kG.SIZE,type:4,value:[H.byteLength]},{tag:kG.MD5,type:7,value:hashBytes(`md5`,H)},{tag:kG.PAYLOADSIZE,type:4,value:[N.byteLength]}],62));return concatBytes([buildRpmLead(`${n.binaryName}-${n.version}-${n.release}`),W,H])}function collectFiles(t,n){let S=t.payload.map(t=>{if(t.data.byteLength>4294967295)throw Error(`gjsify ship: ${t.path} is larger than 4 GiB, which needs rpm's LONGFILESIZES tag. That is not implemented — split the payload.`);return{path:`${n}/${t.path}`,mode:bG|t.mode&4095,data:t.data,isDirectory:!1}}),C=new Set;for(let t of S){let n=t.path.split(`/`).slice(1);n.pop();let S=``;for(let t of n)S=`${S}/${t}`,NG.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:xG|493,data:new Uint8Array,isDirectory:!0});return S.sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function mainHeaderEntries(t,n,S,C){let{settings:N}=t,F=`${N.version}-${N.release}`,I=[],H=[],W=[];for(let t of n){let n=t.path.lastIndexOf(`/`),S=`${t.path.slice(0,n)}/`,C=I.indexOf(S);C===-1&&(C=I.push(S)-1),H.push(C),W.push(t.path.slice(n+1))}let q=renderRpmScriptlets(readPayloadFacts(t.payload),t.prefix),Y=buildRequires(t.depends,q,readShebangInterpreters(t.payload)),X=buildRecommends(t.recommends??[]),Z=[{tag:OG.HEADERI18NTABLE,type:8,value:[`C`]},{tag:OG.NAME,type:6,value:N.binaryName},{tag:OG.VERSION,type:6,value:N.version},{tag:OG.RELEASE,type:6,value:N.release},{tag:OG.SUMMARY,type:9,value:[N.summary]},{tag:OG.DESCRIPTION,type:9,value:[N.description.join(`
1191
+ `)}function prependVar(t,n){return`if defined ${t} (set "${t}=${n};%${t}%") else (set "${t}=${n}")`}function windowsPath(t){return t.split(`/`).filter(t=>t.length>0).join(`\\`)}function execLine(t,n,S,C){let N=t.name===`windows`?cmdQuote:shellQuote,F=S.execArgs.map(N).join(` `),I=C??(S.app===`node`?`node`:`gjs`);return`${S.app===`node`?I:`${I} -m`} ${n}${F?` ${F}`:``}`}var yG=__esmMin(()=>{Xn(),vH()});function createCpioArchive(t){let n=[],S=0;t.forEach((t,C)=>{let N=t.linkTarget===void 0?t.data??new Uint8Array:encodeUtf8(t.linkTarget),F=encodeUtf8(`${t.name}\0`),I=buildHeader({ino:t.ino??C+1,mode:t.mode,nlink:t.nlink??1,mtime:t.mtime??0,filesize:N.byteLength,namesize:F.byteLength});S=push(n,I,S),S=push(n,F,S),S=padTo4(n,S),S=push(n,N,S),S=padTo4(n,S)});let C=encodeUtf8(`TRAILER!!!\0`);return S=push(n,buildHeader({ino:0,mode:0,nlink:1,mtime:0,filesize:0,namesize:C.byteLength}),S),S=push(n,C,S),padTo4(n,S),concatBytes(n)}function buildHeader(t){let n=bG+hex8(t.ino)+hex8(t.mode)+hex8(0)+hex8(0)+hex8(t.nlink)+hex8(t.mtime)+hex8(t.filesize)+hex8(0)+hex8(0)+hex8(0)+hex8(0)+hex8(t.namesize)+hex8(0);if(n.length!==xG)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${xG}.`);return encodeUtf8(n)}function hex8(t){if(t<0||!Number.isInteger(t))throw Error(`gjsify ship: cpio header field must be a non-negative integer, got ${t}.`);let n=t.toString(16).toUpperCase();if(n.length>8)throw Error(`gjsify ship: cpio header field ${t} does not fit in 8 hex digits.`);return n.padStart(8,`0`)}function push(t,n,S){return n.byteLength>0&&t.push(n),S+n.byteLength}function padTo4(t,n){let S=n%4;if(S===0)return n;let C=4-S;return t.push(new Uint8Array(C)),n+C}var bG,xG,SG,CG,wG=__esmMin(()=>{rH(),bG=`070701`,xG=110,SG=32768,CG=16384});function buildRpmHeader(t,n){let S=[...t].sort((t,n)=>t.tag-n.tag),C=[],N=[],F=0;for(let t of S){if(t.tag<100)throw Error(`gjsify ship: rpm tag ${t.tag} is below 100 and would be rejected by hdrchkTag.`);let{data:n,count:S}=encodeValue(t.type,t.value,t.tag),I=OG[t.type],H=(I-F%I)%I;H>0&&(N.push(new Uint8Array(H)),F+=H),C.push({tag:t.tag,type:t.type,offset:F,count:S}),N.push(n),F+=n.byteLength}let I=F,H=C.length+1;N.push(indexEntry(n,7,-(EG*H),DG)),F+=EG;let W=new Uint8Array(TG.byteLength+8+H*EG+F),q=new DataView(W.buffer);W.set(TG,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,DG),Y),Y+=EG;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=EG;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(EG),F=new DataView(N.buffer);return F.setInt32(0,t),F.setInt32(4,n),F.setInt32(8,S),F.setInt32(12,C),N}function encodeValue(t,n,S){let C=new TextEncoder;switch(t){case 6:if(typeof n!=`string`)throw typeMismatch(S,`a string`);return{data:C.encode(`${n}\0`),count:1};case 8:case 9:{let t=typeof n==`string`?[n]:n;if(!Array.isArray(t))throw typeMismatch(S,`a string array`);if(t.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);return{data:C.encode(t.map(t=>`${t}\0`).join(``)),count:t.length}}case 7:if(!(n instanceof Uint8Array))throw typeMismatch(S,`binary data`);return{data:n,count:n.byteLength};case 3:case 4:{let C=typeof n==`number`?[n]:n;if(!Array.isArray(C))throw typeMismatch(S,`a number array`);if(C.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);let N=t===3?2:4,F=new Uint8Array(C.length*N),I=new DataView(F.buffer);return C.forEach((n,S)=>{t===3?I.setUint16(S*N,n&65535):I.setUint32(S*N,n>>>0)}),{data:F,count:C.length}}}}function typeMismatch(t,n){return Error(`gjsify ship: internal error — rpm tag ${t} expects ${n}.`)}function buildRpmLead(t){let n=new Uint8Array(96),S=new DataView(n.buffer);n.set([237,171,238,219],0),n[4]=3,n[5]=0,S.setInt16(6,0),S.setInt16(8,0);let C=new TextEncoder().encode(t).slice(0,65);return n.set(C,10),S.setInt16(76,0),S.setInt16(78,5),n}function padToEight(t){let n=(8-t.byteLength%8)%8;if(n===0)return t;let S=new Uint8Array(t.byteLength+n);return S.set(t,0),S}var TG,EG,DG,OG,kG=__esmMin(()=>{TG=Uint8Array.from([142,173,232,1,0,0,0,0]),EG=16,DG=16,OG={3:2,4:4,6:1,7:1,8:1,9:1}});async function buildRpm(t){let{settings:n,mtime:S}=t,C=collectFiles(t,`/${t.prefix.replace(/^\/+|\/+$/g,``)}`),N=createCpioArchive(C.map((t,n)=>({name:`.${t.path}`,mode:t.mode,data:t.data,mtime:S,ino:n+1}))),F=await gzipDeterministic(N),I=buildRpmHeader(mainHeaderEntries(t,C,N,F),63),H=concatBytes([I,F]),W=padToEight(buildRpmHeader([{tag:jG.SHA1HEADER,type:6,value:hashHex(`sha1`,I)},{tag:jG.SHA256HEADER,type:6,value:hashHex(`sha256`,I)},{tag:jG.SIZE,type:4,value:[H.byteLength]},{tag:jG.MD5,type:7,value:hashBytes(`md5`,H)},{tag:jG.PAYLOADSIZE,type:4,value:[N.byteLength]}],62));return concatBytes([buildRpmLead(`${n.binaryName}-${n.version}-${n.release}`),W,H])}function collectFiles(t,n){let S=t.payload.map(t=>{if(t.data.byteLength>4294967295)throw Error(`gjsify ship: ${t.path} is larger than 4 GiB, which needs rpm's LONGFILESIZES tag. That is not implemented — split the payload.`);return{path:`${n}/${t.path}`,mode:SG|t.mode&4095,data:t.data,isDirectory:!1}}),C=new Set;for(let t of S){let n=t.path.split(`/`).slice(1);n.pop();let S=``;for(let t of n)S=`${S}/${t}`,FG.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:CG|493,data:new Uint8Array,isDirectory:!0});return S.sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function mainHeaderEntries(t,n,S,C){let{settings:N}=t,F=`${N.version}-${N.release}`,I=[],H=[],W=[];for(let t of n){let n=t.path.lastIndexOf(`/`),S=`${t.path.slice(0,n)}/`,C=I.indexOf(S);C===-1&&(C=I.push(S)-1),H.push(C),W.push(t.path.slice(n+1))}let q=renderRpmScriptlets(readPayloadFacts(t.payload),t.prefix),Y=buildRequires(t.depends,q,readShebangInterpreters(t.payload)),X=buildRecommends(t.recommends??[]),Z=[{tag:AG.HEADERI18NTABLE,type:8,value:[`C`]},{tag:AG.NAME,type:6,value:N.binaryName},{tag:AG.VERSION,type:6,value:N.version},{tag:AG.RELEASE,type:6,value:N.release},{tag:AG.SUMMARY,type:9,value:[N.summary]},{tag:AG.DESCRIPTION,type:9,value:[N.description.join(`
1192
1192
 
1193
- `)]},{tag:OG.BUILDTIME,type:4,value:[t.mtime]},{tag:OG.BUILDHOST,type:6,value:`localhost`},{tag:OG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:OG.LICENSE,type:6,value:N.license},{tag:OG.GROUP,type:9,value:[N.group]},{tag:OG.OS,type:6,value:`linux`},{tag:OG.ARCH,type:6,value:t.archLabel},{tag:OG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:OG.RPMVERSION,type:6,value:`4.20.0`},{tag:OG.ENCODING,type:6,value:`utf-8`},{tag:OG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:OG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:OG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:OG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:OG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:OG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:OG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:OG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:OG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:OG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:OG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:OG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:OG.FILELANGS,type:8,value:n.map(()=>``)},{tag:OG.FILEDIGESTALGO,type:4,value:[jG]},{tag:OG.DIRINDEXES,type:4,value:H},{tag:OG.BASENAMES,type:8,value:W},{tag:OG.DIRNAMES,type:8,value:I},{tag:OG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:OG.PROVIDEFLAGS,type:4,value:[AG.EQUAL]},{tag:OG.PROVIDEVERSION,type:8,value:[F]},{tag:OG.REQUIRENAME,type:8,value:Y.names},{tag:OG.REQUIREFLAGS,type:4,value:Y.flags},{tag:OG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:OG.RECOMMENDNAME,type:8,value:X.names},{tag:OG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:OG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:OG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:OG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:OG.PAYLOADFLAGS,type:6,value:`9`},{tag:OG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:OG.PAYLOADDIGESTALGO,type:4,value:[jG]},{tag:OG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:OG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:OG.POSTIN,type:6,value:q.post}),Z.push({tag:OG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:OG.POSTUN,type:6,value:q.postun}),Z.push({tag:OG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([OG.FILESIZES,OG.FILEMODES,OG.FILERDEVS,OG.FILEMTIMES,OG.FILEDIGESTS,OG.FILELINKTOS,OG.FILEFLAGS,OG.FILEUSERNAME,OG.FILEGROUPNAME,OG.FILEVERIFYFLAGS,OG.FILEDEVICES,OG.FILEINODES,OG.FILELANGS,OG.DIRINDEXES,OG.BASENAMES]);for(let C of t){if(!S.has(C.tag))continue;let t=Array.isArray(C.value)?C.value.length:1;if(t!==n)throw Error(`gjsify ship: internal error — rpm tag ${C.tag} has ${t} values for ${n} files.`)}}function buildRequires(t,n,S){let C=[],N=[],F=[];for(let n of t){let t=parseDepend(n);C.push(t.name),N.push(senseFor(t.relation)),F.push(t.version??``)}n.post!==void 0&&(C.push(`/bin/sh`),N.push(AG.INTERP|AG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(AG.INTERP|AG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(AG.FIND_REQUIRES),F.push(``);for(let[t,n]of MG)C.push(t),N.push(AG.RPMLIB|AG.LESS|AG.EQUAL),F.push(n);return{names:C,flags:N,versions:F}}function buildRecommends(t){let n=[],S=[],C=[];for(let N of t){let t=parseDepend(N);n.push(t.name),S.push(senseFor(t.relation)),C.push(t.version??``)}return{names:n,flags:S,versions:C}}function senseFor(t){switch(t){case`>=`:return AG.GREATER|AG.EQUAL;case`>`:return AG.GREATER;case`<=`:return AG.LESS|AG.EQUAL;case`<`:return AG.LESS;case`=`:return AG.EQUAL;default:return 0}}function hashHex(t,n){return createHash(t).update(n).digest(`hex`)}function hashBytes(t,n){return new Uint8Array(createHash(t).update(n).digest())}var OG,kG,AG,jG,MG,NG,PG=__esmMin(()=>{gl(),rH(),SG(),hH(),xU(),DG(),gH(),yH(),vH(),OG={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RECOMMENDNAME:5046,RECOMMENDVERSION:5047,RECOMMENDFLAGS:5048,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},kG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},AG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},jG=8,MG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],NG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${_H.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${_H.metainfo}`,`/usr/share/glib-2.0`,`/usr/${_H.schemas}`,`/usr/${_H.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(t){let n=process.cwd(),S=t.os===void 0?hostLayout():resolveLayout(t.os),C=await new Config().forCommand(n),N=C.ship??{},F=C.flatpak??{},I=resolveShipApp({project:C.app,perTarget:N.app,layoutOs:S.os}),H=I.app;I.overridden&&ge.log(`${FG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${FG} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>qW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${FG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${FG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${FG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,desktopExecArgs:ae.desktopExecArgs,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()};for(let t of validateAppMetadata(le))ge.warn(`${FG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${FG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let ue=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),de=await resolveCarriedRuntime(S,ae,n),fe=carryNodeModules(de,S,ae,n,N.nodeModules,N.nodeModulesExclude);fe.length>0&&(ae.nodeModulesDirs=fe);let pe=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),me={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,de.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,de.launcher)])),metainfo:ue.metainfo,desktopEntry:ue.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},he=In(n,ae.outDir),_e=zn(he,`stage`),ve=[...planStage(ae,me),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(he,`schemas`)})],ye=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;ye!==void 0&&ge.log(`${FG} icon: ${iconSizes(ye).join(`/`)} px, ${ye.source}`);let be=placeStage(S,{...ae,icon:ye,categories:oe.categories},ve,[...de.files,...pe.files]);if(writeStage(_e,be),ge.log(`${FG} staged ${be.length} file(s) for ${S.name} in ${Bn(n,_e)}/`),t.verbose)for(let t of be)ge.log(`${FG} ${t.path}`);if(assertPayloadMatchesArch(readStage([_e],be),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(ve);if(t.length>0){ge.warn(`${FG} the ${S.name} layout carries ${t.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let n={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:S,verdict:C,why:N}of t)ge.warn(`${FG} ${n[C]??``}${S} — ${N}`)}for(let t of de.found)ge.log(`${FG} carries its own ${t}`);for(let t of de.missing)ge.warn(`${FG} ${t}`);de.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${FG} ${S.runtimeGap}`),S.fontGap!==void 0&&ve.some(t=>isUnder(t.path,_H.fonts))&&ge.warn(`${FG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${FG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let xe=scanGiRequirements(se),Se=xe.namespaces,Ce=xe.optional;if(t.verbose){let t=Se.filter(t=>!Ce.includes(t));ge.log(`${FG} gi namespaces: ${Se.join(`, `)||`(none)`}`),Ce.length>0&&(ge.log(`${FG} gi optional namespaces: ${Ce.join(`, `)}`),ge.log(`${FG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let we=new Map;for(let t of q)we.set(t.id,(await planOverlay(ae,t,me)).map(t=>({...t,path:place(S,ae,t.path)})));let Te=readPayloadFacts(ve);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:Se,optionalNamespaces:Ce,hasIcons:Te.hasIcons,hasSchemas:Te.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:Te.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${FG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${FG} ${t}`)}let Ee=writeStageManifest({stageDir:_e,settings:ae,formats:q,mtime:ce,namespaces:Se,optionalNamespaces:Ce,staged:be,overlay:we});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Ee.formats.join(`, `)||t;ge.log(`${FG} stage manifest: ${formatTarget(Ee.target)}, formats ${n}`);return}let De=[];for(let n of q)De.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:be,overlay:we.get(n.id)??[],stageDir:_e,outRoot:he,namespaces:Se,optionalNamespaces:Ce,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,De)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${FG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${FG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:LG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${FG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return[];let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${FG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${FG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${FG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${FG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>qW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>qW[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${FG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${FG} ${t}`);if(ge.log(`${FG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${FG} ${t.path}`);ge.log(`${FG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${FG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${FG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${FG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:xW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${FG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${FG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${FG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${FG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,$W),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${$W}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${FG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${FG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${FG} ${t}`)}),ce=!0):ge.warn(`${FG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${FG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${FG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
1193
+ `)]},{tag:AG.BUILDTIME,type:4,value:[t.mtime]},{tag:AG.BUILDHOST,type:6,value:`localhost`},{tag:AG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:AG.LICENSE,type:6,value:N.license},{tag:AG.GROUP,type:9,value:[N.group]},{tag:AG.OS,type:6,value:`linux`},{tag:AG.ARCH,type:6,value:t.archLabel},{tag:AG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:AG.RPMVERSION,type:6,value:`4.20.0`},{tag:AG.ENCODING,type:6,value:`utf-8`},{tag:AG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:AG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:AG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:AG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:AG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:AG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:AG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:AG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:AG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:AG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:AG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:AG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:AG.FILELANGS,type:8,value:n.map(()=>``)},{tag:AG.FILEDIGESTALGO,type:4,value:[NG]},{tag:AG.DIRINDEXES,type:4,value:H},{tag:AG.BASENAMES,type:8,value:W},{tag:AG.DIRNAMES,type:8,value:I},{tag:AG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:AG.PROVIDEFLAGS,type:4,value:[MG.EQUAL]},{tag:AG.PROVIDEVERSION,type:8,value:[F]},{tag:AG.REQUIRENAME,type:8,value:Y.names},{tag:AG.REQUIREFLAGS,type:4,value:Y.flags},{tag:AG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:AG.RECOMMENDNAME,type:8,value:X.names},{tag:AG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:AG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:AG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:AG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:AG.PAYLOADFLAGS,type:6,value:`9`},{tag:AG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:AG.PAYLOADDIGESTALGO,type:4,value:[NG]},{tag:AG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:AG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:AG.POSTIN,type:6,value:q.post}),Z.push({tag:AG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:AG.POSTUN,type:6,value:q.postun}),Z.push({tag:AG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([AG.FILESIZES,AG.FILEMODES,AG.FILERDEVS,AG.FILEMTIMES,AG.FILEDIGESTS,AG.FILELINKTOS,AG.FILEFLAGS,AG.FILEUSERNAME,AG.FILEGROUPNAME,AG.FILEVERIFYFLAGS,AG.FILEDEVICES,AG.FILEINODES,AG.FILELANGS,AG.DIRINDEXES,AG.BASENAMES]);for(let C of t){if(!S.has(C.tag))continue;let t=Array.isArray(C.value)?C.value.length:1;if(t!==n)throw Error(`gjsify ship: internal error — rpm tag ${C.tag} has ${t} values for ${n} files.`)}}function buildRequires(t,n,S){let C=[],N=[],F=[];for(let n of t){let t=parseDepend(n);C.push(t.name),N.push(senseFor(t.relation)),F.push(t.version??``)}n.post!==void 0&&(C.push(`/bin/sh`),N.push(MG.INTERP|MG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(MG.INTERP|MG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(MG.FIND_REQUIRES),F.push(``);for(let[t,n]of PG)C.push(t),N.push(MG.RPMLIB|MG.LESS|MG.EQUAL),F.push(n);return{names:C,flags:N,versions:F}}function buildRecommends(t){let n=[],S=[],C=[];for(let N of t){let t=parseDepend(N);n.push(t.name),S.push(senseFor(t.relation)),C.push(t.version??``)}return{names:n,flags:S,versions:C}}function senseFor(t){switch(t){case`>=`:return MG.GREATER|MG.EQUAL;case`>`:return MG.GREATER;case`<=`:return MG.LESS|MG.EQUAL;case`<`:return MG.LESS;case`=`:return MG.EQUAL;default:return 0}}function hashHex(t,n){return createHash(t).update(n).digest(`hex`)}function hashBytes(t,n){return new Uint8Array(createHash(t).update(n).digest())}var AG,jG,MG,NG,PG,FG,IG=__esmMin(()=>{gl(),rH(),wG(),hH(),xU(),kG(),gH(),yH(),vH(),AG={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RECOMMENDNAME:5046,RECOMMENDVERSION:5047,RECOMMENDFLAGS:5048,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},jG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},MG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},NG=8,PG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],FG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${_H.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${_H.metainfo}`,`/usr/share/glib-2.0`,`/usr/${_H.schemas}`,`/usr/${_H.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(t){let n=process.cwd(),S=t.os===void 0?hostLayout():resolveLayout(t.os),C=await new Config().forCommand(n),N=C.ship??{},F=C.flatpak??{},I=resolveShipApp({project:C.app,perTarget:N.app,layoutOs:S.os}),H=I.app;I.overridden&&ge.log(`${LG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${LG} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>YW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${LG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${LG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${LG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,desktopExecArgs:ae.desktopExecArgs,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()},ue=resolveHandMetainfo({shipMetainfo:N.metainfo,siteMetainfo:C.site?.metainfo,configReleases:N.releases,projectDir:n});if(ue!==void 0){for(let t of checkHandMetainfo(ue,{appId:ae.appId,kind:ae.kind,version:ae.version}))ge.warn(`${LG} ${t}`);ge.log(`${LG} AppStream metainfo from ${ue.path} (\`${ue.key}\`), staged as written`);for(let t of await lintMetainfo(ue.xml))ge.warn(`${LG} ${formatFinding(t,!1)}`)}if(ue===void 0)for(let t of validateAppMetadata(le))ge.warn(`${LG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${LG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let de=ue?.xml,fe=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),pe=await resolveCarriedRuntime(S,ae,n),me=carryNodeModules(pe,S,ae,n,N.nodeModules,N.nodeModulesExclude);me.length>0&&(ae.nodeModulesDirs=me);let he=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),_e={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,pe.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,pe.launcher)])),metainfo:de??fe.metainfo,desktopEntry:fe.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},ve=In(n,ae.outDir),ye=zn(ve,`stage`),be=[...planStage(ae,_e),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(ve,`schemas`)})],xe=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;xe!==void 0&&ge.log(`${LG} icon: ${iconSizes(xe).join(`/`)} px, ${xe.source}`);let Se=placeStage(S,{...ae,icon:xe,categories:oe.categories},be,[...pe.files,...he.files]);if(writeStage(ye,Se),ge.log(`${LG} staged ${Se.length} file(s) for ${S.name} in ${Bn(n,ye)}/`),t.verbose)for(let t of Se)ge.log(`${LG} ${t.path}`);if(assertPayloadMatchesArch(readStage([ye],Se),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(be);if(t.length>0){ge.warn(`${LG} the ${S.name} layout carries ${t.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let n={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:S,verdict:C,why:N}of t)ge.warn(`${LG} ${n[C]??``}${S} — ${N}`)}for(let t of pe.found)ge.log(`${LG} carries its own ${t}`);for(let t of pe.missing)ge.warn(`${LG} ${t}`);pe.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${LG} ${S.runtimeGap}`),S.fontGap!==void 0&&be.some(t=>isUnder(t.path,_H.fonts))&&ge.warn(`${LG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${LG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let Ce=scanGiRequirements(se),we=Ce.namespaces,Te=Ce.optional;if(t.verbose){let t=we.filter(t=>!Te.includes(t));ge.log(`${LG} gi namespaces: ${we.join(`, `)||`(none)`}`),Te.length>0&&(ge.log(`${LG} gi optional namespaces: ${Te.join(`, `)}`),ge.log(`${LG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ee=new Map;for(let t of q)Ee.set(t.id,(await planOverlay(ae,t,_e)).map(t=>({...t,path:place(S,ae,t.path)})));let De=readPayloadFacts(be);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:we,optionalNamespaces:Te,hasIcons:De.hasIcons,hasSchemas:De.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:De.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${LG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${LG} ${t}`)}let Oe=writeStageManifest({stageDir:ye,settings:ae,formats:q,mtime:ce,namespaces:we,optionalNamespaces:Te,staged:Se,overlay:Ee});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Oe.formats.join(`, `)||t;ge.log(`${LG} stage manifest: ${formatTarget(Oe.target)}, formats ${n}`);return}let ke=[];for(let n of q)ke.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:Se,overlay:Ee.get(n.id)??[],stageDir:ye,outRoot:ve,namespaces:we,optionalNamespaces:Te,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,ke)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${LG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${LG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:zG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${LG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return[];let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${LG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${LG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${LG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${LG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>YW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>YW[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${LG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${LG} ${t}`);if(ge.log(`${LG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${LG} ${t.path}`);ge.log(`${LG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${LG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${LG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:SW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${LG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${LG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,tG),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${tG}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${LG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)}),ce=!0):ge.warn(`${LG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${LG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${LG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
1194
1194
  \`gjsify ship ${n.name} --stage\` assembles the tree either way.`);let N=formatIdsFor(n.os).sort();if(N.length>0){let t=S===`stage`?`${n.name} --stage --target`:`${n.name} --target`;throw Error(`gjsify ship: this run records no formats for the ${n.name} layout, so there is nothing to pack — and it is not that none exist: ${N.join(`, `)} wrap it.\n An empty list means none were SELECTED. \`gjsify.ship.targets\` is filtered to the layout being assembled,
1195
1195
  so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
1196
- Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${FG} running the project's build script`);let C=S===void 0&&n===void 0?void 0:{...process.env};C!==void 0&&(n!==void 0&&(C[Oh]=n),S!==void 0&&(C[jh]=S));let N=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,env:C,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(N.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(N)}.`)}var FG,IG,LG,RG=__esmMin(()=>{_e(),kh(),Mh(),af(),Xn(),_R(),EB(),gV(),KI(),bB(),Ch(),hv(),SU(),hH(),$U(),eW(),nW(),rW(),zU(),fW(),_W(),pV(),vW(),wH(),yW(),XW(),oU(),VU(),vH(),dU(),eG(),NW(),tG(),lG(),dG(),fP(),xU(),KU(),pG(),gG(),_G(),PG(),PU(),SW(),CW(),FG=`[gjsify ship]`,IG={command:`ship [os]`,description:`Build installable artifacts (${JW.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${iU.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`channel`,{type:`string`,choices:[...Eh],description:"Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. Passed to the project build, and gates the metainfo donation URL."}).option(`pricing`,{type:`string`,choices:[...Ah],description:`Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project build. Default 'free'.`}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}},LG=1440*7});function parseGithubRepo(t){let n=t.trim().replace(/^git\+/,``),S=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(n),C=/^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(n)??S;return C===null?void 0:`${C[1]}/${C[2].replace(/\.git$/,``)}`}function releaseDateOf(t){return new Date(t*1e3).toISOString().slice(0,10)}function readFlatparkSources(t){let n=[];if(existsSync(t.dir))for(let S of readdirSync(t.dir).sort()){if(!S.endsWith(`.gjsify-release.json`))continue;let C=JSON.parse(readFileSync(zn(t.dir,S),`utf-8`));C.format===`linux-tar-flatpak`&&C.os===`linux`&&n.push(C)}if(n.length===0)throw Error(`gjsify flatpark: no release record for \`${BG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${fG}\`, which \`gjsify ship --target ${BG}\` writes beside the archive. Run that first, or point --release-dir at the directory that holds the record.`);let S=`${t.tagPrefix}${t.version}`,C=n.map(n=>{let C=VG[n.arch===`noarch`?t.stageArch??n.arch:n.arch];if(C===void 0)throw Error(`gjsify flatpark: ${n.artifact} is built for \`${n.arch}\`, which has no Flatpak arch (known: ${Object.keys(VG).join(`, `)}).`);return{arch:C,artifact:n.artifact,url:`https://github.com/${t.repo}/releases/download/${S}/${n.artifact}`,sha256:n.sha256,size:n.size}}),N=new Set;for(let n of C){if(N.has(n.arch))throw Error(`gjsify flatpark: two release records for ${n.arch} in ${t.dir}; keep one.`);N.add(n.arch)}return C.sort((t,n)=>t.arch.localeCompare(n.arch))}function renderApplyExtra(t){return`#!/bin/sh
1196
+ Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${LG} running the project's build script`);let C=S===void 0&&n===void 0?void 0:{...process.env};C!==void 0&&(n!==void 0&&(C[Oh]=n),S!==void 0&&(C[jh]=S));let N=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,env:C,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(N.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(N)}.`)}var LG,RG,zG,BG=__esmMin(()=>{_e(),kh(),Mh(),af(),Xn(),_R(),EB(),gV(),KI(),bB(),Ch(),hv(),SU(),hH(),$U(),eW(),nW(),rW(),zU(),fW(),_W(),pV(),vW(),wH(),UV(),yW(),bW(),QW(),oU(),VU(),vH(),dU(),nG(),FW(),rG(),dG(),pG(),fP(),xU(),KU(),hG(),vG(),yG(),IG(),PU(),CW(),wW(),LG=`[gjsify ship]`,RG={command:`ship [os]`,description:`Build installable artifacts (${XW.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${iU.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`channel`,{type:`string`,choices:[...Eh],description:"Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. Passed to the project build, and gates the metainfo donation URL."}).option(`pricing`,{type:`string`,choices:[...Ah],description:`Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project build. Default 'free'.`}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}},zG=1440*7});function parseGithubRepo(t){let n=t.trim().replace(/^git\+/,``),S=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(n),C=/^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(n)??S;return C===null?void 0:`${C[1]}/${C[2].replace(/\.git$/,``)}`}function releaseDateOf(t){return new Date(t*1e3).toISOString().slice(0,10)}function readFlatparkSources(t){let n=[];if(existsSync(t.dir))for(let S of readdirSync(t.dir).sort()){if(!S.endsWith(`.gjsify-release.json`))continue;let C=JSON.parse(readFileSync(zn(t.dir,S),`utf-8`));C.format===`linux-tar-flatpak`&&C.os===`linux`&&n.push(C)}if(n.length===0)throw Error(`gjsify flatpark: no release record for \`${HG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${mG}\`, which \`gjsify ship --target ${HG}\` writes beside the archive. Run that first, or point --release-dir at the directory that holds the record.`);let S=`${t.tagPrefix}${t.version}`,C=n.map(n=>{let C=UG[n.arch===`noarch`?t.stageArch??n.arch:n.arch];if(C===void 0)throw Error(`gjsify flatpark: ${n.artifact} is built for \`${n.arch}\`, which has no Flatpak arch (known: ${Object.keys(UG).join(`, `)}).`);return{arch:C,artifact:n.artifact,url:`https://github.com/${t.repo}/releases/download/${S}/${n.artifact}`,sha256:n.sha256,size:n.size}}),N=new Set;for(let n of C){if(N.has(n.arch))throw Error(`gjsify flatpark: two release records for ${n.arch} in ${t.dir}; keep one.`);N.add(n.arch)}return C.sort((t,n)=>t.arch.localeCompare(n.arch))}function renderApplyExtra(t){return`#!/bin/sh
1197
1197
  set -eu
1198
1198
 
1199
1199
  extra_root="\${EXTRA_ROOT:-/app/extra}"
1200
1200
  cd "$extra_root"
1201
1201
 
1202
- [ -f ${zG} ] || { echo "missing extra-data: ${zG}" >&2; exit 1; }
1202
+ [ -f ${VG} ] || { echo "missing extra-data: ${VG}" >&2; exit 1; }
1203
1203
 
1204
1204
  rm -rf stage app
1205
1205
  mkdir stage
1206
- bsdtar --no-same-owner -xf ${zG} -C stage
1206
+ bsdtar --no-same-owner -xf ${VG} -C stage
1207
1207
 
1208
1208
  top="$(find stage -mindepth 1 -maxdepth 1 -type d)"
1209
1209
  [ "$(printf '%s\\n' "$top" | wc -l)" -eq 1 ] || { echo "expected one top-level directory" >&2; exit 1; }
1210
1210
  mv "$top" app
1211
1211
  [ -x app/bin/${shellWord(t)} ] || { echo "${shellWord(t)} launcher not found in the tarball" >&2; exit 1; }
1212
1212
 
1213
- rm -rf stage ${zG}
1213
+ rm -rf stage ${VG}
1214
1214
  `}function renderWrapper(t){return`#!/bin/sh
1215
1215
  set -eu
1216
1216
  exec /app/extra/app/bin/${shellWord(t)} "$@"
1217
- `}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${zG}`,` only-arches:`,` - ${t.arch}`,` url: ${yamlString(t.url)}`,` sha256: ${t.sha256}`,` size: ${t.size}`]),` # END MANAGED EXTRA-DATA`,...C.flatMap(t=>[` - type: file`,` path: ${yamlString(t)}`])].join(`
1217
+ `}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${VG}`,` only-arches:`,` - ${t.arch}`,` url: ${yamlString(t.url)}`,` sha256: ${t.sha256}`,` size: ${t.size}`]),` # END MANAGED EXTRA-DATA`,...C.flatMap(t=>[` - type: file`,` path: ${yamlString(t)}`])].join(`
1218
1218
  `)}\n`}function firstCategory(t){return/<category>([^<]+)<\/category>/.exec(t)?.[1]?.trim()??`Utility`}function keywords(t){return[...t.matchAll(/<keyword>([^<]+)<\/keyword>/g)].map(t=>t[1].trim())}function renderDescriptor(t){let n=keywords(t.metainfo);return`${[`id: ${yamlString(t.appId)}`,`name: ${yamlString(t.name)}`,`summary: ${yamlString(t.summary)}`,`website: ${yamlString(t.homepage??`https://github.com/${t.repo}`)}`,`source_url: https://github.com/${t.repo}`,`build:`,` manifest: ${t.appId}.yml`,` branch: stable`,` mode: extra-data`,` arches: [${t.sources.map(t=>t.arch).join(`, `)}]`,`catalog:`,` category: ${yamlString(firstCategory(t.metainfo))}`,` upstream_approved: false`,...n.length===0?[]:[` tags:`,...n.map(t=>` - ${yamlString(t)}`)],`update:`,` command: ./resolve-update.sh`,`policy:`,` proprietary: false`,` dangerous_permissions: []`].join(`
1219
- `)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${zG}", arch:"${t.arch}", url:$u_${n}}`),N=n.map(({key:t})=>`--arg u_${t} "$url_${t}"`);return`#!/usr/bin/env bash
1219
+ `)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${VG}", arch:"${t.arch}", url:$u_${n}}`),N=n.map(({key:t})=>`--arg u_${t} "$url_${t}"`);return`#!/usr/bin/env bash
1220
1220
  # Update resolver for ${t.name}, written by \`gjsify flatpark\`.
1221
1221
  #
1222
1222
  # Prints the latest release on stdout as JSON:
1223
1223
  # { "version": "…", "releaseDate": "YYYY-MM-DD",
1224
- # "sources": [ { "filename": "${zG}", "arch": "…", "url": "…" } ] }
1224
+ # "sources": [ { "filename": "${VG}", "arch": "…", "url": "…" } ] }
1225
1225
  # Logs go to stderr. No hashing and no manifest rewriting: FlatPark downloads
1226
1226
  # each URL and computes the extra-data sha256 and size itself.
1227
1227
  set -euo pipefail
@@ -1244,8 +1244,8 @@ echo "resolved ${t.name} $version ($date)" >&2
1244
1244
 
1245
1245
  jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
1246
1246
  '{version:$v, releaseDate:$d, sources:[${C.join(`, `)}]}'
1247
- `}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var zG,BG,VG,HG=__esmMin(()=>{af(),Xn(),pG(),CU(),zG=`app.tar.gz`,BG=`linux-tar-flatpak`,VG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${UG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${UG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${UG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var UG,WG,GG=__esmMin(()=>{_e(),af(),Xn(),_R(),KI(),HG(),SW(),UG=`[gjsify flatpark]`,WG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${UG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${UG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${UG} ${t.arch}: ${t.url}`);ge.log(`${UG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var KG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return qG===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===XG&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[XG];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,XG,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
1248
- `)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,qG)};for(let t=0;t<Math.min(32,S.length);t++)F.push((async()=>{for(;;){let t=C++;if(t>=S.length)return;let n=S[t];if(!n)return;await wireOne(n.linkPath,n.relTarget)}})());await Promise.all(F),ge.log(`gjsify install: wired ${q.length} workspace symlink(s)`)}let n=zn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=zn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(Hn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,qG),S++)}S>0&&ge.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let X=C.find(n=>n.location===t)?.manifest,Z=extractOverrides(X),te=Z?.global,ne=new Map,re=new Set;if(Z&&Z.scoped.size>0){for(let t of F?.workspaces??C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){let C=scopedOverrideFor(t,n,Z);if(!C)continue;let N=C,F=t.location,I=ne.get(F);I||(I=new Set,ne.set(F,I)),I.add(`${n}@${N}`),re.add(`${n}@${S}`)}}}let t=new Set;for(let n of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(n,S,Z)||t.add(`${S}@${N}`)}for(let n of re)t.has(n)||H.delete(n);ne.size>0&&ge.log(`gjsify install: ${ne.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(H.size>0){let I=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1});await installPackages({prefix:t,specs:[...H],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],overrides:te,signal:S,progress:I,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,specOrigins:new Map([...W].map(([t,n])=>[t,[...n]])),optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest)),focusSpecs:F?.specs})}else n.verbose&&ge.log(`gjsify install: no external deps to fetch`);for(let[t,F]of ne){if(F.size===0)continue;let I=C.find(n=>n.location===t)?.name??t;n.verbose&&ge.log(`gjsify install: ${I} — installing ${F.size} scoped-override spec(s) into ${t}/node_modules/`),await installPackages({prefix:t,specs:[...F],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,signal:S,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest))})}await wireWorkspaceSymlinks(),reportRewiredDevLinks(Y);let ie=writeWorkspaceBinShims(t,F?.workspaces??C);ie>0&&ge.log(`gjsify install: linked ${ie} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(t,n){let S=zn(t,`node_modules`,`.bin`),C=detectNativePackages(t).map(t=>t.prebuildsDir),N=0;for(let F of n){let n=F.manifest,I=n.gjsify?.bin,H=n.bin,W=mergeWorkspaceBins(F.name,I,H);if(W.size!==0){mkdirSync(S,{recursive:!0});for(let[n,{nodeTarget:I,gjsTarget:H}]of W){let W=zn(S,n);for(let t of[W,`${W}.cmd`,`${W}.ps1`])try{rmSync(t,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(W,buildBinShim(F.location,I,H,C,process.platform,t),{mode:493}),chmodSync(W,493),process.platform===`win32`)for(let[t,n]of Object.entries(buildWorkspaceBinShimsForWindows(F.location,I,H,C)))writeFileSync(`${W}.${t}`,n,{mode:493});N++}}}return N}function extractOverrides(t){if(!t)return;let n={},S=new Map,merge=(t,C)=>{if(t){for(let[N,F]of Object.entries(t))if(!N.startsWith(`_`)){if(typeof F==`string`){let t=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(t=N.slice(0,S)),n[t]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let t={};for(let[n,S]of Object.entries(F)){if(n.startsWith(`_`))continue;if(typeof S!=`string`){ge.warn(`gjsify install: ${C}["${N}"]["${n}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=n,I=n.startsWith(`@`)?n.indexOf(`@`,1):n.indexOf(`@`);I>0&&(F=n.slice(0,I)),t[F]=S}if(Object.keys(t).length>0){let n=S.get(N)??{};S.set(N,{...n,...t})}continue}ge.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(t.overrides,`overrides`),merge(t.resolutions,`resolutions`),!(Object.keys(n).length===0&&S.size===0))return{global:n,scoped:S}}function scopedOverrideFor(t,n,S){if(!S||S.scoped.size===0)return;let C=[t.name,t.relativeLocation];for(let t of C){let C=S.scoped.get(t);if(C?.[n])return C[n]}}function buildBinShim(t,n,S,C=[],N=process.platform,F=t){let I=n?zn(t,n):null,H=S?zn(t,S):null,W=buildNativeEnvPreamble(F,C,{platform:N});if(I&&H){let t=N===`darwin`||N===`win32`,n=`if command -v gjs >/dev/null 2>&1 && [ -f "${H}" ]; then\n${W}exec gjs -m "${H}" "$@"\nfi\nexec node "${I}" "$@"\n`,S=`if command -v node >/dev/null 2>&1 && [ -f "${I}" ]; then\nexec node "${I}" "$@"\nfi\n${W}exec gjs -m "${H}" "$@"\n`;return`#!/bin/sh
1247
+ `}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var VG,HG,UG,WG=__esmMin(()=>{af(),Xn(),hG(),CU(),VG=`app.tar.gz`,HG=`linux-tar-flatpak`,UG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${GG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${GG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${GG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var GG,KG,qG=__esmMin(()=>{_e(),af(),Xn(),_R(),KI(),WG(),CW(),GG=`[gjsify flatpark]`,KG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${GG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${GG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${GG} ${t.arch}: ${t.url}`);ge.log(`${GG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var JG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return YG===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===QG&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[QG];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,QG,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
1248
+ `)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,YG)};for(let t=0;t<Math.min(32,S.length);t++)F.push((async()=>{for(;;){let t=C++;if(t>=S.length)return;let n=S[t];if(!n)return;await wireOne(n.linkPath,n.relTarget)}})());await Promise.all(F),ge.log(`gjsify install: wired ${q.length} workspace symlink(s)`)}let n=zn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=zn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(Hn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,YG),S++)}S>0&&ge.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let X=C.find(n=>n.location===t)?.manifest,Z=extractOverrides(X),te=Z?.global,ne=new Map,re=new Set;if(Z&&Z.scoped.size>0){for(let t of F?.workspaces??C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){let C=scopedOverrideFor(t,n,Z);if(!C)continue;let N=C,F=t.location,I=ne.get(F);I||(I=new Set,ne.set(F,I)),I.add(`${n}@${N}`),re.add(`${n}@${S}`)}}}let t=new Set;for(let n of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(n,S,Z)||t.add(`${S}@${N}`)}for(let n of re)t.has(n)||H.delete(n);ne.size>0&&ge.log(`gjsify install: ${ne.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(H.size>0){let I=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1});await installPackages({prefix:t,specs:[...H],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],overrides:te,signal:S,progress:I,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,specOrigins:new Map([...W].map(([t,n])=>[t,[...n]])),optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest)),focusSpecs:F?.specs})}else n.verbose&&ge.log(`gjsify install: no external deps to fetch`);for(let[t,F]of ne){if(F.size===0)continue;let I=C.find(n=>n.location===t)?.name??t;n.verbose&&ge.log(`gjsify install: ${I} — installing ${F.size} scoped-override spec(s) into ${t}/node_modules/`),await installPackages({prefix:t,specs:[...F],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,signal:S,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest))})}await wireWorkspaceSymlinks(),reportRewiredDevLinks(Y);let ie=writeWorkspaceBinShims(t,F?.workspaces??C);ie>0&&ge.log(`gjsify install: linked ${ie} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(t,n){let S=zn(t,`node_modules`,`.bin`),C=detectNativePackages(t).map(t=>t.prebuildsDir),N=0;for(let F of n){let n=F.manifest,I=n.gjsify?.bin,H=n.bin,W=mergeWorkspaceBins(F.name,I,H);if(W.size!==0){mkdirSync(S,{recursive:!0});for(let[n,{nodeTarget:I,gjsTarget:H}]of W){let W=zn(S,n);for(let t of[W,`${W}.cmd`,`${W}.ps1`])try{rmSync(t,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(W,buildBinShim(F.location,I,H,C,process.platform,t),{mode:493}),chmodSync(W,493),process.platform===`win32`)for(let[t,n]of Object.entries(buildWorkspaceBinShimsForWindows(F.location,I,H,C)))writeFileSync(`${W}.${t}`,n,{mode:493});N++}}}return N}function extractOverrides(t){if(!t)return;let n={},S=new Map,merge=(t,C)=>{if(t){for(let[N,F]of Object.entries(t))if(!N.startsWith(`_`)){if(typeof F==`string`){let t=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(t=N.slice(0,S)),n[t]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let t={};for(let[n,S]of Object.entries(F)){if(n.startsWith(`_`))continue;if(typeof S!=`string`){ge.warn(`gjsify install: ${C}["${N}"]["${n}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=n,I=n.startsWith(`@`)?n.indexOf(`@`,1):n.indexOf(`@`);I>0&&(F=n.slice(0,I)),t[F]=S}if(Object.keys(t).length>0){let n=S.get(N)??{};S.set(N,{...n,...t})}continue}ge.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(t.overrides,`overrides`),merge(t.resolutions,`resolutions`),!(Object.keys(n).length===0&&S.size===0))return{global:n,scoped:S}}function scopedOverrideFor(t,n,S){if(!S||S.scoped.size===0)return;let C=[t.name,t.relativeLocation];for(let t of C){let C=S.scoped.get(t);if(C?.[n])return C[n]}}function buildBinShim(t,n,S,C=[],N=process.platform,F=t){let I=n?zn(t,n):null,H=S?zn(t,S):null,W=buildNativeEnvPreamble(F,C,{platform:N});if(I&&H){let t=N===`darwin`||N===`win32`,n=`if command -v gjs >/dev/null 2>&1 && [ -f "${H}" ]; then\n${W}exec gjs -m "${H}" "$@"\nfi\nexec node "${I}" "$@"\n`,S=`if command -v node >/dev/null 2>&1 && [ -f "${I}" ]; then\nexec node "${I}" "$@"\nfi\n${W}exec gjs -m "${H}" "$@"\n`;return`#!/bin/sh
1249
1249
  `+(t?S:n)}if(I)return`#!/bin/sh\nexec node "${I}" "$@"\n`;if(H)return`#!/bin/sh\n${W}exec gjs -m "${H}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(t,n,S,C=[]){let N=n?zn(t,n):null,F=S?zn(t,S):null;if(N)return buildLauncherShims({interpreter:`node`,target:N});if(F){let t=C.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:F,prependEnv:C.length===0?{}:{GI_TYPELIB_PATH:t,PATH:t}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(t,n,S){let C=new Map,N=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t,get=t=>{let n=C.get(t);return n||(n={},C.set(t,n)),n};if(typeof S==`string`)get(N).nodeTarget=S;else if(S&&typeof S==`object`)for(let[t,n]of Object.entries(S))typeof n==`string`&&n.length>0&&(get(t).nodeTarget=n);if(typeof n==`string`)get(N).gjsTarget=n;else if(n&&typeof n==`object`)for(let[t,S]of Object.entries(n))typeof S==`string`&&S.length>0&&(get(t).gjsTarget=S);return C}async function projectInstallViaNpm(t){let n=[`install`];t[`save-dev`]&&n.push(`--save-dev`),t[`save-peer`]&&n.push(`--save-peer`),t[`save-optional`]&&n.push(`--save-optional`),t.verbose&&n.push(`--loglevel`,`verbose`),t.packages&&t.packages.length>0&&n.push(...t.packages),await spawnNpm(n)}async function spawnNpm(t){return spawnToCompletion(`npm`,t,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:t})=>{if(t!==0)throw Error(`npm install exited with code ${t}`)}).catch(t=>{let n=t.code;ge.error(n===void 0?t.message:`npm install failed: ${t.message}`),process.exit(1)})}async function installGlobalAndLink(t,n){let S=defaultGlobalLayout();mkdirSync(S.prefix,{recursive:!0}),ge.log(`gjsify install --global → ${S.prefix}`),ge.log(` bins → ${S.binDir}`);let C=await acquireInstallLock(S.prefix,{});try{let C=await installPackages({prefix:S.prefix,specs:t,verbose:n.verbose}),N=t.map(specToPackageName);if(N.includes(`@gjsify/cli`)){let t=C.installed.find(t=>t.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(S.prefix,t,{verbose:n.verbose})}n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(N,S),S.binDir)}finally{C.release()}}function pruneProjectPrefix(t){t.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:t.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(t,n){if(t.length===0)ge.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ge.log(`\nLinked ${t.length} bin(s):`);for(let n of t)ge.log(` • ${n.link} → ${n.target}`)}t.length>0&&!binDirOnPath(n)&&ge.warn(`\nNote: ${n} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${n}:$PATH"`)}async function ensureProjectGjsEngine(t,n,S={}){let C=S.cwd??process.cwd(),N=S.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${qz} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
1250
1250
  gjsify install ${qz}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let F=readCliVersionFrom(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ge.log(`\n${qz} is missing and this host can run gjs, so \`gjsify build\` would have no\n bundler engine (there is no npm \`rolldown\` fallback under GJS). Installing the GJS engine set at\n ${F}, in lockstep with the CLI.`),await(S.installFn??installGjsEnginePackages)(C,F,{verbose:t.verbose})}async function runPostInstallChecks(t){ge.log(`
1251
1251
  --- gjsify post-install checks ---`);let n=runMinimalChecks(),S=n.filter(t=>!t.found&&t.severity===`required`);if(S.length>0){ge.warn(`Missing required system dependencies:
@@ -1257,27 +1257,27 @@ jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
1257
1257
  A bridge lost that way is silently absent from the next build rather than
1258
1258
  reported, so the first symptom can be an unrelated-looking bundler error
1259
1259
  (\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
1260
- install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(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 qG,JG,YG,XG,ZG=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),KG(),GI(),dL(),gL(),NR(),Gz(),ZR(),gz(),UR(),hv(),qI(),jV(),Yz(),Az(),Mz(),YR(),Fz(),qG=process.platform===`win32`?`junction`:void 0,JG=18e5,YG={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:JG}).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)}}},XG=`@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 QG,$G,eK=__esmMin(()=>{_e(),af(),Xn(),Fz(),QG={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 uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",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=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${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} → ${Bn(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: ${Nz} 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 ${Nz} 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`.")}},$G={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 ${Nz}).`);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 ${Nz} 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(`
1261
- `)+`\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 ${Nz} 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(()=>(FX(),PX));await Y([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var tK=__esmMin(()=>{af(),Xn(),fP(),Ch()});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 nK){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of nK){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},rK).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(`
1262
- `)),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(),iK).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,nK.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&&nK.delete(N)}}var nK,rK,iK,aK,oK=__esmMin(()=>{_e(),hv(),sz(),o_(),GI(),qI(),tK(),cB(),TR(),fB(),hB(),nK=new Set,rK=5e3,iK=15e3,aK={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=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(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(Jn),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 sK=__esmMin(()=>{Xn(),hv(),qI()});async function packWorkspace(t,n={}){let S=zn(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))+`
1260
+ install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(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 YG,XG,ZG,QG,$G=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),JG(),GI(),dL(),gL(),NR(),Gz(),ZR(),gz(),UR(),hv(),qI(),jV(),Yz(),Az(),Mz(),YR(),Fz(),YG=process.platform===`win32`?`junction`:void 0,XG=18e5,ZG={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:XG}).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)}}},QG=`@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 eK,tK,nK=__esmMin(()=>{_e(),af(),Xn(),Fz(),eK={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 uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",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=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${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} → ${Bn(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: ${Nz} 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 ${Nz} 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`.")}},tK={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 ${Nz}).`);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 ${Nz} 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(`
1261
+ `)+`\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 ${Nz} 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(()=>(VX(),BX));await Y([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var rK=__esmMin(()=>{af(),Xn(),fP(),Ch()});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 iK){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of iK){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},aK).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(`
1262
+ `)),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(),oK).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,iK.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&&iK.delete(N)}}var iK,aK,oK,sK,cK=__esmMin(()=>{_e(),hv(),sz(),o_(),GI(),qI(),rK(),cB(),TR(),fB(),hB(),iK=new Set,aK=5e3,oK=15e3,sK={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=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(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(Jn),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 lK=__esmMin(()=>{Xn(),hv(),qI()});async function packWorkspace(t,n={}){let S=zn(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))+`
1263
1263
  `,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(zn(t,n)));let C=statSync(zn(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?In(n.destination):t,ce=zn(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(zn(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=zn(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(`
1264
1264
  `)+`
1265
- Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(lK.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=n?`${n}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(t,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(t,n){let S=new Set,C=null;for(let N of n){let n=N.replace(/^\.\//,``).replace(/\/$/,``);if(!n)continue;if(!/[*?[\]]/.test(n)){let C=zn(t,n);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(t,n))S.add(C);else N.isFile()&&S.add(n);continue}C??=walkAll(t);let F=filesGlobToRegExp(n),I=filesGlobToRegExp(`${n}/**`);for(let t of C)(F.test(t)||I.test(t))&&S.add(t)}return[...S]}function filesGlobToRegExp(t){let n=`^`;for(let S=0;S<t.length;S++){let C=t[S];if(C===`*`)t[S+1]===`*`?(n+=`.*`,S++,t[S+1]===`/`&&S++):n+=`[^/]*`;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(t[C]===`!`&&(N+=`^`,C++);C<t.length&&t[C]!==`]`;C++)N+=t[C];C<t.length?(n+=`${N}]`,S=C):n+=`\\[`}else".+^${}()|\\]".includes(C)?n+=`\\${C}`:n+=C}return RegExp(`${n}$`)}function loadIgnore(t){let n=zn(t,`.npmignore`),S=zn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
1266
- `);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of uK){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=zn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=In(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of uK){let n=N[t];if(n)for(let[F,I]of Object.entries(n)){if(typeof I!=`string`||!I.startsWith(`workspace:`))continue;let H=C.get(F);if(!H)throw Error(`gjsify pack: ${N.name} declares ${I} on ${F} (${t}) but no sibling workspace with that name exists in the monorepo at ${S}`);let W=I.slice(10);W===`*`||W===``?n[F]=H:W===`^`||W===`~`?n[F]=`${W}${H}`:n[F]=W}}return N}function indentOf(t){let n=t.match(/\n([ \t]+)"/);return n?n[1]:` `}var cK,lK,uK,dK=__esmMin(()=>{af(),gl(),Xn(),oz(),GI(),qI(),KI(),sK(),cK={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(In(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},lK=new Set([`.git`,`.svn`,`.hg`,`.gitignore`,`.gitattributes`,`.npmrc`,`CVS`,`.DS_Store`,`node_modules`,`.npmignore`,`package-lock.json`,`gjsify-lock.json`,`yarn.lock`,`yarn-error.log`,`.yarn`,`.pnp.cjs`,`.pnp.loader.mjs`,`tsconfig.tsbuildinfo`]),uK=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function parseRetryAfter(t,n=Date.now()){if(!t)return;let S=t.trim();if(/^\d+(?:\.\d+)?$/.test(S))return Math.round(Number(S)*1e3);let C=Date.parse(S);return Number.isNaN(C)?void 0:Math.max(0,C-n)}function retryDelayMs(t,n,S){let C=parseRetryAfter(S);return Math.min(C??n*2**t,pK)}async function fetchWithTransientRetry(t,n={}){let S=n.retries??5,C=n.baseMs??2e3,N=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),F=n.random??Math.random;for(let I=0;;I++){let H,W;try{H=await t()}catch(t){W=t}if(H&&!isTransientStatus(H.status))return{response:H,retried:I};if(I>=S){if(H)return{response:H,retried:I};throw W}let q=H?.headers.get(`retry-after`),Y=retryDelayMs(I,C,q),X=parseRetryAfter(q)===void 0?Math.round(Y*(.5+.5*F())):Y,Z=H?`${H.status} ${H.statusText}`:`network error: ${W instanceof Error?W.message:String(W)}`;n.log?.(`transient ${Z} (attempt ${I+1}/${S+1}), retrying in ${X}ms`),await N(X)}}var fK,isTransientStatus,pK,mK=__esmMin(()=>{fK=new Set([408,425,429,500,502,503,504]),isTransientStatus=t=>fK.has(t),pK=3e4});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n,S={}){let C=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,N=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!C||!N)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let F=`${C}${C.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I;try{({response:I}=await fetchWithTransientRetry(()=>fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}}),{...retryOptions(S),log:n&&(t=>n(`gjsify oidc: id_token ${t}`))}))}catch(t){throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: network error — ${t instanceof Error?t.message:String(t)}`,`fetch-id-token`)}if(!I.ok){let t=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let H=await I.json().catch(()=>({}));if(!H.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return H.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I,H;try{({response:I,retried:H}=await fetchWithTransientRetry(()=>fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`}),{...retryOptions(t),log:N&&(t=>N(`gjsify oidc: ${t} for ${n}`))}))}catch(t){throw new OidcExchangeError(`npm OIDC token exchange network error for ${n}: ${t instanceof Error?t.message:String(t)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await I.text().catch(()=>``);if(!I.ok)throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${I.status} ${I.statusText} — ${W.slice(0,300)}${H?` (after ${H} retries)`:``}`,I.status,W,n,decodeJwtPayload(C)??void 0);let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,I.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,I.status,W,n,decodeJwtPayload(C)??void 0);return q.token}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log,t);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var retryOptions,OidcUnavailableError,OidcExchangeError,hK,gK=__esmMin(()=>{mK(),retryOptions=t=>({retries:t.maxRetries??5,baseMs:t.retryBaseMs??2e3,sleep:t.sleep,random:t.random}),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}},hK="Trust entries are stored but the OIDC exchange is only verifiable in CI: run `gh workflow run release.yml --ref main -f verify_only=true -f skip_publish=true` and check for ✗ lines."});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
1265
+ Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(dK.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=n?`${n}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(t,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(t,n){let S=new Set,C=null;for(let N of n){let n=N.replace(/^\.\//,``).replace(/\/$/,``);if(!n)continue;if(!/[*?[\]]/.test(n)){let C=zn(t,n);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(t,n))S.add(C);else N.isFile()&&S.add(n);continue}C??=walkAll(t);let F=filesGlobToRegExp(n),I=filesGlobToRegExp(`${n}/**`);for(let t of C)(F.test(t)||I.test(t))&&S.add(t)}return[...S]}function filesGlobToRegExp(t){let n=`^`;for(let S=0;S<t.length;S++){let C=t[S];if(C===`*`)t[S+1]===`*`?(n+=`.*`,S++,t[S+1]===`/`&&S++):n+=`[^/]*`;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(t[C]===`!`&&(N+=`^`,C++);C<t.length&&t[C]!==`]`;C++)N+=t[C];C<t.length?(n+=`${N}]`,S=C):n+=`\\[`}else".+^${}()|\\]".includes(C)?n+=`\\${C}`:n+=C}return RegExp(`${n}$`)}function loadIgnore(t){let n=zn(t,`.npmignore`),S=zn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
1266
+ `);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of fK){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=zn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=In(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of fK){let n=N[t];if(n)for(let[F,I]of Object.entries(n)){if(typeof I!=`string`||!I.startsWith(`workspace:`))continue;let H=C.get(F);if(!H)throw Error(`gjsify pack: ${N.name} declares ${I} on ${F} (${t}) but no sibling workspace with that name exists in the monorepo at ${S}`);let W=I.slice(10);W===`*`||W===``?n[F]=H:W===`^`||W===`~`?n[F]=`${W}${H}`:n[F]=W}}return N}function indentOf(t){let n=t.match(/\n([ \t]+)"/);return n?n[1]:` `}var uK,dK,fK,pK=__esmMin(()=>{af(),gl(),Xn(),oz(),GI(),qI(),KI(),lK(),uK={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(In(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},dK=new Set([`.git`,`.svn`,`.hg`,`.gitignore`,`.gitattributes`,`.npmrc`,`CVS`,`.DS_Store`,`node_modules`,`.npmignore`,`package-lock.json`,`gjsify-lock.json`,`yarn.lock`,`yarn-error.log`,`.yarn`,`.pnp.cjs`,`.pnp.loader.mjs`,`tsconfig.tsbuildinfo`]),fK=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function parseRetryAfter(t,n=Date.now()){if(!t)return;let S=t.trim();if(/^\d+(?:\.\d+)?$/.test(S))return Math.round(Number(S)*1e3);let C=Date.parse(S);return Number.isNaN(C)?void 0:Math.max(0,C-n)}function retryDelayMs(t,n,S){let C=parseRetryAfter(S);return Math.min(C??n*2**t,hK)}async function fetchWithTransientRetry(t,n={}){let S=n.retries??5,C=n.baseMs??2e3,N=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),F=n.random??Math.random;for(let I=0;;I++){let H,W;try{H=await t()}catch(t){W=t}if(H&&!isTransientStatus(H.status))return{response:H,retried:I};if(I>=S){if(H)return{response:H,retried:I};throw W}let q=H?.headers.get(`retry-after`),Y=retryDelayMs(I,C,q),X=parseRetryAfter(q)===void 0?Math.round(Y*(.5+.5*F())):Y,Z=H?`${H.status} ${H.statusText}`:`network error: ${W instanceof Error?W.message:String(W)}`;n.log?.(`transient ${Z} (attempt ${I+1}/${S+1}), retrying in ${X}ms`),await N(X)}}var mK,isTransientStatus,hK,gK=__esmMin(()=>{mK=new Set([408,425,429,500,502,503,504]),isTransientStatus=t=>mK.has(t),hK=3e4});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n,S={}){let C=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,N=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!C||!N)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let F=`${C}${C.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I;try{({response:I}=await fetchWithTransientRetry(()=>fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}}),{...retryOptions(S),log:n&&(t=>n(`gjsify oidc: id_token ${t}`))}))}catch(t){throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: network error — ${t instanceof Error?t.message:String(t)}`,`fetch-id-token`)}if(!I.ok){let t=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let H=await I.json().catch(()=>({}));if(!H.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return H.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I,H;try{({response:I,retried:H}=await fetchWithTransientRetry(()=>fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`}),{...retryOptions(t),log:N&&(t=>N(`gjsify oidc: ${t} for ${n}`))}))}catch(t){throw new OidcExchangeError(`npm OIDC token exchange network error for ${n}: ${t instanceof Error?t.message:String(t)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await I.text().catch(()=>``);if(!I.ok)throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${I.status} ${I.statusText} — ${W.slice(0,300)}${H?` (after ${H} retries)`:``}`,I.status,W,n,decodeJwtPayload(C)??void 0);let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,I.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,I.status,W,n,decodeJwtPayload(C)??void 0);return q.token}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log,t);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var retryOptions,OidcUnavailableError,OidcExchangeError,_K,vK=__esmMin(()=>{gK(),retryOptions=t=>({retries:t.maxRetries??5,baseMs:t.retryBaseMs??2e3,sleep:t.sleep,random:t.random}),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}},_K="Trust entries are stored but the OIDC exchange is only verifiable in CI: run `gh workflow run release.yml --ref main -f verify_only=true -f skip_publish=true` and check for ✗ lines."});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
1267
1267
  `)}function formatLiveToken404(t,n,S){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`Authenticated as: ${S}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${t} is not (yet) on npmjs.com. Two cases:`,``,` 1. First publish of a brand-new scoped package — do the one-time bootstrap`,` (see AGENTS.md > "New @gjsify/* package: first-publish + Trusted`,` Publisher bootstrap"). The npm registry can also 404 *transiently*`,` while provisioning a brand-new package: simply re-run, or do the very`," first publish with `npm publish` (then configure the Trusted Publisher)."," 2. You lack publish access to the scope — verify with `npm access ls-packages`."].join(`
1268
- `)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var _K=__esmMin(()=>{xh()});function backoffFor(t){return vK[Math.min(Math.max(t,0),vK.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,yK))}function budgetForPayload(t,n){if(t<6e5||n<=xK)return t;let S=(n-xK)/(1024*1024);return t+Math.ceil(S)*SK}function cacheBustedUrl(t,n){return`${t}${t.includes(`?`)?`&`:`?`}__gjsify_readback=${encodeURIComponent(n)}`}async function verifyPublishedVersion(t){let{registry:n,name:S,version:C,budgetMs:N}=t,F=t.fetchImpl??((...t)=>globalThis.fetch(...t)),I=t.sleep??(t=>new Promise(n=>setTimeout(n,t))),H=t.now??(()=>Date.now()),W=t.probeTimeoutMs??3e4,q=`${n.endsWith(`/`)?n.slice(0,-1):n}/${escapePackageName(S)}`,Y=H(),X=0,Z={state:`error`,detail:`no probe was sent`};for(let n=0;X++,Z=await probeOnce({url:q,version:C,doFetch:F,probeTimeoutMs:probeTimeoutFor(W,N-(H()-Y)),authorization:t.authorization,nonce:`${Y}-${X}`}),t.log?.(`gjsify publish: read-back probe ${X} of ${S}@${C} → ${Z.state}`+(Z.state===`present`?``:` (${Z.detail})`)),Z.state!==`present`;n++){let t=N-(H()-Y);if(t<=0)break;await I(Math.min(backoffFor(n),t))}let te={attempts:X,elapsedMs:H()-Y,url:q,last:Z};if(Z.state===`present`)return{...te,confirmed:!0,verdict:`confirmed`,verdictDetail:`${q} serves ${C} with a tarball`};if(Z.state===`error`)return{...te,confirmed:!1,verdict:`unknown`,verdictDetail:`the read-back could not reach a verdict — ${Z.detail}`};let ne=await probeRegistryRecord({url:q,version:C,doFetch:F,probeTimeoutMs:W,authorization:t.authorization,nonce:`${Y}-record`});return t.log?.(`gjsify publish: read-back record probe of ${S}@${C} → ${ne.state} (${ne.detail})`),ne.state===`recorded`?{...te,confirmed:!1,verdict:`recorded-not-served`,verdictDetail:ne.detail,recordedAt:ne.recordedAt}:ne.state===`no-record`?{...te,confirmed:!1,verdict:`not-published`,verdictDetail:ne.detail}:{...te,confirmed:!1,verdict:`unknown`,verdictDetail:ne.detail}}async function probeRegistryRecord(t){let{url:n,version:S,doFetch:C,probeTimeoutMs:N}=t,F=new AbortController,I=setTimeout(()=>F.abort(),N),H;try{H=await C(cacheBustedUrl(n,t.nonce),{headers:{"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},signal:F.signal})}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record was unreadable (${t instanceof Error?t.message:String(t)})`}}finally{clearTimeout(I)}if(H.status===404)return{state:`no-record`,detail:`the registry has no packument for this name at all (404)`};if(!H.ok)return{state:`unknown`,detail:`the registry serves no ${S} and its own record answered ${H.status} ${H.statusText}`};let W;try{W=await H.json()}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record is not JSON (${t instanceof Error?t.message:String(t)})`}}let q=W?.time,Y=q&&typeof q==`object`?q[S]:void 0;return typeof Y==`string`&&Y.length>0?{state:`recorded`,recordedAt:Y,detail:`the registry RECORDS ${S} at ${Y} and its install document does not serve it`}:{state:`no-record`,detail:`the registry has no record of ${S} — neither in its install document nor in its own \`time\` map`}}async function sendPackumentRequest(t){let{url:n,doFetch:S,probeTimeoutMs:C}=t,N={accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},send=async t=>{let n=new AbortController,F=setTimeout(()=>n.abort(),C);try{return await S(t,{headers:N,signal:n.signal})}finally{clearTimeout(F)}},F;try{F=await send(cacheBustedUrl(n,t.nonce)),!F.ok&&F.status!==404&&F.status>=400&&F.status<500&&(F=await send(n))}catch(t){return{error:`request failed (${t instanceof Error?t.message:String(t)})`}}return F}async function probeOnce(t){let{version:n}=t,S=await sendPackumentRequest(t);if(`error`in S)return{state:`error`,detail:S.error};let C=S;if(C.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!C.ok)return{state:`error`,status:C.status,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`error`,status:C.status,detail:`packument is not JSON (${n})`}}let F=N?.versions,I=F&&typeof F==`object`?Object.keys(F):[],H=F&&typeof F==`object`&&Object.hasOwn(F,n)?F[n]:void 0;if(!H){let t=I.length>0?I[I.length-1]:`(none)`;return{state:`absent`,status:C.status,detail:`packument carries ${I.length} version(s), newest ${t} — ${n} is not among them`}}let W=H.dist?.tarball;return typeof W!=`string`||W.length===0?{state:`absent`,status:C.status,detail:`packument has ${n} but its \`dist.tarball\` is missing`}:{state:`present`,status:C.status,tarball:W}}function formatUnconfirmedPublish(t){let{name:n,version:S,putUrl:C,putStatus:N,putStatusText:F,payloadBytes:I,readback:H}=t,W=t.claim??`accepted`,q=(H.elapsedMs/1e3).toFixed(1),Y=H.last.state===`present`?`served`:H.last.detail,X=W===`already-published`?`npm says ${S} is ALREADY PUBLISHED`:`npm ACCEPTED the upload`,Z=H.verdict===`unknown`?H.last.state===`absent`?`${X}; its install document does not serve ${S} and the registry's own record could NOT be read.`:`${X} and the read-back could NOT establish whether the registry serves it.`:H.verdict===`recorded-not-served`?`${X}; the registry RECORDS ${S} and its install document does not serve it.`:`${X} and the registry has no record of ${S}.`,te=H.verdict===`unknown`?[` This is NOT a report that the publish failed, and it is not one that it worked. The read-back`,` reached no answer it could act on, so the version may or may not be installable — confirm it`," before releasing anything that depends on it (`npm view <name>@<version> dist.tarball`)."]:H.verdict===`recorded-not-served`?[` Do NOT re-publish: the registry holds the write, so a re-run is answered 409 and changes`,` nothing. The document npm installs from is behind the registry's own record — measured on`,` the ts-for-gir v5.1.0 release, @ts-for-gir/reporter was recorded at 21:43:00.983Z and a`,` cache-busted read of its install document still did not carry 5.1.0 ~40 min later. Wait and`,` re-read; if it persists, check https://status.npmjs.org/.`]:W===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it:`,` in the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and`,` the registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it`," cannot fix this — wait and re-read (`npm view <name>@<version>`), or check",` https://status.npmjs.org/.`]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${n}@${S} — ${Z}`,` PUT ${C} (${I} bytes) → ${N} ${F}`,` read-back GET ${H.url} (accept: application/vnd.npm.install-v1+json, per-probe cache buster)`,` answered ${H.last.state}: ${Y}`,` after ${H.attempts} probe(s) over ${q}s`,` verdict ${H.verdict} — ${H.verdictDetail}`,...te].join(`
1269
- `)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++CK}`});if(`error`in S)return{state:`unknown`,detail:S.error};if(S.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!S.ok)return{state:`unknown`,status:S.status,detail:`${S.status} ${S.statusText}`};let C;try{C=await S.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`unknown`,status:S.status,detail:`packument is not JSON (${n})`}}let N=C?.versions,F=N&&typeof N==`object`?Object.keys(N).length:0;return F===0?{state:`unknown`,status:S.status,detail:`a 200 carrying no versions establishes nothing`}:{state:`present`,status:S.status,versions:F}}var vK,yK,bK,xK,SK,CK,wK=__esmMin(()=>{Ch(),vK=[2e3,4e3,8e3,15e3,3e4],yK=2e3,bK=6e5,xK=32*1024*1024,SK=1e4,CK=0});function collectWorkspacePins(t,n){let S=[];for(let C of TK){let N=depsOf(t,C),F=depsOf(n,C);for(let[t,n]of Object.entries(N))typeof n!=`string`||!n.startsWith(`workspace:`)||S.push({name:t,spec:F[t]??n,block:C})}return S}var TK,EK,depsOf,DK=__esmMin(()=>{TK=[`dependencies`,`optionalDependencies`,`peerDependencies`],EK=`dependencies`,depsOf=(t,n)=>{let S=t[n];return S&&typeof S==`object`?S:{}}});function statusTokenFromEnv(t){for(let n of[t.NPM_STATUS_TOKEN,t.NODE_AUTH_TOKEN]){let t=n?.trim();if(t&&!/^X+(-X+)+$/.test(t))return t}}async function fetchVersionStatus(t){if(!t.token)return{state:`unavailable`,reason:`no-credential`,detail:`the status endpoint needs an npm access token (set NPM_STATUS_TOKEN); OIDC publish tokens are not accepted`};let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/-/package/${escapePackageName(t.name)}/version/${encodeURIComponent(t.version)}/status`,C;try{C=await n(S,{headers:{accept:`application/json`,authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(t.probeTimeoutMs??3e4)})}catch(t){return{state:`unavailable`,reason:`error`,detail:t instanceof Error?t.message:String(t)}}if(C.status===401)return{state:`unavailable`,reason:`rejected`,detail:`401 — the token is missing, invalid or expired`};if(C.status===403)return{state:`unavailable`,reason:`not-enabled`,detail:`403 — package version status is not enabled for this package`};if(C.status===404)return{state:`unavailable`,reason:`not-found`,detail:`404 — no such version, or the token cannot see this package`};if(!C.ok)return{state:`unavailable`,reason:`error`,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){return{state:`unavailable`,reason:`error`,detail:`status body is not JSON (${t instanceof Error?t.message:String(t)})`}}let F=N?.status;return typeof F!=`string`||!OK.includes(F)?{state:`unavailable`,reason:`error`,detail:`unrecognised status ${JSON.stringify(F)}`}:{state:`known`,status:F}}function isTerminalClass(t){return t!==`validating`&&t!==`published-lagging`&&t!==`unchecked`}function whyUnchecked(t){return t.reason===`no-credential`?`status endpoint not asked: no NPM_STATUS_TOKEN`:t.detail}function classifyUnserved(t,n){if(n.state===`known`)switch(n.status){case`validating`:return{cls:`validating`,detail:`npm accepted the upload and its automated review has not finished`,terminal:!1};case`staged`:return{cls:`staged`,detail:`awaiting maintainer approval on npm`,terminal:!0};case`blocked`:return{cls:`blocked`,detail:`failed npm automated validation`,terminal:!0};case`deleted`:return{cls:`deleted`,detail:`deleted on npm`,terminal:!0};case`published`:return{cls:`published-lagging`,detail:`npm reports it published; the install document does not serve it yet`,terminal:!1}}return n.reason===`not-found`?{cls:`missing`,detail:`the registry has no such version (${n.detail}); the PUT did not land`,terminal:!0}:{cls:`unchecked`,detail:`not served (read-back: ${t}); ${whyUnchecked(n)}`,terminal:!1}}function describeClass(t){switch(t){case`validating`:return`validating (npm automated review pending)`;case`staged`:return`staged (needs maintainer approval)`;case`blocked`:return`blocked (failed automated validation)`;case`deleted`:return`deleted`;case`published-lagging`:return`published, not yet served`;case`missing`:return`missing (never recorded)`;case`unchecked`:return`not served (status not checked)`}}var OK,kK=__esmMin(()=>{Ch(),OK=[`published`,`validating`,`staged`,`blocked`,`deleted`]});function appendLedger(t,n){t&&appendFileSync(t,`${JSON.stringify(n)}\n`)}function readLedger(t){if(!t||!existsSync(t))return[];let n=[];for(let S of readFileSync(t,`utf-8`).split(`
1270
- `))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:jK});if(I.confirmed)return confirmedServed(t,N,n,S);let ask=()=>fetchVersionStatus({registry:t.registry,name:n,version:S,token:t.statusToken,fetchImpl:t.fetchImpl}),H=classifyUnserved(I.verdict,await ask());if(!H.terminal&&t.waitBudgetMs>0){if(I=await verifyPublishedVersion({...F,budgetMs:t.waitBudgetMs}),I.confirmed)return confirmedServed(t,N,n,S);H=classifyUnserved(I.verdict,await ask())}return{...C,cls:H.cls,detail:H.detail}}function confirmedServed(t,n,S,C){return n?.ev===`unserved`&&appendLedger(t.ledgerPath,{ev:`served`,name:S,version:C}),null}function summariseReasons(t){return t.map(t=>`${t.name}@${t.version} is ${t.cls===`held`?`held`:describeClass(t.cls)}`).join(`; `)}async function recordUnserved(t){let n=await fetchVersionStatus({registry:t.registry,name:t.name,version:t.version,token:t.statusToken,fetchImpl:t.fetchImpl}),S=classifyUnserved(t.verdict,n);return appendLedger(t.ledgerPath,{ev:`unserved`,name:t.name,version:t.version,cls:S.cls,detail:S.detail}),S}function pendingEntries(t){let n=new Map;for(let S of t)n.set(`${S.name}@${S.version}`,S);let S=[...n.values()];return{unserved:S.filter(t=>t.ev===`unserved`),held:S.filter(t=>t.ev===`held`)}}function markHeldPublished(t,n,S){[...readLedger(t)].reverse().find(t=>t.name===n&&t.version===S)?.ev===`held`&&appendLedger(t,{ev:`served`,name:n,version:S})}async function settleUnserved(t){let n=pendingEntries(t.entries).unserved.filter(t=>!isTerminalClass(t.cls));return(await Promise.all(n.map(async n=>{if((await verifyPublishedVersion({registry:t.registryFor(n.name),name:n.name,version:n.version,budgetMs:t.budgetMs,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log})).confirmed)return appendLedger(t.ledgerPath,{ev:`served`,name:n.name,version:n.version}),`${n.name}@${n.version}`}))).filter(t=>t!==void 0)}function renderLedgerSummary(t,n){let{unserved:S,held:C}=pendingEntries(t);if(S.length===0&&C.length===0)return;let N=[`### npm versions that were accepted but are not installable`,``];if(S.length>0){N.push(`| Package | Version | State | Detail |`,`| --- | --- | --- | --- |`);for(let t of S)N.push(`| \`${t.name}\` | ${t.version} | ${describeClass(t.cls)} | ${t.detail} |`);N.push(``)}if(C.length>0){N.push(`### Held — NOT published in this run`,``,`Each package below depends on a version npm does not serve, so publishing it would have shipped a package that cannot be installed.`,``,`| Package | Version | Because |`,`| --- | --- | --- |`);for(let t of C)N.push(`| \`${t.name}\` | ${t.version} | ${summariseReasons(t.reasons)} |`);N.push(``,"Once the dependencies above are served by npm (a `validating` version appears on its own, or is approved/released by a maintainer), publish the held set with:",``,"```sh",`gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${[...new Set(C.map(t=>t.name))].join(` `)}'`,"```"),S.some(t=>t.cls===`blocked`||t.cls===`deleted`)&&N.push(``,"A `blocked` or `deleted` version is a spent number: re-running the release cannot serve it, the package needs a version bump.")}return N.join(`
1271
- `)}var AK,jK,holdsPublish,MK=__esmMin(()=>{af(),DK(),wK(),kK(),AK=3e5,jK=1,holdsPublish=t=>t.block===EK});function beginPrompt(){NK++}function endPrompt(t=defaultWrite){if(NK=Math.max(0,NK-1),NK>0||PK.length===0)return;let n=PK.splice(0,PK.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(NK>0){PK.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var NK,PK,FK=__esmMin(()=>{NK=0,PK=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
1268
+ `)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var yK=__esmMin(()=>{xh()});function backoffFor(t){return bK[Math.min(Math.max(t,0),bK.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,xK))}function budgetForPayload(t,n){if(t<6e5||n<=CK)return t;let S=(n-CK)/(1024*1024);return t+Math.ceil(S)*wK}function cacheBustedUrl(t,n){return`${t}${t.includes(`?`)?`&`:`?`}__gjsify_readback=${encodeURIComponent(n)}`}async function verifyPublishedVersion(t){let{registry:n,name:S,version:C,budgetMs:N}=t,F=t.fetchImpl??((...t)=>globalThis.fetch(...t)),I=t.sleep??(t=>new Promise(n=>setTimeout(n,t))),H=t.now??(()=>Date.now()),W=t.probeTimeoutMs??3e4,q=`${n.endsWith(`/`)?n.slice(0,-1):n}/${escapePackageName(S)}`,Y=H(),X=0,Z={state:`error`,detail:`no probe was sent`};for(let n=0;X++,Z=await probeOnce({url:q,version:C,doFetch:F,probeTimeoutMs:probeTimeoutFor(W,N-(H()-Y)),authorization:t.authorization,nonce:`${Y}-${X}`}),t.log?.(`gjsify publish: read-back probe ${X} of ${S}@${C} → ${Z.state}`+(Z.state===`present`?``:` (${Z.detail})`)),Z.state!==`present`;n++){let t=N-(H()-Y);if(t<=0)break;await I(Math.min(backoffFor(n),t))}let te={attempts:X,elapsedMs:H()-Y,url:q,last:Z};if(Z.state===`present`)return{...te,confirmed:!0,verdict:`confirmed`,verdictDetail:`${q} serves ${C} with a tarball`};if(Z.state===`error`)return{...te,confirmed:!1,verdict:`unknown`,verdictDetail:`the read-back could not reach a verdict — ${Z.detail}`};let ne=await probeRegistryRecord({url:q,version:C,doFetch:F,probeTimeoutMs:W,authorization:t.authorization,nonce:`${Y}-record`});return t.log?.(`gjsify publish: read-back record probe of ${S}@${C} → ${ne.state} (${ne.detail})`),ne.state===`recorded`?{...te,confirmed:!1,verdict:`recorded-not-served`,verdictDetail:ne.detail,recordedAt:ne.recordedAt}:ne.state===`no-record`?{...te,confirmed:!1,verdict:`not-published`,verdictDetail:ne.detail}:{...te,confirmed:!1,verdict:`unknown`,verdictDetail:ne.detail}}async function probeRegistryRecord(t){let{url:n,version:S,doFetch:C,probeTimeoutMs:N}=t,F=new AbortController,I=setTimeout(()=>F.abort(),N),H;try{H=await C(cacheBustedUrl(n,t.nonce),{headers:{"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},signal:F.signal})}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record was unreadable (${t instanceof Error?t.message:String(t)})`}}finally{clearTimeout(I)}if(H.status===404)return{state:`no-record`,detail:`the registry has no packument for this name at all (404)`};if(!H.ok)return{state:`unknown`,detail:`the registry serves no ${S} and its own record answered ${H.status} ${H.statusText}`};let W;try{W=await H.json()}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record is not JSON (${t instanceof Error?t.message:String(t)})`}}let q=W?.time,Y=q&&typeof q==`object`?q[S]:void 0;return typeof Y==`string`&&Y.length>0?{state:`recorded`,recordedAt:Y,detail:`the registry RECORDS ${S} at ${Y} and its install document does not serve it`}:{state:`no-record`,detail:`the registry has no record of ${S} — neither in its install document nor in its own \`time\` map`}}async function sendPackumentRequest(t){let{url:n,doFetch:S,probeTimeoutMs:C}=t,N={accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},send=async t=>{let n=new AbortController,F=setTimeout(()=>n.abort(),C);try{return await S(t,{headers:N,signal:n.signal})}finally{clearTimeout(F)}},F;try{F=await send(cacheBustedUrl(n,t.nonce)),!F.ok&&F.status!==404&&F.status>=400&&F.status<500&&(F=await send(n))}catch(t){return{error:`request failed (${t instanceof Error?t.message:String(t)})`}}return F}async function probeOnce(t){let{version:n}=t,S=await sendPackumentRequest(t);if(`error`in S)return{state:`error`,detail:S.error};let C=S;if(C.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!C.ok)return{state:`error`,status:C.status,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`error`,status:C.status,detail:`packument is not JSON (${n})`}}let F=N?.versions,I=F&&typeof F==`object`?Object.keys(F):[],H=F&&typeof F==`object`&&Object.hasOwn(F,n)?F[n]:void 0;if(!H){let t=I.length>0?I[I.length-1]:`(none)`;return{state:`absent`,status:C.status,detail:`packument carries ${I.length} version(s), newest ${t} — ${n} is not among them`}}let W=H.dist?.tarball;return typeof W!=`string`||W.length===0?{state:`absent`,status:C.status,detail:`packument has ${n} but its \`dist.tarball\` is missing`}:{state:`present`,status:C.status,tarball:W}}function formatUnconfirmedPublish(t){let{name:n,version:S,putUrl:C,putStatus:N,putStatusText:F,payloadBytes:I,readback:H}=t,W=t.claim??`accepted`,q=(H.elapsedMs/1e3).toFixed(1),Y=H.last.state===`present`?`served`:H.last.detail,X=W===`already-published`?`npm says ${S} is ALREADY PUBLISHED`:`npm ACCEPTED the upload`,Z=H.verdict===`unknown`?H.last.state===`absent`?`${X}; its install document does not serve ${S} and the registry's own record could NOT be read.`:`${X} and the read-back could NOT establish whether the registry serves it.`:H.verdict===`recorded-not-served`?`${X}; the registry RECORDS ${S} and its install document does not serve it.`:`${X} and the registry has no record of ${S}.`,te=H.verdict===`unknown`?[` This is NOT a report that the publish failed, and it is not one that it worked. The read-back`,` reached no answer it could act on, so the version may or may not be installable — confirm it`," before releasing anything that depends on it (`npm view <name>@<version> dist.tarball`)."]:H.verdict===`recorded-not-served`?[` Do NOT re-publish: the registry holds the write, so a re-run is answered 409 and changes`,` nothing. The document npm installs from is behind the registry's own record — measured on`,` the ts-for-gir v5.1.0 release, @ts-for-gir/reporter was recorded at 21:43:00.983Z and a`,` cache-busted read of its install document still did not carry 5.1.0 ~40 min later. Wait and`,` re-read; if it persists, check https://status.npmjs.org/.`]:W===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it:`,` in the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and`,` the registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it`," cannot fix this — wait and re-read (`npm view <name>@<version>`), or check",` https://status.npmjs.org/.`]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${n}@${S} — ${Z}`,` PUT ${C} (${I} bytes) → ${N} ${F}`,` read-back GET ${H.url} (accept: application/vnd.npm.install-v1+json, per-probe cache buster)`,` answered ${H.last.state}: ${Y}`,` after ${H.attempts} probe(s) over ${q}s`,` verdict ${H.verdict} — ${H.verdictDetail}`,...te].join(`
1269
+ `)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++TK}`});if(`error`in S)return{state:`unknown`,detail:S.error};if(S.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!S.ok)return{state:`unknown`,status:S.status,detail:`${S.status} ${S.statusText}`};let C;try{C=await S.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`unknown`,status:S.status,detail:`packument is not JSON (${n})`}}let N=C?.versions,F=N&&typeof N==`object`?Object.keys(N).length:0;return F===0?{state:`unknown`,status:S.status,detail:`a 200 carrying no versions establishes nothing`}:{state:`present`,status:S.status,versions:F}}var bK,xK,SK,CK,wK,TK,EK=__esmMin(()=>{Ch(),bK=[2e3,4e3,8e3,15e3,3e4],xK=2e3,SK=6e5,CK=32*1024*1024,wK=1e4,TK=0});function collectWorkspacePins(t,n){let S=[];for(let C of DK){let N=depsOf(t,C),F=depsOf(n,C);for(let[t,n]of Object.entries(N))typeof n!=`string`||!n.startsWith(`workspace:`)||S.push({name:t,spec:F[t]??n,block:C})}return S}var DK,OK,depsOf,kK=__esmMin(()=>{DK=[`dependencies`,`optionalDependencies`,`peerDependencies`],OK=`dependencies`,depsOf=(t,n)=>{let S=t[n];return S&&typeof S==`object`?S:{}}});function statusTokenFromEnv(t){for(let n of[t.NPM_STATUS_TOKEN,t.NODE_AUTH_TOKEN]){let t=n?.trim();if(t&&!/^X+(-X+)+$/.test(t))return t}}async function fetchVersionStatus(t){if(!t.token)return{state:`unavailable`,reason:`no-credential`,detail:`the status endpoint needs an npm access token (set NPM_STATUS_TOKEN); OIDC publish tokens are not accepted`};let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/-/package/${escapePackageName(t.name)}/version/${encodeURIComponent(t.version)}/status`,C;try{C=await n(S,{headers:{accept:`application/json`,authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(t.probeTimeoutMs??3e4)})}catch(t){return{state:`unavailable`,reason:`error`,detail:t instanceof Error?t.message:String(t)}}if(C.status===401)return{state:`unavailable`,reason:`rejected`,detail:`401 — the token is missing, invalid or expired`};if(C.status===403)return{state:`unavailable`,reason:`not-enabled`,detail:`403 — package version status is not enabled for this package`};if(C.status===404)return{state:`unavailable`,reason:`not-found`,detail:`404 — no such version, or the token cannot see this package`};if(!C.ok)return{state:`unavailable`,reason:`error`,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){return{state:`unavailable`,reason:`error`,detail:`status body is not JSON (${t instanceof Error?t.message:String(t)})`}}let F=N?.status;return typeof F!=`string`||!AK.includes(F)?{state:`unavailable`,reason:`error`,detail:`unrecognised status ${JSON.stringify(F)}`}:{state:`known`,status:F}}function isTerminalClass(t){return t!==`validating`&&t!==`published-lagging`&&t!==`unchecked`}function whyUnchecked(t){return t.reason===`no-credential`?`status endpoint not asked: no NPM_STATUS_TOKEN`:t.detail}function classifyUnserved(t,n){if(n.state===`known`)switch(n.status){case`validating`:return{cls:`validating`,detail:`npm accepted the upload and its automated review has not finished`,terminal:!1};case`staged`:return{cls:`staged`,detail:`awaiting maintainer approval on npm`,terminal:!0};case`blocked`:return{cls:`blocked`,detail:`failed npm automated validation`,terminal:!0};case`deleted`:return{cls:`deleted`,detail:`deleted on npm`,terminal:!0};case`published`:return{cls:`published-lagging`,detail:`npm reports it published; the install document does not serve it yet`,terminal:!1}}return n.reason===`not-found`?{cls:`missing`,detail:`the registry has no such version (${n.detail}); the PUT did not land`,terminal:!0}:{cls:`unchecked`,detail:`not served (read-back: ${t}); ${whyUnchecked(n)}`,terminal:!1}}function describeClass(t){switch(t){case`validating`:return`validating (npm automated review pending)`;case`staged`:return`staged (needs maintainer approval)`;case`blocked`:return`blocked (failed automated validation)`;case`deleted`:return`deleted`;case`published-lagging`:return`published, not yet served`;case`missing`:return`missing (never recorded)`;case`unchecked`:return`not served (status not checked)`}}var AK,jK=__esmMin(()=>{Ch(),AK=[`published`,`validating`,`staged`,`blocked`,`deleted`]});function appendLedger(t,n){t&&appendFileSync(t,`${JSON.stringify(n)}\n`)}function readLedger(t){if(!t||!existsSync(t))return[];let n=[];for(let S of readFileSync(t,`utf-8`).split(`
1270
+ `))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:NK});if(I.confirmed)return confirmedServed(t,N,n,S);let ask=()=>fetchVersionStatus({registry:t.registry,name:n,version:S,token:t.statusToken,fetchImpl:t.fetchImpl}),H=classifyUnserved(I.verdict,await ask());if(!H.terminal&&t.waitBudgetMs>0){if(I=await verifyPublishedVersion({...F,budgetMs:t.waitBudgetMs}),I.confirmed)return confirmedServed(t,N,n,S);H=classifyUnserved(I.verdict,await ask())}return{...C,cls:H.cls,detail:H.detail}}function confirmedServed(t,n,S,C){return n?.ev===`unserved`&&appendLedger(t.ledgerPath,{ev:`served`,name:S,version:C}),null}function summariseReasons(t){return t.map(t=>`${t.name}@${t.version} is ${t.cls===`held`?`held`:describeClass(t.cls)}`).join(`; `)}async function recordUnserved(t){let n=await fetchVersionStatus({registry:t.registry,name:t.name,version:t.version,token:t.statusToken,fetchImpl:t.fetchImpl}),S=classifyUnserved(t.verdict,n);return appendLedger(t.ledgerPath,{ev:`unserved`,name:t.name,version:t.version,cls:S.cls,detail:S.detail}),S}function pendingEntries(t){let n=new Map;for(let S of t)n.set(`${S.name}@${S.version}`,S);let S=[...n.values()];return{unserved:S.filter(t=>t.ev===`unserved`),held:S.filter(t=>t.ev===`held`)}}function markHeldPublished(t,n,S){[...readLedger(t)].reverse().find(t=>t.name===n&&t.version===S)?.ev===`held`&&appendLedger(t,{ev:`served`,name:n,version:S})}async function settleUnserved(t){let n=pendingEntries(t.entries).unserved.filter(t=>!isTerminalClass(t.cls));return(await Promise.all(n.map(async n=>{if((await verifyPublishedVersion({registry:t.registryFor(n.name),name:n.name,version:n.version,budgetMs:t.budgetMs,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log})).confirmed)return appendLedger(t.ledgerPath,{ev:`served`,name:n.name,version:n.version}),`${n.name}@${n.version}`}))).filter(t=>t!==void 0)}function renderLedgerSummary(t,n){let{unserved:S,held:C}=pendingEntries(t);if(S.length===0&&C.length===0)return;let N=[`### npm versions that were accepted but are not installable`,``];if(S.length>0){N.push(`| Package | Version | State | Detail |`,`| --- | --- | --- | --- |`);for(let t of S)N.push(`| \`${t.name}\` | ${t.version} | ${describeClass(t.cls)} | ${t.detail} |`);N.push(``)}if(C.length>0){N.push(`### Held — NOT published in this run`,``,`Each package below depends on a version npm does not serve, so publishing it would have shipped a package that cannot be installed.`,``,`| Package | Version | Because |`,`| --- | --- | --- |`);for(let t of C)N.push(`| \`${t.name}\` | ${t.version} | ${summariseReasons(t.reasons)} |`);N.push(``,"Once the dependencies above are served by npm (a `validating` version appears on its own, or is approved/released by a maintainer), publish the held set with:",``,"```sh",`gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${[...new Set(C.map(t=>t.name))].join(` `)}'`,"```"),S.some(t=>t.cls===`blocked`||t.cls===`deleted`)&&N.push(``,"A `blocked` or `deleted` version is a spent number: re-running the release cannot serve it, the package needs a version bump.")}return N.join(`
1271
+ `)}var MK,NK,holdsPublish,PK=__esmMin(()=>{af(),kK(),EK(),jK(),MK=3e5,NK=1,holdsPublish=t=>t.block===OK});function beginPrompt(){FK++}function endPrompt(t=defaultWrite){if(FK=Math.max(0,FK-1),FK>0||IK.length===0)return;let n=IK.splice(0,IK.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(FK>0){IK.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var FK,IK,LK=__esmMin(()=>{FK=0,IK=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
1272
1272
  `?{buf:t,echo:`
1273
- `,done:!0,interrupt:!1}:n===IK?{buf:t,echo:`
1274
- `,done:!1,interrupt:!0}:n===LK||n===RK?t.length>0?{buf:t.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}:n>=` `?{buf:t+n,echo:S?`*`:n,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}}async function runRawSession(t){let n=process.stdin,S=process.stdout,C=null,cleanup=()=>{n.removeListener(`data`,onData);try{n.setRawMode(!1)}catch{}typeof n.pause==`function`&&n.pause()},onData=t=>{let n=typeof t==`string`?t:t.toString(`utf-8`);for(let t of n){if(!C)continue;let n=applyKey(C.buf,t,C.mask);if(C.buf=n.buf,n.echo&&S.write(n.echo),n.interrupt)return cleanup(),process.exit(130);if(n.done){let{resolve:t}=C;C=null,t(n.buf)}}};n.setRawMode(!0),typeof n.resume==`function`&&n.resume(),n.setEncoding(`utf-8`),n.on(`data`,onData);let read=(t,n)=>new Promise(N=>{beginPrompt(),S.write(t),C={mask:n,buf:``,resolve:t=>{endPrompt(),N(t)}}});try{return await t(read)}finally{cleanup()}}function readLine(){return new Promise(t=>{let n=``,onData=S=>{n+=typeof S==`string`?S:S.toString(`utf-8`);let C=n.search(/[\r\n]/);C>=0&&(cleanup(),t(n.slice(0,C)))},onEnd=()=>{cleanup(),t(n.replace(/\r$/,``).trim())},cleanup=()=>{process.stdin.removeListener(`data`,onData),process.stdin.removeListener(`end`,onEnd)};process.stdin.setEncoding(`utf-8`),typeof process.stdin.isPaused==`function`&&process.stdin.isPaused()&&process.stdin.resume(),process.stdin.on(`data`,onData),process.stdin.once(`end`,onEnd)})}async function promptLine(t){if(!isTtyStdin()){beginPrompt(),process.stdout.write(t);try{return await readLine()}finally{endPrompt()}}return runRawSession(n=>n(t,!1))}async function promptCredentials(t){if(!isTtyStdin()){let n=t;n||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let S=await readLine();return{username:n,password:S}}return runRawSession(async n=>({username:t??await n(`Username: `,!1),password:await n(`Password: `,!0)}))}var IK,LK,RK,zK=__esmMin(()=>{FK(),IK=``,LK=``,RK=`\b`});function isOtpCacheEnabled(){let t=process.env[BK];return!(t===`1`||t===`true`||t===`yes`)}function normalizeRegistry(t){return t.endsWith(`/`)?t.slice(0,-1):t}function cacheBaseDir(t){if(t?.dir)return t.dir;let n=process.env.XDG_RUNTIME_DIR;return zn(n&&n.length>0?n:tmpdir(),VK)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return zn(cacheBaseDir(n),`otp-${S||`default`}.json`)}function readCachedOtp(t,n){if(!isOtpCacheEnabled())return;let S=n?.now??Date.now(),C=cacheFileFor(t,n);try{if(!existsSync(C))return;let n=JSON.parse(readFileSync(C,`utf8`));if(!n||typeof n.otp!=`string`||typeof n.expiresAt!=`number`){deleteCacheFile(C);return}if(n.registry!==normalizeRegistry(t))return;if(S>=n.expiresAt){deleteCacheFile(C);return}return n.otp.length>0?n.otp:void 0}catch{deleteCacheFile(C);return}}function writeCachedOtp(t,n,S){if(!isOtpCacheEnabled()||!n||n.length===0)return;let C=S?.now??Date.now(),N=S?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(S),{recursive:!0,mode:448});let F=cacheFileFor(t,S),I={otp:n,expiresAt:C+N,registry:normalizeRegistry(t)};writeFileSync(F,JSON.stringify(I),{mode:384}),chmodSync(F,384)}catch{}}function clearCachedOtp(t,n){deleteCacheFile(cacheFileFor(t,n))}function deleteCacheFile(t){try{existsSync(t)&&rmSync(t,{force:!0})}catch{}}var BK,VK,HK=__esmMin(()=>{af(),o_(),Xn(),BK=`GJSIFY_NO_OTP_CACHE`,VK=`gjsify-otp`});async function isOtpChallenge(t){if(t.status!==401)return!1;if((t.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let n=await t.clone().text().catch(()=>``);return/one-time pass/i.test(n)||/\bEOTP\b/.test(n)}async function withOtpRetry(t,n,S={}){let C=S.maxPrompts??2,N=S.question,F=n.current(),I=S.seedFirstAttempt===!0&&F!==void 0,H=n.epoch(),W=await t(I?F:void 0);if(!await isOtpChallenge(W))return W;if(I&&n.invalidate(H),!I&&n.current()!==void 0){if(H=n.epoch(),W=await t(n.current()),!await isOtpChallenge(W))return W;n.invalidate(H)}for(let S=0;S<C;S++){let S=await n.refresh(N,H);if(!S||(H=n.epoch(),W=await t(S),!await isOtpChallenge(W)))return W;n.invalidate(H)}return W}var UK,WK,OtpProvider,GK=__esmMin(()=>{zK(),HK(),UK=`This operation requires a one-time password.
1275
- Enter OTP: `,WK=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
1276
- Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?WK:UK));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(t){let n=(await this.promptFn(t)).trim();return n&&(this.cached=n,this.generation++,this.registry&&writeCachedOtp(this.registry,n)),n}invalidate(t){t!==void 0&&this.generation!==t||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});function remainingHoldDeadlineMs(){let t=Number(process.env.GJSIFY_HOLD_DEADLINE);return Number.isFinite(t)&&t>0?Math.max(0,t-Date.now()):1/0}function acceptsRepublish(t,n,S,C){return(t===409||t===403&&/previously published/i.test(n))&&(S||C)}async function publishWorkspace(t){let{wsDir:n,tag:S,access:C,provenance:N,tolerate:F,tolerateUntrustedNew:I,trustedFlag:H,verbose:W,json:q,otpProvider:Y}=t,X=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:q?`inherit-stderr`:`inherit`}),Z=await packWorkspaceToBytes(n),te=readFileSync(zn(n,`package.json`),`utf-8`),ne=JSON.parse(te),re=await loadRewrittenManifest(n,ne),ie=await loadNpmrc(n),ae=t.registry??process.env.npm_config_registry??registryFor(X.name,ie)??ph,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,Q=`${oe}/${escapePackageName(X.name)}`,se=`${X.name.includes(`/`)?X.name.slice(X.name.indexOf(`/`)+1):X.name}-${X.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:S,access:C,tarballBytes:Z,tarballUrl:`${oe}/${X.name}/-/${se}`,packed:{...X,wireFilename:se},provenance:N}),le=buildPublishHeaders(Q,{npmrc:ie}),ue=new Set(t.assumePresent??[]),de=collectWorkspacePins(ne,re).filter(t=>!ue.has(t.name));if(de.length>0){let t=await Promise.all(de.map(async t=>({pin:t,presence:await probePackageName({registry:ae,name:t.name,authorization:le.authorization})}))),n=[];for(let{pin:S,presence:C}of t){if(C.state===`present`)continue;let t=`${S.block}.${S.name}@${S.spec}`;if(C.state===`unknown`){ge.error(`gjsify publish: could not establish whether ${S.name} exists (${C.detail}) — not blocking on ${t}`);continue}if(S.block!==`dependencies`){ge.error(`gjsify publish: ${t} names a package ${ae} does not have — npm installs around it, Yarn (\`YN0035\`) does not`);continue}n.push(S)}if(n.length>0)return{ok:I,action:`blocked-missing-dependency`,name:X.name,version:X.version,registry:ae,tolerated:I,missing:n}}let fe=process.env.GJSIFY_PUBLISH_LEDGER;if(de.length>0){let n=await findUnavailablePins({registry:oe,pins:de,ledger:readLedger(fe),ledgerPath:fe,authorization:le.authorization,statusToken:statusTokenFromEnv(process.env),waitBudgetMs:t.holdWaitMs??3e5,log:W?t=>ge.error(t):void 0});for(let t of n.filter(t=>!holdsPublish(t)))ge.error(`gjsify publish: ${t.block}.${t.name}@${t.version} is not served (${t.detail}) — optional edge, publishing anyway`);let S=n.filter(holdsPublish);if(S.length>0)return appendLedger(fe,{ev:`held`,name:X.name,version:X.version,reasons:S}),{ok:!1,action:`held-unpublished-dependency`,name:X.name,version:X.version,registry:oe,reasons:S}}let pe=H===!0||H===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,me=`token`;if(pe)try{let{token:t,audience:n}=await getNpmTrustedToken({packageName:X.name,registry:ae,log:W?t=>ge.error(t):void 0});le.authorization=`Bearer ${t}`,me=`oidc`,W&&ge.error(`gjsify publish: OIDC token obtained (audience=${n})`)}catch(t){if(t instanceof OidcExchangeError&&t.status===404&&/package not found/i.test(t.body)&&I)return{ok:!0,action:`skipped-untrusted-new`,name:X.name,version:X.version};if(H===!0)return{ok:!1,action:`oidc-failed`,name:X.name,version:X.version,error:t};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:X.name,version:X.version,error:t};if(W){let n=t instanceof Error?t.message:String(t);ge.error(`gjsify publish: OIDC auto-detect failed (${n}) — falling back to token auth`)}}W&&(ge.error(`gjsify publish: PUT ${Q} (${X.name}@${X.version})`),ge.error(` auth-mode: ${me}`),ge.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ge.error(` payload size: ${JSON.stringify(ce).length} bytes`));let he=JSON.stringify(ce),_e=!1,doPut=async n=>{let S={...le};n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`);let{response:C,retried:N}=await fetchWithTransientRetry(()=>fetch(Q,{method:`PUT`,headers:S,body:he}),{log:t=>ge.error(`gjsify publish: PUT ${X.name}@${X.version}: ${t}`),...t.putRetry});return N>0&&(_e=!0),C},ve=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${ve.status} ${ve.statusText}`);let t=await ve.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(n<=0)return;let S=budgetForPayload(n,he.length);return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:S,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(ve))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:ve.status};if(ve.ok){let t=await readBack();return t?.confirmed&&W&&ge.error(` read-back: confirmed after ${t.attempts} probe(s) in ${t.elapsedMs} ms`),t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`published`,name:X.name,version:X.version,filename:X.filename,size:X.size,integrity:X.integrity,tag:S,registry:oe,readback:t})}let ye=await ve.text().catch(()=>`<no body>`);if(acceptsRepublish(ve.status,ye,F,_e)){let t=await readBack();return t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:ve.status,registry:oe,readback:t})}if(ve.status===404&&me===`token`&&is404DiagnosticCandidate(ye)){let t=await diagnose404({packageName:X.name,version:X.version,registry:oe,npmrc:ie});if(t.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:X.name,version:X.version,status:404,diag:t}}return{ok:!1,action:`error`,name:X.name,version:X.version,status:ve.status,statusText:ve.statusText,text:ye}}function describeVerification(t,n){if(!t?.confirmed)return{verified:!1,clause:`(UNVERIFIED — read-back disabled by --verify-timeout 0)`,json:null};let S=(t.elapsedMs/1e3).toFixed(1);return{verified:!0,clause:`(verified on ${n} — ${t.attempts} probe(s), ${S}s)`,json:{registry:n,verdict:t.verdict,probes:t.attempts,elapsedMs:t.elapsedMs,tarball:t.last.state===`present`?t.last.tarball:null}}}function warnUnverified(t,n,S){process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Publish unverified::${t}@${n} was published with the read-back disabled (--verify-timeout 0) — nothing confirmed that ${S} serves it\n`)}function reportPublishOutcome(t,n,S=!1){switch(t.action){case`published`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,name:t.name,version:t.version,filename:t.filename,size:t.size,integrity:t.integrity,tag:t.tag,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${t.name}@${t.version} ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`held-unpublished-dependency`:{let C=summariseReasons(t.reasons);return n?process.stdout.write(`${JSON.stringify({ok:!1,action:`held-unpublished-dependency`,name:t.name,version:t.version,registry:t.registry,reasons:t.reasons,deferred:S},null,2)}\n`):process.stderr.write(`~ ${t.name}@${t.version} (HELD — not published: ${C})\n`),process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Package held::${t.name}@${t.version} was NOT published: ${C}\n`),S?void 0:process.exit(1)}case`publish-unconfirmed`:{let C=`${formatUnconfirmedPublish(t)}\n state: ${describeClass(t.classification.cls)} — ${t.classification.detail}`;if(n?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:t.name,version:t.version,registry:t.registry,claim:t.claim,putStatus:t.putStatus,probes:t.readback.attempts,elapsedMs:t.readback.elapsedMs,readbackUrl:t.readback.url,readbackState:t.readback.last.state,verdict:t.readback.verdict,verdictDetail:t.readback.verdictDetail,recordedAt:t.readback.recordedAt??null,deferred:S,class:t.classification.cls,classDetail:t.classification.detail},null,2)}\n`):process.stderr.write(`${C}\n`),S){if(process.env.GITHUB_ACTIONS){let n=t.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${t.name}@${t.version} ${n} (HTTP ${t.putStatus}) but did not resolve on ${t.registry} within ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}; ${describeClass(t.classification.cls)}] — the release-closure job must confirm it
1277
- `)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(oz(),az)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var KK,qK=__esmMin(()=>{_e(),af(),o_(),Xn(),bW(),xh(),Ch(),dK(),gK(),_K(),wK(),DK(),MK(),kK(),DB(),GK(),zK(),mK(),KK={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:bK/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`hold-timeout`,{description:'Seconds to wait for an intra-repo dependency pin whose exact version the registry does not serve (yet) before HOLDING this package instead of publishing it. A version npm accepted but never serves (status "validating") would make every dependent uninstallable; the write lag measured on v0.46.0 reaches 252s, hence the default. `0` probes once and holds without waiting. A hold exits 1, or 0 under `--verify-defer`.',type:`number`,default:AK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:bK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=JK[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,JK,clean,YK=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,JK={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
1273
+ `,done:!0,interrupt:!1}:n===RK?{buf:t,echo:`
1274
+ `,done:!1,interrupt:!0}:n===zK||n===BK?t.length>0?{buf:t.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}:n>=` `?{buf:t+n,echo:S?`*`:n,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}}async function runRawSession(t){let n=process.stdin,S=process.stdout,C=null,cleanup=()=>{n.removeListener(`data`,onData);try{n.setRawMode(!1)}catch{}typeof n.pause==`function`&&n.pause()},onData=t=>{let n=typeof t==`string`?t:t.toString(`utf-8`);for(let t of n){if(!C)continue;let n=applyKey(C.buf,t,C.mask);if(C.buf=n.buf,n.echo&&S.write(n.echo),n.interrupt)return cleanup(),process.exit(130);if(n.done){let{resolve:t}=C;C=null,t(n.buf)}}};n.setRawMode(!0),typeof n.resume==`function`&&n.resume(),n.setEncoding(`utf-8`),n.on(`data`,onData);let read=(t,n)=>new Promise(N=>{beginPrompt(),S.write(t),C={mask:n,buf:``,resolve:t=>{endPrompt(),N(t)}}});try{return await t(read)}finally{cleanup()}}function readLine(){return new Promise(t=>{let n=``,onData=S=>{n+=typeof S==`string`?S:S.toString(`utf-8`);let C=n.search(/[\r\n]/);C>=0&&(cleanup(),t(n.slice(0,C)))},onEnd=()=>{cleanup(),t(n.replace(/\r$/,``).trim())},cleanup=()=>{process.stdin.removeListener(`data`,onData),process.stdin.removeListener(`end`,onEnd)};process.stdin.setEncoding(`utf-8`),typeof process.stdin.isPaused==`function`&&process.stdin.isPaused()&&process.stdin.resume(),process.stdin.on(`data`,onData),process.stdin.once(`end`,onEnd)})}async function promptLine(t){if(!isTtyStdin()){beginPrompt(),process.stdout.write(t);try{return await readLine()}finally{endPrompt()}}return runRawSession(n=>n(t,!1))}async function promptCredentials(t){if(!isTtyStdin()){let n=t;n||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let S=await readLine();return{username:n,password:S}}return runRawSession(async n=>({username:t??await n(`Username: `,!1),password:await n(`Password: `,!0)}))}var RK,zK,BK,VK=__esmMin(()=>{LK(),RK=``,zK=``,BK=`\b`});function isOtpCacheEnabled(){let t=process.env[HK];return!(t===`1`||t===`true`||t===`yes`)}function normalizeRegistry(t){return t.endsWith(`/`)?t.slice(0,-1):t}function cacheBaseDir(t){if(t?.dir)return t.dir;let n=process.env.XDG_RUNTIME_DIR;return zn(n&&n.length>0?n:tmpdir(),UK)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return zn(cacheBaseDir(n),`otp-${S||`default`}.json`)}function readCachedOtp(t,n){if(!isOtpCacheEnabled())return;let S=n?.now??Date.now(),C=cacheFileFor(t,n);try{if(!existsSync(C))return;let n=JSON.parse(readFileSync(C,`utf8`));if(!n||typeof n.otp!=`string`||typeof n.expiresAt!=`number`){deleteCacheFile(C);return}if(n.registry!==normalizeRegistry(t))return;if(S>=n.expiresAt){deleteCacheFile(C);return}return n.otp.length>0?n.otp:void 0}catch{deleteCacheFile(C);return}}function writeCachedOtp(t,n,S){if(!isOtpCacheEnabled()||!n||n.length===0)return;let C=S?.now??Date.now(),N=S?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(S),{recursive:!0,mode:448});let F=cacheFileFor(t,S),I={otp:n,expiresAt:C+N,registry:normalizeRegistry(t)};writeFileSync(F,JSON.stringify(I),{mode:384}),chmodSync(F,384)}catch{}}function clearCachedOtp(t,n){deleteCacheFile(cacheFileFor(t,n))}function deleteCacheFile(t){try{existsSync(t)&&rmSync(t,{force:!0})}catch{}}var HK,UK,WK=__esmMin(()=>{af(),o_(),Xn(),HK=`GJSIFY_NO_OTP_CACHE`,UK=`gjsify-otp`});async function isOtpChallenge(t){if(t.status!==401)return!1;if((t.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let n=await t.clone().text().catch(()=>``);return/one-time pass/i.test(n)||/\bEOTP\b/.test(n)}async function withOtpRetry(t,n,S={}){let C=S.maxPrompts??2,N=S.question,F=n.current(),I=S.seedFirstAttempt===!0&&F!==void 0,H=n.epoch(),W=await t(I?F:void 0);if(!await isOtpChallenge(W))return W;if(I&&n.invalidate(H),!I&&n.current()!==void 0){if(H=n.epoch(),W=await t(n.current()),!await isOtpChallenge(W))return W;n.invalidate(H)}for(let S=0;S<C;S++){let S=await n.refresh(N,H);if(!S||(H=n.epoch(),W=await t(S),!await isOtpChallenge(W)))return W;n.invalidate(H)}return W}var GK,KK,OtpProvider,qK=__esmMin(()=>{VK(),WK(),GK=`This operation requires a one-time password.
1275
+ Enter OTP: `,KK=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
1276
+ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?KK:GK));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(t){let n=(await this.promptFn(t)).trim();return n&&(this.cached=n,this.generation++,this.registry&&writeCachedOtp(this.registry,n)),n}invalidate(t){t!==void 0&&this.generation!==t||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});function remainingHoldDeadlineMs(){let t=Number(process.env.GJSIFY_HOLD_DEADLINE);return Number.isFinite(t)&&t>0?Math.max(0,t-Date.now()):1/0}function acceptsRepublish(t,n,S,C){return(t===409||t===403&&/previously published/i.test(n))&&(S||C)}async function publishWorkspace(t){let{wsDir:n,tag:S,access:C,provenance:N,tolerate:F,tolerateUntrustedNew:I,trustedFlag:H,verbose:W,json:q,otpProvider:Y}=t,X=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:q?`inherit-stderr`:`inherit`}),Z=await packWorkspaceToBytes(n),te=readFileSync(zn(n,`package.json`),`utf-8`),ne=JSON.parse(te),re=await loadRewrittenManifest(n,ne),ie=await loadNpmrc(n),ae=t.registry??process.env.npm_config_registry??registryFor(X.name,ie)??ph,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,Q=`${oe}/${escapePackageName(X.name)}`,se=`${X.name.includes(`/`)?X.name.slice(X.name.indexOf(`/`)+1):X.name}-${X.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:S,access:C,tarballBytes:Z,tarballUrl:`${oe}/${X.name}/-/${se}`,packed:{...X,wireFilename:se},provenance:N}),le=buildPublishHeaders(Q,{npmrc:ie}),ue=new Set(t.assumePresent??[]),de=collectWorkspacePins(ne,re).filter(t=>!ue.has(t.name));if(de.length>0){let t=await Promise.all(de.map(async t=>({pin:t,presence:await probePackageName({registry:ae,name:t.name,authorization:le.authorization})}))),n=[];for(let{pin:S,presence:C}of t){if(C.state===`present`)continue;let t=`${S.block}.${S.name}@${S.spec}`;if(C.state===`unknown`){ge.error(`gjsify publish: could not establish whether ${S.name} exists (${C.detail}) — not blocking on ${t}`);continue}if(S.block!==`dependencies`){ge.error(`gjsify publish: ${t} names a package ${ae} does not have — npm installs around it, Yarn (\`YN0035\`) does not`);continue}n.push(S)}if(n.length>0)return{ok:I,action:`blocked-missing-dependency`,name:X.name,version:X.version,registry:ae,tolerated:I,missing:n}}let fe=process.env.GJSIFY_PUBLISH_LEDGER;if(de.length>0){let n=await findUnavailablePins({registry:oe,pins:de,ledger:readLedger(fe),ledgerPath:fe,authorization:le.authorization,statusToken:statusTokenFromEnv(process.env),waitBudgetMs:t.holdWaitMs??3e5,log:W?t=>ge.error(t):void 0});for(let t of n.filter(t=>!holdsPublish(t)))ge.error(`gjsify publish: ${t.block}.${t.name}@${t.version} is not served (${t.detail}) — optional edge, publishing anyway`);let S=n.filter(holdsPublish);if(S.length>0)return appendLedger(fe,{ev:`held`,name:X.name,version:X.version,reasons:S}),{ok:!1,action:`held-unpublished-dependency`,name:X.name,version:X.version,registry:oe,reasons:S}}let pe=H===!0||H===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,me=`token`;if(pe)try{let{token:t,audience:n}=await getNpmTrustedToken({packageName:X.name,registry:ae,log:W?t=>ge.error(t):void 0});le.authorization=`Bearer ${t}`,me=`oidc`,W&&ge.error(`gjsify publish: OIDC token obtained (audience=${n})`)}catch(t){if(t instanceof OidcExchangeError&&t.status===404&&/package not found/i.test(t.body)&&I)return{ok:!0,action:`skipped-untrusted-new`,name:X.name,version:X.version};if(H===!0)return{ok:!1,action:`oidc-failed`,name:X.name,version:X.version,error:t};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:X.name,version:X.version,error:t};if(W){let n=t instanceof Error?t.message:String(t);ge.error(`gjsify publish: OIDC auto-detect failed (${n}) — falling back to token auth`)}}W&&(ge.error(`gjsify publish: PUT ${Q} (${X.name}@${X.version})`),ge.error(` auth-mode: ${me}`),ge.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ge.error(` payload size: ${JSON.stringify(ce).length} bytes`));let he=JSON.stringify(ce),_e=!1,doPut=async n=>{let S={...le};n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`);let{response:C,retried:N}=await fetchWithTransientRetry(()=>fetch(Q,{method:`PUT`,headers:S,body:he}),{log:t=>ge.error(`gjsify publish: PUT ${X.name}@${X.version}: ${t}`),...t.putRetry});return N>0&&(_e=!0),C},ve=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${ve.status} ${ve.statusText}`);let t=await ve.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(n<=0)return;let S=budgetForPayload(n,he.length);return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:S,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(ve))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:ve.status};if(ve.ok){let t=await readBack();return t?.confirmed&&W&&ge.error(` read-back: confirmed after ${t.attempts} probe(s) in ${t.elapsedMs} ms`),t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`published`,name:X.name,version:X.version,filename:X.filename,size:X.size,integrity:X.integrity,tag:S,registry:oe,readback:t})}let ye=await ve.text().catch(()=>`<no body>`);if(acceptsRepublish(ve.status,ye,F,_e)){let t=await readBack();return t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:ve.status,registry:oe,readback:t})}if(ve.status===404&&me===`token`&&is404DiagnosticCandidate(ye)){let t=await diagnose404({packageName:X.name,version:X.version,registry:oe,npmrc:ie});if(t.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:X.name,version:X.version,status:404,diag:t}}return{ok:!1,action:`error`,name:X.name,version:X.version,status:ve.status,statusText:ve.statusText,text:ye}}function describeVerification(t,n){if(!t?.confirmed)return{verified:!1,clause:`(UNVERIFIED — read-back disabled by --verify-timeout 0)`,json:null};let S=(t.elapsedMs/1e3).toFixed(1);return{verified:!0,clause:`(verified on ${n} — ${t.attempts} probe(s), ${S}s)`,json:{registry:n,verdict:t.verdict,probes:t.attempts,elapsedMs:t.elapsedMs,tarball:t.last.state===`present`?t.last.tarball:null}}}function warnUnverified(t,n,S){process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Publish unverified::${t}@${n} was published with the read-back disabled (--verify-timeout 0) — nothing confirmed that ${S} serves it\n`)}function reportPublishOutcome(t,n,S=!1){switch(t.action){case`published`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,name:t.name,version:t.version,filename:t.filename,size:t.size,integrity:t.integrity,tag:t.tag,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${t.name}@${t.version} ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`held-unpublished-dependency`:{let C=summariseReasons(t.reasons);return n?process.stdout.write(`${JSON.stringify({ok:!1,action:`held-unpublished-dependency`,name:t.name,version:t.version,registry:t.registry,reasons:t.reasons,deferred:S},null,2)}\n`):process.stderr.write(`~ ${t.name}@${t.version} (HELD — not published: ${C})\n`),process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Package held::${t.name}@${t.version} was NOT published: ${C}\n`),S?void 0:process.exit(1)}case`publish-unconfirmed`:{let C=`${formatUnconfirmedPublish(t)}\n state: ${describeClass(t.classification.cls)} — ${t.classification.detail}`;if(n?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:t.name,version:t.version,registry:t.registry,claim:t.claim,putStatus:t.putStatus,probes:t.readback.attempts,elapsedMs:t.readback.elapsedMs,readbackUrl:t.readback.url,readbackState:t.readback.last.state,verdict:t.readback.verdict,verdictDetail:t.readback.verdictDetail,recordedAt:t.readback.recordedAt??null,deferred:S,class:t.classification.cls,classDetail:t.classification.detail},null,2)}\n`):process.stderr.write(`${C}\n`),S){if(process.env.GITHUB_ACTIONS){let n=t.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${t.name}@${t.version} ${n} (HTTP ${t.putStatus}) but did not resolve on ${t.registry} within ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}; ${describeClass(t.classification.cls)}] — the release-closure job must confirm it
1277
+ `)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(oz(),az)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var JK,YK=__esmMin(()=>{_e(),af(),o_(),Xn(),xW(),xh(),Ch(),pK(),vK(),yK(),EK(),kK(),PK(),jK(),DB(),qK(),VK(),gK(),JK={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:SK/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`hold-timeout`,{description:'Seconds to wait for an intra-repo dependency pin whose exact version the registry does not serve (yet) before HOLDING this package instead of publishing it. A version npm accepted but never serves (status "validating") would make every dependent uninstallable; the write lag measured on v0.46.0 reaches 252s, hence the default. `0` probes once and holds without waiting. A hold exits 1, or 0 under `--verify-defer`.',type:`number`,default:MK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:SK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=XK[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,XK,clean,ZK=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,XK={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
1278
1278
  `))}return S.join(`
1279
1279
 
1280
- `)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var XK=__esmMin(()=>{gV(),YK()}),ZK,QK=__esmMin(()=>{_R(),KI(),XK(),af(),Xn(),ZK={command:`release-notes [release]`,description:"Print the `releases` entry for a version as GitHub Markdown (from the config or a metainfo file). Fails when there is no entry or no description.",builder:t=>t.positional(`release`,{description:"Version or tag (a leading `v` is accepted). Default: the version in package.json.",type:`string`}).option(`compare`,{description:"Append a `**Full changelog:**` compare link to the previous entry (needs `vcsBrowserUrl`).",type:`boolean`,default:!1}).option(`metainfo`,{description:"Read the `<release>` entries from this AppStream metainfo file instead of the config. Default without `releases` in the config: the file named by `gjsify.site.metainfo`.",type:`string`}),handler:async t=>{let n=process.cwd();try{let S=await new Config().forCommand(n),C=S.ship??{},N=S.flatpak??{},F=t.release??readPackageJson$2(zn(n,`package.json`))?.version;if(!F)throw Error(`no version given and package.json has none`);let{releases:I,source:H}=resolveReleases({metainfo:t.metainfo,configReleases:C.releases??N.releases,siteMetainfo:S.site?.metainfo,readMetainfo:t=>{try{return readFileSync(In(n,t),`utf8`)}catch{throw Error(`cannot read the metainfo file ${t}`)}}}),W=t.compare===!0?C.vcsBrowserUrl??N.vcsBrowserUrl:void 0;process.stdout.write(renderReleaseNotes({releases:I,source:H,version:stripVersionPrefix(F),repoUrl:W}))}catch(t){return process.stderr.write(`gjsify release-notes: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function px(t,n){return Math.round(t*n)}function planAndroidIcons(t){let n=[];for(let{name:S,scale:C}of eq){let N=`mipmap-${S}`;n.push({path:`${N}/ic_launcher.png`,kind:`legacy`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_round.png`,kind:`round`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_foreground.png`,kind:`foreground`,size:px(108,C)}),t.monochrome&&n.push({path:`${N}/ic_launcher_monochrome.png`,kind:`monochrome`,size:px(108,C)})}for(let{name:t,scale:S}of tq)n.push({path:`drawable-${t}/logo.png`,kind:`splash`,size:px(96,S)});let S=adaptiveIconXml(t.monochrome);return{png:n,text:[{path:`values/ic_launcher_background.xml`,content:backgroundXml(t.background)},{path:`mipmap-anydpi-v26/ic_launcher.xml`,content:S},{path:`mipmap-anydpi-v26/ic_launcher_round.xml`,content:S}]}}function backgroundXml(t){return`<?xml version="1.0" encoding="utf-8"?>
1280
+ `)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var QK=__esmMin(()=>{gV(),ZK()}),$K,eq=__esmMin(()=>{_R(),KI(),QK(),af(),Xn(),$K={command:`release-notes [release]`,description:"Print the `releases` entry for a version as GitHub Markdown (from the config or a metainfo file). Fails when there is no entry or no description.",builder:t=>t.positional(`release`,{description:"Version or tag (a leading `v` is accepted). Default: the version in package.json.",type:`string`}).option(`compare`,{description:"Append a `**Full changelog:**` compare link to the previous entry (needs `vcsBrowserUrl`).",type:`boolean`,default:!1}).option(`metainfo`,{description:"Read the `<release>` entries from this AppStream metainfo file instead of the config. Default without `releases` in the config: the file named by `gjsify.site.metainfo`.",type:`string`}),handler:async t=>{let n=process.cwd();try{let S=await new Config().forCommand(n),C=S.ship??{},N=S.flatpak??{},F=t.release??readPackageJson$2(zn(n,`package.json`))?.version;if(!F)throw Error(`no version given and package.json has none`);let{releases:I,source:H}=resolveReleases({metainfo:t.metainfo,configReleases:C.releases??N.releases,siteMetainfo:S.site?.metainfo,readMetainfo:t=>{try{return readFileSync(In(n,t),`utf8`)}catch{throw Error(`cannot read the metainfo file ${t}`)}}}),W=t.compare===!0?C.vcsBrowserUrl??N.vcsBrowserUrl:void 0;process.stdout.write(renderReleaseNotes({releases:I,source:H,version:stripVersionPrefix(F),repoUrl:W}))}catch(t){return process.stderr.write(`gjsify release-notes: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function px(t,n){return Math.round(t*n)}function planAndroidIcons(t){let n=[];for(let{name:S,scale:C}of nq){let N=`mipmap-${S}`;n.push({path:`${N}/ic_launcher.png`,kind:`legacy`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_round.png`,kind:`round`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_foreground.png`,kind:`foreground`,size:px(108,C)}),t.monochrome&&n.push({path:`${N}/ic_launcher_monochrome.png`,kind:`monochrome`,size:px(108,C)})}for(let{name:t,scale:S}of rq)n.push({path:`drawable-${t}/logo.png`,kind:`splash`,size:px(96,S)});let S=adaptiveIconXml(t.monochrome);return{png:n,text:[{path:`values/ic_launcher_background.xml`,content:backgroundXml(t.background)},{path:`mipmap-anydpi-v26/ic_launcher.xml`,content:S},{path:`mipmap-anydpi-v26/ic_launcher_round.xml`,content:S}]}}function backgroundXml(t){return`<?xml version="1.0" encoding="utf-8"?>
1281
1281
  <resources>
1282
1282
  <color name="ic_launcher_background">${t}</color>
1283
1283
  </resources>
@@ -1287,12 +1287,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
1287
1287
  <foreground android:drawable="@mipmap/ic_launcher_foreground"/>
1288
1288
  ${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
1289
1289
  `:``}</adaptive-icon>
1290
- `}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*nq,N=(100-t)/2;return`<svg ${C} width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="50" fill="${S}"/><image x="${N}" y="${N}" width="${t}" height="${t}" xlink:href="${dataUri(n)}"/></svg>`}return`<svg ${C} width="108" height="108" viewBox="0 0 108 108"><image x="21" y="21" width="66" height="66" xlink:href="${dataUri(n)}"/></svg>`}function sha256(t){return createHash(`sha256`).update(t).digest(`hex`)}function hashInputs(t){return sha256(JSON.stringify({generator:1,icon:sha256(t.icon),symbolic:t.symbolic===null?null:sha256(t.symbolic),background:t.background}))}function buildStamp(t,n,S){return{generator:1,inputs:t,files:[...n.png.map(t=>t.path),...n.text.map(t=>t.path)].map(t=>On.join(S,t)).sort()}}function checkStamp(t,n,S){if(t===null)return{current:!1,reason:`was never generated`};let C;try{C=JSON.parse(t)}catch{return{current:!1,reason:`has an unreadable stamp`}}if(C.generator!==1||C.inputs!==n)return{current:!1,reason:`is out of date with the icon, colour or generator`};let N=(C.files??[]).find(t=>!S(t));return N===void 0?{current:!0}:{current:!1,reason:`lacks ${N}`}}var $K,eq,tq,nq,rq=__esmMin(()=>{gl(),Xn(),wH(),$K=`.gjsify-android-icons.json`,eq=[{name:`mdpi`,scale:1},{name:`hdpi`,scale:1.5},{name:`xhdpi`,scale:2},{name:`xxhdpi`,scale:3},{name:`xxxhdpi`,scale:4}],tq=[{name:`ldpi`,scale:.75},...eq],nq=.72});function walk(t,n=[]){if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){let C=zn(t,S.name);S.isDirectory()?walk(C,n):n.push(C)}return n}function discoverIcon(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`the icon ${n} does not exist`);let C=symbolicSibling(S);return{icon:S,symbolic:existsSync(C)?C:null}}let S=[zn(t,`data`,`icons`),...siblingIconRoots(t)];for(let t of S){let n=pickIconSources(walk(t).filter(t=>t.toLowerCase().endsWith(`.svg`)).sort());if(n.icon!==null)return{icon:n.icon,symbolic:n.symbolic}}throw Error("no app icon found; pass --icon <svg> or set `gjsify.androidIcons.icon`")}function siblingIconRoots(t){let n=Hn(t);return existsSync(n)?readdirSync(n).sort().map(t=>zn(n,t,`data`,`icons`)).filter(n=>n!==zn(t,`data`,`icons`)&&existsSync(n)&&statSync(n).isDirectory()):[]}function findMetainfoColor(t,n){let S=new Set([zn(n,`data`)]);S.add(In(Hn(t),`..`,`..`,`..`,`..`));for(let t of S){let n=walk(zn(t,`metainfo`)).filter(t=>/\.metainfo\.xml(\.in)?$/.test(t)).sort();for(let t of n){let n=parseMetainfoBranding(readFileSync(t,`utf8`));if(n!==null)return n}}return null}var iq,aq,oq=__esmMin(()=>{af(),o_(),Xn(),_R(),rq(),wH(),iq=`Android/src/main/res`,aq={command:`android-icons`,description:`Generate the Android launcher icon and splash logo of a NativeScript app from its one app icon.`,builder:t=>t.option(`resources`,{description:"The App_Resources directory. Default: `gjsify.androidIcons.resources`, else `appResourcesPath` of nativescript.config.ts, else App_Resources.",type:`string`}).option(`icon`,{description:"The scalable app icon SVG. Default: `gjsify.androidIcons.icon`, else the hicolor icon under data/icons (here or in a sibling package).",type:`string`}).option(`background`,{description:"Adaptive-icon background colour. Default: `gjsify.androidIcons.background`, else the metainfo light `<branding>` colour, else white.",type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the generated files are missing or the inputs changed.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).androidIcons??{},C=[`nativescript.config.ts`,`nativescript.config.js`].map(t=>zn(n,t)).find(t=>existsSync(t)),N=resolveResourcesName({flag:t.resources,configured:S.resources,nativescriptConfig:C===void 0?null:readFileSync(C,`utf8`)}),F=In(n,N),{icon:I,symbolic:H}=discoverIcon(n,t.icon??S.icon),W=resolveBackground({flag:t.background,configured:S.background,fromMetainfo:findMetainfoColor(I,n)}),q=new Uint8Array(readFileSync(I)),Y=H===null?null:new Uint8Array(readFileSync(H)),X=hashInputs({icon:q,symbolic:Y,background:W}),Z=planAndroidIcons({background:W,monochrome:Y!==null}),te=zn(F,$K);if(t.check===!0){let t=checkStamp(existsSync(te)?readFileSync(te,`utf8`):null,X,t=>existsSync(zn(F,...t.split(`/`))));return t.current?void 0:(process.stderr.write(`gjsify android-icons: ${N} ${t.reason}; run \`gjsify android-icons\` and commit it\n`),process.exit(1))}let ne=zn(F,...iq.split(`/`)),re=mkdtempSync(zn(tmpdir(),`gjsify-android-icons-`));try{let t=new Map([[`plain`,I]]);for(let n of[`round`,`foreground`]){let S=zn(re,`${n}.svg`);writeFileSync(S,wrapperSvg(n,q,W)),t.set(n,S)}if(Y!==null){let n=zn(re,`monochrome.svg`);writeFileSync(n,wrapperSvg(`monochrome`,Y,W)),t.set(`monochrome`,n)}for(let[n,S]of t){let t=Z.png.filter(t=>n===`plain`?t.kind===`legacy`||t.kind===`splash`:t.kind===n),C=await rasterizeSvg({svg:S,sizes:[...new Set(t.map(t=>t.size))],command:`gjsify android-icons`});for(let n of t){let t=zn(ne,n.path);mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,C.get(n.size))}}}finally{rmSync(re,{recursive:!0,force:!0})}for(let t of Z.text){let n=zn(ne,t.path);mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,t.content)}rmSync(zn(ne,`drawable`,`ic_launcher_foreground.xml`),{force:!0}),writeFileSync(te,`${JSON.stringify(buildStamp(X,Z,iq),null,2)}\n`),process.stdout.write(`gjsify android-icons: wrote ${Z.png.length+Z.text.length} files under ${Bn(n,ne).split(qn).join(`/`)} from ${Bn(n,I)}\n`)}catch(t){return process.stderr.write(`gjsify android-icons: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function globToRegExp(t){let n=t.split(`*`).map(t=>t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)).join(`.*`);return RegExp(`^${n}$`,`i`)}function isIgnored(t,n){return n.some(n=>{let S=globToRegExp(n);return S.test(t.name)||t.email!==``&&S.test(t.email)})}function parsePerson(t){let n=/^(.*?)\s*<([^>]*)>\s*$/.exec(t.trim());return n?{name:n[1].trim(),email:n[2].trim()}:{name:t.trim(),email:``}}function poLanguage(t){let n=On.basename(t);return/\.po$/i.test(n)?n.slice(0,-3):void 0}function bump(t,n){t.set(n,(t.get(n)??0)+1)}function rank(t){return[...t.entries()].sort(([t,n],[S,C])=>C-n||(t<S?-1:+(t>S))).map(([t])=>t)}function appendUnseen(t,n,S){let C=new Set(t);for(let N of n??[]){let n=N.trim();n&&!C.has(n)&&!S(n)&&(C.add(n),t.push(n))}}function buildCredits(t,n={}){let S=n.ignore??sq,C=n.overrides??{},N=C.exclude??[],excluded=t=>isIgnored({name:t,email:``},N),F=new Map,I=new Map,H=t.map(t=>{let n=new Set;for(let C of[t.author,...t.coAuthors])C.name&&!isIgnored(C,S)&&!excluded(C.name)&&n.add(C.name);let C=new Set,N=!1;for(let n of t.files){isTranslationFile(n)||(N=!0);let t=poLanguage(n);t&&C.add(t)}return{names:n,languages:C,touchesCode:N}}),W=new Map;for(let{names:t,languages:n}of H){if(t.size!==1||n.size!==1)continue;let[S]=t,[C]=n,N=W.get(S);N||W.set(S,N=new Set),N.add(C)}for(let{names:t,languages:n,touchesCode:S}of H){let C=t.size>1||n.size>1;for(let N of t){S&&bump(F,N);let t=W.get(N);for(let S of n){if(C&&t&&!t.has(S))continue;let n=I.get(S);n||I.set(S,n=new Map),bump(n,N)}}}let q={developers:rank(F),translators:{},supporters:[]},Y=C.excludeTranslators??{};for(let t of[...I.keys()].sort()){let n=[...Y[`*`]??[],...Y[t]??[]],S=rank(I.get(t)).filter(t=>!isIgnored({name:t,email:``},n));S.length&&(q.translators[t]=S)}appendUnseen(q.developers,C.developers,excluded);for(let t of Object.keys(C.translators??{}).sort()){let n=q.translators[t]??[];appendUnseen(n,C.translators[t],excluded),n.length&&(q.translators[t]=n)}return q.translators=Object.fromEntries(Object.entries(q.translators).sort(([t],[n])=>t<n?-1:1)),appendUnseen(q.supporters,C.supporters,excluded),q}function parseGitLog(t){let n=[];for(let S of t.split(lq)){if(!S.trim())continue;let[t=``,C=``,N=``,F=``]=S.split(cq);n.push({author:{name:t.trim(),email:C.trim()},coAuthors:N.split(uq).map(t=>t.trim()).filter(Boolean).map(parsePerson),files:F.split(`
1290
+ `}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*iq,N=(100-t)/2;return`<svg ${C} width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="50" fill="${S}"/><image x="${N}" y="${N}" width="${t}" height="${t}" xlink:href="${dataUri(n)}"/></svg>`}return`<svg ${C} width="108" height="108" viewBox="0 0 108 108"><image x="21" y="21" width="66" height="66" xlink:href="${dataUri(n)}"/></svg>`}function sha256(t){return createHash(`sha256`).update(t).digest(`hex`)}function hashInputs(t){return sha256(JSON.stringify({generator:1,icon:sha256(t.icon),symbolic:t.symbolic===null?null:sha256(t.symbolic),background:t.background}))}function buildStamp(t,n,S){return{generator:1,inputs:t,files:[...n.png.map(t=>t.path),...n.text.map(t=>t.path)].map(t=>On.join(S,t)).sort()}}function checkStamp(t,n,S){if(t===null)return{current:!1,reason:`was never generated`};let C;try{C=JSON.parse(t)}catch{return{current:!1,reason:`has an unreadable stamp`}}if(C.generator!==1||C.inputs!==n)return{current:!1,reason:`is out of date with the icon, colour or generator`};let N=(C.files??[]).find(t=>!S(t));return N===void 0?{current:!0}:{current:!1,reason:`lacks ${N}`}}var tq,nq,rq,iq,aq=__esmMin(()=>{gl(),Xn(),wH(),tq=`.gjsify-android-icons.json`,nq=[{name:`mdpi`,scale:1},{name:`hdpi`,scale:1.5},{name:`xhdpi`,scale:2},{name:`xxhdpi`,scale:3},{name:`xxxhdpi`,scale:4}],rq=[{name:`ldpi`,scale:.75},...nq],iq=.72});function walk(t,n=[]){if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){let C=zn(t,S.name);S.isDirectory()?walk(C,n):n.push(C)}return n}function discoverIcon(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`the icon ${n} does not exist`);let C=symbolicSibling(S);return{icon:S,symbolic:existsSync(C)?C:null}}let S=[zn(t,`data`,`icons`),...siblingIconRoots(t)];for(let t of S){let n=pickIconSources(walk(t).filter(t=>t.toLowerCase().endsWith(`.svg`)).sort());if(n.icon!==null)return{icon:n.icon,symbolic:n.symbolic}}throw Error("no app icon found; pass --icon <svg> or set `gjsify.androidIcons.icon`")}function siblingIconRoots(t){let n=Hn(t);return existsSync(n)?readdirSync(n).sort().map(t=>zn(n,t,`data`,`icons`)).filter(n=>n!==zn(t,`data`,`icons`)&&existsSync(n)&&statSync(n).isDirectory()):[]}function findMetainfoColor(t,n){let S=new Set([zn(n,`data`)]);S.add(In(Hn(t),`..`,`..`,`..`,`..`));for(let t of S){let n=walk(zn(t,`metainfo`)).filter(t=>/\.metainfo\.xml(\.in)?$/.test(t)).sort();for(let t of n){let n=parseMetainfoBranding(readFileSync(t,`utf8`));if(n!==null)return n}}return null}var oq,sq,cq=__esmMin(()=>{af(),o_(),Xn(),_R(),aq(),wH(),oq=`Android/src/main/res`,sq={command:`android-icons`,description:`Generate the Android launcher icon and splash logo of a NativeScript app from its one app icon.`,builder:t=>t.option(`resources`,{description:"The App_Resources directory. Default: `gjsify.androidIcons.resources`, else `appResourcesPath` of nativescript.config.ts, else App_Resources.",type:`string`}).option(`icon`,{description:"The scalable app icon SVG. Default: `gjsify.androidIcons.icon`, else the hicolor icon under data/icons (here or in a sibling package).",type:`string`}).option(`background`,{description:"Adaptive-icon background colour. Default: `gjsify.androidIcons.background`, else the metainfo light `<branding>` colour, else white.",type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the generated files are missing or the inputs changed.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).androidIcons??{},C=[`nativescript.config.ts`,`nativescript.config.js`].map(t=>zn(n,t)).find(t=>existsSync(t)),N=resolveResourcesName({flag:t.resources,configured:S.resources,nativescriptConfig:C===void 0?null:readFileSync(C,`utf8`)}),F=In(n,N),{icon:I,symbolic:H}=discoverIcon(n,t.icon??S.icon),W=resolveBackground({flag:t.background,configured:S.background,fromMetainfo:findMetainfoColor(I,n)}),q=new Uint8Array(readFileSync(I)),Y=H===null?null:new Uint8Array(readFileSync(H)),X=hashInputs({icon:q,symbolic:Y,background:W}),Z=planAndroidIcons({background:W,monochrome:Y!==null}),te=zn(F,tq);if(t.check===!0){let t=checkStamp(existsSync(te)?readFileSync(te,`utf8`):null,X,t=>existsSync(zn(F,...t.split(`/`))));return t.current?void 0:(process.stderr.write(`gjsify android-icons: ${N} ${t.reason}; run \`gjsify android-icons\` and commit it\n`),process.exit(1))}let ne=zn(F,...oq.split(`/`)),re=mkdtempSync(zn(tmpdir(),`gjsify-android-icons-`));try{let t=new Map([[`plain`,I]]);for(let n of[`round`,`foreground`]){let S=zn(re,`${n}.svg`);writeFileSync(S,wrapperSvg(n,q,W)),t.set(n,S)}if(Y!==null){let n=zn(re,`monochrome.svg`);writeFileSync(n,wrapperSvg(`monochrome`,Y,W)),t.set(`monochrome`,n)}for(let[n,S]of t){let t=Z.png.filter(t=>n===`plain`?t.kind===`legacy`||t.kind===`splash`:t.kind===n),C=await rasterizeSvg({svg:S,sizes:[...new Set(t.map(t=>t.size))],command:`gjsify android-icons`});for(let n of t){let t=zn(ne,n.path);mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,C.get(n.size))}}}finally{rmSync(re,{recursive:!0,force:!0})}for(let t of Z.text){let n=zn(ne,t.path);mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,t.content)}rmSync(zn(ne,`drawable`,`ic_launcher_foreground.xml`),{force:!0}),writeFileSync(te,`${JSON.stringify(buildStamp(X,Z,oq),null,2)}\n`),process.stdout.write(`gjsify android-icons: wrote ${Z.png.length+Z.text.length} files under ${Bn(n,ne).split(qn).join(`/`)} from ${Bn(n,I)}\n`)}catch(t){return process.stderr.write(`gjsify android-icons: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function globToRegExp(t){let n=t.split(`*`).map(t=>t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)).join(`.*`);return RegExp(`^${n}$`,`i`)}function isIgnored(t,n){return n.some(n=>{let S=globToRegExp(n);return S.test(t.name)||t.email!==``&&S.test(t.email)})}function parsePerson(t){let n=/^(.*?)\s*<([^>]*)>\s*$/.exec(t.trim());return n?{name:n[1].trim(),email:n[2].trim()}:{name:t.trim(),email:``}}function poLanguage(t){let n=On.basename(t);return/\.po$/i.test(n)?n.slice(0,-3):void 0}function bump(t,n){t.set(n,(t.get(n)??0)+1)}function rank(t){return[...t.entries()].sort(([t,n],[S,C])=>C-n||(t<S?-1:+(t>S))).map(([t])=>t)}function appendUnseen(t,n,S){let C=new Set(t);for(let N of n??[]){let n=N.trim();n&&!C.has(n)&&!S(n)&&(C.add(n),t.push(n))}}function buildCredits(t,n={}){let S=n.ignore??lq,C=n.overrides??{},N=C.exclude??[],excluded=t=>isIgnored({name:t,email:``},N),F=new Map,I=new Map,H=t.map(t=>{let n=new Set;for(let C of[t.author,...t.coAuthors])C.name&&!isIgnored(C,S)&&!excluded(C.name)&&n.add(C.name);let C=new Set,N=!1;for(let n of t.files){isTranslationFile(n)||(N=!0);let t=poLanguage(n);t&&C.add(t)}return{names:n,languages:C,touchesCode:N}}),W=new Map;for(let{names:t,languages:n}of H){if(t.size!==1||n.size!==1)continue;let[S]=t,[C]=n,N=W.get(S);N||W.set(S,N=new Set),N.add(C)}for(let{names:t,languages:n,touchesCode:S}of H){let C=t.size>1||n.size>1;for(let N of t){S&&bump(F,N);let t=W.get(N);for(let S of n){if(C&&t&&!t.has(S))continue;let n=I.get(S);n||I.set(S,n=new Map),bump(n,N)}}}let q={developers:rank(F),translators:{},supporters:[]},Y=C.excludeTranslators??{};for(let t of[...I.keys()].sort()){let n=[...Y[`*`]??[],...Y[t]??[]],S=rank(I.get(t)).filter(t=>!isIgnored({name:t,email:``},n));S.length&&(q.translators[t]=S)}appendUnseen(q.developers,C.developers,excluded);for(let t of Object.keys(C.translators??{}).sort()){let n=q.translators[t]??[];appendUnseen(n,C.translators[t],excluded),n.length&&(q.translators[t]=n)}return q.translators=Object.fromEntries(Object.entries(q.translators).sort(([t],[n])=>t<n?-1:1)),appendUnseen(q.supporters,C.supporters,excluded),q}function parseGitLog(t){let n=[];for(let S of t.split(dq)){if(!S.trim())continue;let[t=``,C=``,N=``,F=``]=S.split(uq);n.push({author:{name:t.trim(),email:C.trim()},coAuthors:N.split(fq).map(t=>t.trim()).filter(Boolean).map(parsePerson),files:F.split(`
1291
1291
  `).map(t=>t.trim()).filter(Boolean)})}return n}function git(t,n,S){let C=spawnSync(`git`,[...n],{cwd:t,encoding:`utf8`,input:S,maxBuffer:1<<30});if(C.error)throw Error(`cannot run git: ${C.error.message}`);if(C.status!==0)throw Error(`git ${n.join(` `)} failed: ${String(C.stderr).trim()}`);return String(C.stdout)}function mapTrailers(t,n){let S=new Set;for(let t of n)for(let n of t.coAuthors)n.email&&S.add(`${n.name} <${n.email}>`);if(S.size===0)return;let C=[...S],N=git(t,[`check-mailmap`,`--stdin`],C.join(`
1292
1292
  `)+`
1293
1293
  `).split(`
1294
- `).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,dq));return mapTrailers(t,n),n}function asStringList(t,n){if(!Array.isArray(t)||t.some(t=>typeof t!=`string`))throw Error(`${n} must be an array of strings`);return t}function parseOverrides(t,n=`overrides`){let S;try{S=JSON.parse(t)}catch(t){throw Error(`${n} is not valid JSON: ${t instanceof Error?t.message:String(t)}`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n} must be a JSON object`);let C=S,N=new Set([...fq,...pq]);for(let t of Object.keys(C))if(!N.has(t))throw Error(`${n} has an unknown key "${t}" (known: ${[...N].join(`, `)})`);let F={};for(let t of fq)C[t]!==void 0&&(F[t]=asStringList(C[t],`${n}.${t}`));for(let t of pq){let S=C[t];if(S===void 0)continue;if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n}.${t} must map a language to an array of names`);let N={};for(let[C,F]of Object.entries(S))N[C]=asStringList(F,`${n}.${t}.${C}`);F[t]=N}return F}function serializeCredits(t){return JSON.stringify(t,null,2)+`
1295
- `}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var sq,cq,lq,uq,isTranslationFile,dq,fq,pq,mq=__esmMin(()=>{cv(),Xn(),sq=[`*[bot]`,`github-actions`,`Weblate`,`Weblate (bot)`,`Hosted Weblate`,`Weblate Translation Memory`,`LibreTranslate`,`Claude`,`*@anthropic.com`,`noreply-mt-*@weblate.org`,`hosted@weblate.org`,`*[bot]@users.noreply.github.com`],cq=``,lq=``,uq=``,isTranslationFile=t=>/\.pot?$/i.test(t),dq=[`-c`,`core.quotepath=off`,`log`,`--no-merges`,`--use-mailmap`,`--name-only`,`--format=${lq}%aN${cq}%aE${cq}%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x1d)${cq}`],fq=[`developers`,`supporters`,`exclude`],pq=[`translators`,`excludeTranslators`]}),hq,gq,_q,vq=__esmMin(()=>{_R(),mq(),af(),Xn(),hq=`credits.json`,gq=`credits.overrides.json`,_q={command:`credits`,description:`Write the project’s contributors (developers, translators per language) from the git history as JSON, names only.`,builder:t=>t.option(`output`,{alias:`o`,description:`File to write. Default: \`gjsify.credits.output\`, else ${hq}.`,type:`string`}).option(`overrides`,{description:`Hand-kept additions and exclusions. Default: \`gjsify.credits.overrides\`, else ${gq} when it exists.`,type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the file on disk differs from what the history gives.`,type:`boolean`,default:!1}).option(`stdout`,{description:`Print the JSON instead of writing it.`,type:`boolean`,default:!1}).conflicts(`check`,`stdout`),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).credits??{},C=In(n,t.output??S.output??hq),N=t.overrides??S.overrides,F=In(n,N??gq),I;if(existsSync(F))I=parseOverrides(readFileSync(F,`utf8`),N??gq);else if(N!==void 0)throw Error(`cannot read the overrides file ${N}`);let H=buildCredits(readCommits(n),{ignore:S.ignore??sq,overrides:I}),W=serializeCredits(H);if(t.stdout===!0)process.stdout.write(W);else if(t.check===!0){let n=existsSync(C)?readFileSync(C,`utf8`):null;if(isStale(n,H))return process.stderr.write(`gjsify credits: ${t.output??S.output??hq} is ${n===null?`missing`:`stale`}; run \`gjsify credits\` and commit it\n`),process.exit(1)}else writeFileSync(C,W)}catch(t){return process.stderr.write(`gjsify credits: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}}),yq,bq=__esmMin(()=>{xh(),DB(),yq={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??ph,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
1294
+ `).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,pq));return mapTrailers(t,n),n}function asStringList(t,n){if(!Array.isArray(t)||t.some(t=>typeof t!=`string`))throw Error(`${n} must be an array of strings`);return t}function parseOverrides(t,n=`overrides`){let S;try{S=JSON.parse(t)}catch(t){throw Error(`${n} is not valid JSON: ${t instanceof Error?t.message:String(t)}`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n} must be a JSON object`);let C=S,N=new Set([...mq,...hq]);for(let t of Object.keys(C))if(!N.has(t))throw Error(`${n} has an unknown key "${t}" (known: ${[...N].join(`, `)})`);let F={};for(let t of mq)C[t]!==void 0&&(F[t]=asStringList(C[t],`${n}.${t}`));for(let t of hq){let S=C[t];if(S===void 0)continue;if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n}.${t} must map a language to an array of names`);let N={};for(let[C,F]of Object.entries(S))N[C]=asStringList(F,`${n}.${t}.${C}`);F[t]=N}return F}function serializeCredits(t){return JSON.stringify(t,null,2)+`
1295
+ `}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var lq,uq,dq,fq,isTranslationFile,pq,mq,hq,gq=__esmMin(()=>{cv(),Xn(),lq=[`*[bot]`,`github-actions`,`Weblate`,`Weblate (bot)`,`Hosted Weblate`,`Weblate Translation Memory`,`LibreTranslate`,`Claude`,`*@anthropic.com`,`noreply-mt-*@weblate.org`,`hosted@weblate.org`,`*[bot]@users.noreply.github.com`],uq=``,dq=``,fq=``,isTranslationFile=t=>/\.pot?$/i.test(t),pq=[`-c`,`core.quotepath=off`,`log`,`--no-merges`,`--use-mailmap`,`--name-only`,`--format=${dq}%aN${uq}%aE${uq}%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x1d)${uq}`],mq=[`developers`,`supporters`,`exclude`],hq=[`translators`,`excludeTranslators`]}),_q,vq,yq,bq=__esmMin(()=>{_R(),gq(),af(),Xn(),_q=`credits.json`,vq=`credits.overrides.json`,yq={command:`credits`,description:`Write the project’s contributors (developers, translators per language) from the git history as JSON, names only.`,builder:t=>t.option(`output`,{alias:`o`,description:`File to write. Default: \`gjsify.credits.output\`, else ${_q}.`,type:`string`}).option(`overrides`,{description:`Hand-kept additions and exclusions. Default: \`gjsify.credits.overrides\`, else ${vq} when it exists.`,type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the file on disk differs from what the history gives.`,type:`boolean`,default:!1}).option(`stdout`,{description:`Print the JSON instead of writing it.`,type:`boolean`,default:!1}).conflicts(`check`,`stdout`),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).credits??{},C=In(n,t.output??S.output??_q),N=t.overrides??S.overrides,F=In(n,N??vq),I;if(existsSync(F))I=parseOverrides(readFileSync(F,`utf8`),N??vq);else if(N!==void 0)throw Error(`cannot read the overrides file ${N}`);let H=buildCredits(readCommits(n),{ignore:S.ignore??lq,overrides:I}),W=serializeCredits(H);if(t.stdout===!0)process.stdout.write(W);else if(t.check===!0){let n=existsSync(C)?readFileSync(C,`utf8`):null;if(isStale(n,H))return process.stderr.write(`gjsify credits: ${t.output??S.output??_q} is ${n===null?`missing`:`stale`}; run \`gjsify credits\` and commit it\n`),process.exit(1)}else writeFileSync(C,W)}catch(t){return process.stderr.write(`gjsify credits: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}}),xq,Sq=__esmMin(()=>{xh(),DB(),xq={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??ph,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
1296
1296
  `)+`
1297
1297
  `),process.exit(1);let F;try{F=await whoami(S,n)}catch(t){let n=t instanceof Error?t.message:String(t);return N?process.stdout.write(`${JSON.stringify({error:n,registry:C})}\n`):(process.stderr.write(`gjsify whoami: ${n}\n`),process.stderr.write(`Registry: ${C}\n`)),process.exit(1)}if(F.username&&F.username.length>0){N?process.stdout.write(`${JSON.stringify({username:F.username,registry:C})}\n`):(process.stdout.write(`Logged in as: ${F.username}\n`),process.stdout.write(`Registry: ${C}\n`));return}N?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:C})}\n`):process.stderr.write([`gjsify whoami: token appears dead or revoked (registry returned an empty whoami response).`,``,`Refresh via: npm login`,`Then verify: gjsify whoami`,``,`For the @gjsify scope, see AGENTS.md > "New @gjsify/* package: first-publish + Trusted Publisher bootstrap".`].join(`
1298
1298
  `)+`
@@ -1301,12 +1301,12 @@ ${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
1301
1301
  `)+`
1302
1302
  `),S}function removeAuthToken(t){let n=userconfigNpmrcPath(),S=authTokenKey(t),C=readUserconfig(n);if(!C)return{path:n,removed:!1};let N=C.split(`
1303
1303
  `),F=N.filter(t=>!t.replace(/\s+/g,``).startsWith(`${S}=`)),I=F.length!==N.length;return I&&writeUserconfig(n,F.join(`
1304
- `)),{path:n,removed:I}}var xq=__esmMin(()=>{af(),o_(),Xn()});async function runLogin(t){let n=await loadNpmrc(t.cwd??process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,{username:N,password:F}=await promptCredentials(t.username);if(!N)throw new LoginError(`gjsify login: a username is required.`);if(!F)throw new LoginError(`gjsify login: a password is required.`);let I=`Basic ${btoa(`${N}:${F}`)}`,H=`${C}-/user/org.couchdb.user:${encodeURIComponent(N)}`,W={_id:`org.couchdb.user:${N}`,name:N,password:F,type:`user`,roles:[],date:void 0};function authHeaders(t){let n={authorization:I,"content-type":`application/json`,accept:`*/*`};return t&&(n[`npm-otp`]=t),n}async function putUser(t,n){return fetch(`${H}${t}`,{method:`PUT`,headers:authHeaders(n),body:JSON.stringify(W)})}let q=typeof t.otp==`string`&&t.otp.length>0,Y=t.otp??readCachedOtp(C),X=await putUser(``,Y);if(X.status===401&&!q){let t=(X.headers.get(`www-authenticate`)??``).toLowerCase(),n=await X.clone().text().catch(()=>``);if(t.includes(`otp`)||/one-time pass/i.test(n)){if(clearCachedOtp(C),Y=await promptLine(`This operation requires a one-time password.
1305
- Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,Sq,Cq=__esmMin(()=>{_e(),xh(),DB(),xq(),zK(),HK(),LoginError=class extends Error{constructor(t){super(t),this.name=`LoginError`}},Sq={command:`login`,description:"Log in to an npm registry (Node-free `npm login`). Prompts for username + password (hidden) and writes the token to ~/.npmrc. Use --otp for 2FA. Web-OAuth flow is not supported — this is npm's legacy credentials flow.",builder:t=>t.option(`registry`,{description:`Registry URL to log in to. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Associate the login with a scope (e.g. @gjsify) — resolves that scope's registry from .npmrc.`,type:`string`}).option(`username`,{description:`Username (prompted if omitted).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code (prompted on demand if omitted).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` JSON on success.",type:`boolean`}),handler:async t=>{try{let{username:n,registry:S,npmrcPath:C}=await runLogin({registry:t.registry,scope:t.scope,username:t.username,otp:t.otp});t.json?process.stdout.write(`${JSON.stringify({username:n,registry:S})}\n`):process.stdout.write(`Logged in as ${n} on ${S}\n(token written to ${C})\n`)}catch(t){if(t instanceof LoginError)return ge.error(t.message),process.exit(1);throw t}}}}),wq,Tq=__esmMin(()=>{xh(),DB(),xq(),HK(),wq={command:`logout`,description:"Log out of an npm registry (Node-free `npm logout`). Revokes the token on the registry (best-effort) and removes it from ~/.npmrc.",builder:t=>t.option(`registry`,{description:`Registry URL to log out of. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Log out of a scope's registry (e.g. @gjsify) — resolved from .npmrc.`,type:`string`}).option(`json`,{description:"Emit `{registry, revoked, removed}` JSON.",type:`boolean`}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,N=resolveAuthForUrl(`${C}-/whoami`,n),F=!1;if(N?.startsWith(`Bearer `)){let t=N.slice(7);try{F=(await fetch(`${C}-/user/token/${encodeURIComponent(t)}`,{method:`DELETE`,headers:{authorization:N,accept:`*/*`}})).ok}catch{}}clearCachedOtp(C);let{path:I,removed:H}=removeAuthToken(C);t.json?process.stdout.write(`${JSON.stringify({registry:C,revoked:F,removed:H})}\n`):H?process.stdout.write(`Logged out of ${C}${F?` (token revoked)`:``}\n(removed from ${I})\n`):process.stdout.write(`No token for ${C} found in ${I} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(t){let n=t,S=Eq[0];for(let t=0;t<8&&!existsSync(zn(n,...S));t++){let t=Hn(n);if(t===n)return[];n=t}let C=[];for(let t of Eq){let S=zn(n,...t);if(!existsSync(S))continue;let N;try{N=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let n of N){if(!n.isDirectory())continue;let N=zn(S,n.name),F=zn(N,`package.json`);if(existsSync(F))try{let S=JSON.parse(readFileSync(F,`utf8`));if(!S||typeof S.name!=`string`||S.name.length===0)continue;C.push({location:N,relativeLocation:zn(...t,n.name),name:S.name,version:typeof S.version==`string`?S.version:`0.0.0`,manifest:S,private:S.private===!0})}catch{}}}return C}function mergePublishables(t,n){let S=new Set(t.map(t=>t.name));return[...t,...discoverNonWorkspacePublishables(n).filter(t=>!S.has(t.name))]}var Eq,Dq=__esmMin(()=>{af(),Xn(),Eq=[[`packages`,`node-gi`],[`packages`,`napi`],[`packages`,`node-runtime`]]});function trustUrl(t,n){return`${t.endsWith(`/`)?t.slice(0,-1):t}/-/package/${escapePackageName(n)}/trust`}function githubTrustBody(t){let n={repository:t.repository,workflow_ref:{file:normalizeWorkflowFile(t.workflow)}};return t.environment&&(n.environment=t.environment),[{type:`github`,claims:n,permissions:t.permissions&&t.permissions.length>0?t.permissions:[Oq]}]}function normalizeWorkflowFile(t){return t.split(`/`).pop()??t}function validateRepository(t){let n=t.split(`/`);return n.length===2&&n[0].length>0&&n[1].length>0}function matchesGithubTrust(t,n){if(t.type!==`github`)return!1;let S=t.claims?.repository,C=t.claims?.workflow_ref?.file;return S===n.repository&&C===normalizeWorkflowFile(n.workflow)}function classifyTrustList(t,n,S){return t===404?`unpublished`:t===401?`auth-required`:t>=200&&t<300?(Array.isArray(n)?n:[]).some(t=>matchesGithubTrust(t,S))?`trusted`:`untrusted`:`error`}function parseRepoFromGitRemote(t){let n=t.trim();if(!n)return null;n=n.replace(/^git\+/,``),n=n.replace(/\.git$/,``);let S=n.match(/^[^/@]+@[^:]+:(.+)$/);if(S)return twoSegments(S[1]);let C=n.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return C?twoSegments(C[1]):null}function twoSegments(t){let n=t.split(`/`).filter(t=>t.length>0);return n.length<2?null:`${n[n.length-2]}/${n[n.length-1]}`}var Oq,kq=__esmMin(()=>{Ch(),Oq=`createPackage`});function createTrustRequester(t){return async(n,S,C)=>{let doFetch=N=>{let F=buildHeaders(S,{npmrc:t.npmrc});F.accept=`application/json`,C!==void 0&&(F[`content-type`]=`application/json`),N&&(F[`npm-otp`]=N);let I={method:n,headers:F};return C!==void 0&&(I.body=JSON.stringify(C)),fetch(S,I)},N=await withOtpRetry(doFetch,t.otpProvider),F=await N.text().catch(()=>``),I;try{I=F?JSON.parse(F):void 0}catch{}return{status:N.status,json:I,text:F,headers:N.headers}}}function firstLine(t){return t.split(`
1306
- `)[0].slice(0,200)}var Aq,jq=__esmMin(()=>{_e(),cv(),af(),Xn(),xh(),GI(),Dq(),DB(),gK(),GK(),kq(),Aq={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 ${ph}).`,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??ph;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.
1307
- (\`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=zn(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)??ph,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}`);return W||(ge.log(),ge.log(hK)),process.exit(1)}W||(ge.log(),ge.log(hK))}}}});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(`
1304
+ `)),{path:n,removed:I}}var Cq=__esmMin(()=>{af(),o_(),Xn()});async function runLogin(t){let n=await loadNpmrc(t.cwd??process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,{username:N,password:F}=await promptCredentials(t.username);if(!N)throw new LoginError(`gjsify login: a username is required.`);if(!F)throw new LoginError(`gjsify login: a password is required.`);let I=`Basic ${btoa(`${N}:${F}`)}`,H=`${C}-/user/org.couchdb.user:${encodeURIComponent(N)}`,W={_id:`org.couchdb.user:${N}`,name:N,password:F,type:`user`,roles:[],date:void 0};function authHeaders(t){let n={authorization:I,"content-type":`application/json`,accept:`*/*`};return t&&(n[`npm-otp`]=t),n}async function putUser(t,n){return fetch(`${H}${t}`,{method:`PUT`,headers:authHeaders(n),body:JSON.stringify(W)})}let q=typeof t.otp==`string`&&t.otp.length>0,Y=t.otp??readCachedOtp(C),X=await putUser(``,Y);if(X.status===401&&!q){let t=(X.headers.get(`www-authenticate`)??``).toLowerCase(),n=await X.clone().text().catch(()=>``);if(t.includes(`otp`)||/one-time pass/i.test(n)){if(clearCachedOtp(C),Y=await promptLine(`This operation requires a one-time password.
1305
+ Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,wq,Tq=__esmMin(()=>{_e(),xh(),DB(),Cq(),VK(),WK(),LoginError=class extends Error{constructor(t){super(t),this.name=`LoginError`}},wq={command:`login`,description:"Log in to an npm registry (Node-free `npm login`). Prompts for username + password (hidden) and writes the token to ~/.npmrc. Use --otp for 2FA. Web-OAuth flow is not supported — this is npm's legacy credentials flow.",builder:t=>t.option(`registry`,{description:`Registry URL to log in to. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Associate the login with a scope (e.g. @gjsify) — resolves that scope's registry from .npmrc.`,type:`string`}).option(`username`,{description:`Username (prompted if omitted).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code (prompted on demand if omitted).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` JSON on success.",type:`boolean`}),handler:async t=>{try{let{username:n,registry:S,npmrcPath:C}=await runLogin({registry:t.registry,scope:t.scope,username:t.username,otp:t.otp});t.json?process.stdout.write(`${JSON.stringify({username:n,registry:S})}\n`):process.stdout.write(`Logged in as ${n} on ${S}\n(token written to ${C})\n`)}catch(t){if(t instanceof LoginError)return ge.error(t.message),process.exit(1);throw t}}}}),Eq,Dq=__esmMin(()=>{xh(),DB(),Cq(),WK(),Eq={command:`logout`,description:"Log out of an npm registry (Node-free `npm logout`). Revokes the token on the registry (best-effort) and removes it from ~/.npmrc.",builder:t=>t.option(`registry`,{description:`Registry URL to log out of. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Log out of a scope's registry (e.g. @gjsify) — resolved from .npmrc.`,type:`string`}).option(`json`,{description:"Emit `{registry, revoked, removed}` JSON.",type:`boolean`}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,N=resolveAuthForUrl(`${C}-/whoami`,n),F=!1;if(N?.startsWith(`Bearer `)){let t=N.slice(7);try{F=(await fetch(`${C}-/user/token/${encodeURIComponent(t)}`,{method:`DELETE`,headers:{authorization:N,accept:`*/*`}})).ok}catch{}}clearCachedOtp(C);let{path:I,removed:H}=removeAuthToken(C);t.json?process.stdout.write(`${JSON.stringify({registry:C,revoked:F,removed:H})}\n`):H?process.stdout.write(`Logged out of ${C}${F?` (token revoked)`:``}\n(removed from ${I})\n`):process.stdout.write(`No token for ${C} found in ${I} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(t){let n=t,S=Oq[0];for(let t=0;t<8&&!existsSync(zn(n,...S));t++){let t=Hn(n);if(t===n)return[];n=t}let C=[];for(let t of Oq){let S=zn(n,...t);if(!existsSync(S))continue;let N;try{N=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let n of N){if(!n.isDirectory())continue;let N=zn(S,n.name),F=zn(N,`package.json`);if(existsSync(F))try{let S=JSON.parse(readFileSync(F,`utf8`));if(!S||typeof S.name!=`string`||S.name.length===0)continue;C.push({location:N,relativeLocation:zn(...t,n.name),name:S.name,version:typeof S.version==`string`?S.version:`0.0.0`,manifest:S,private:S.private===!0})}catch{}}}return C}function mergePublishables(t,n){let S=new Set(t.map(t=>t.name));return[...t,...discoverNonWorkspacePublishables(n).filter(t=>!S.has(t.name))]}var Oq,kq=__esmMin(()=>{af(),Xn(),Oq=[[`packages`,`node-gi`],[`packages`,`napi`],[`packages`,`node-runtime`]]});function trustUrl(t,n){return`${t.endsWith(`/`)?t.slice(0,-1):t}/-/package/${escapePackageName(n)}/trust`}function githubTrustBody(t){let n={repository:t.repository,workflow_ref:{file:normalizeWorkflowFile(t.workflow)}};return t.environment&&(n.environment=t.environment),[{type:`github`,claims:n,permissions:t.permissions&&t.permissions.length>0?t.permissions:[Aq]}]}function normalizeWorkflowFile(t){return t.split(`/`).pop()??t}function validateRepository(t){let n=t.split(`/`);return n.length===2&&n[0].length>0&&n[1].length>0}function matchesGithubTrust(t,n){if(t.type!==`github`)return!1;let S=t.claims?.repository,C=t.claims?.workflow_ref?.file;return S===n.repository&&C===normalizeWorkflowFile(n.workflow)}function classifyTrustList(t,n,S){return t===404?`unpublished`:t===401?`auth-required`:t>=200&&t<300?(Array.isArray(n)?n:[]).some(t=>matchesGithubTrust(t,S))?`trusted`:`untrusted`:`error`}function parseRepoFromGitRemote(t){let n=t.trim();if(!n)return null;n=n.replace(/^git\+/,``),n=n.replace(/\.git$/,``);let S=n.match(/^[^/@]+@[^:]+:(.+)$/);if(S)return twoSegments(S[1]);let C=n.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return C?twoSegments(C[1]):null}function twoSegments(t){let n=t.split(`/`).filter(t=>t.length>0);return n.length<2?null:`${n[n.length-2]}/${n[n.length-1]}`}var Aq,jq=__esmMin(()=>{Ch(),Aq=`createPackage`});function createTrustRequester(t){return async(n,S,C)=>{let doFetch=N=>{let F=buildHeaders(S,{npmrc:t.npmrc});F.accept=`application/json`,C!==void 0&&(F[`content-type`]=`application/json`),N&&(F[`npm-otp`]=N);let I={method:n,headers:F};return C!==void 0&&(I.body=JSON.stringify(C)),fetch(S,I)},N=await withOtpRetry(doFetch,t.otpProvider),F=await N.text().catch(()=>``),I;try{I=F?JSON.parse(F):void 0}catch{}return{status:N.status,json:I,text:F,headers:N.headers}}}function firstLine(t){return t.split(`
1306
+ `)[0].slice(0,200)}var Mq,Nq=__esmMin(()=>{_e(),cv(),af(),Xn(),xh(),GI(),kq(),DB(),vK(),qK(),jq(),Mq={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 ${ph}).`,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??ph;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.
1307
+ (\`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=zn(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)??ph,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}`);return W||(ge.log(),ge.log(_K)),process.exit(1)}W||(ge.log(),ge.log(_K))}}}});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(`
1308
1308
  `))}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(zn(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(`
1309
- `))}var Mq=__esmMin(()=>{af(),cv(),GI(),Xn(),Dq(),kq(),qI()});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,Nq),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)??ph,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 Nq,RateLimitGate,Pq=__esmMin(()=>{xh(),kq(),Nq=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){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;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`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Fq,Iq,Lq=__esmMin(()=>{_e(),cv(),xh(),GI(),DB(),GK(),gK(),FK(),qK(),jq(),Cq(),hB(),hv(),Mq(),kq(),Pq(),Fq=4,Iq={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 ${ph}).`,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:Fq}).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??ph,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.`)),S||(log(),log(hK)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}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,zq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${zq}`,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`&&Rq.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 Rq,zq,Bq=__esmMin(()=>{Xn(),Rq=[`/usr/`,`/opt/`,`/snap/`],zq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,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 ${Vq}\`)\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 \`${Hq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(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===Vq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===Vq&&typeof n.version==`string`)return n.version}n=Hn(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 Vq,Hq,Uq,Wq,Gq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),HI(),Gz(),Bq(),Yz(),$z(),Az(),Mz(),Vq=`@gjsify/cli`,Hq=`latest`,Uq={command:`self-update`,description:`Update the installed ${Vq} 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=zn(zn(n.prefix,`node_modules`,Vq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${Vq}: 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??Hq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${Vq}@${I} ...`);let W;try{W=await fetchPackument(Vq)}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 ${Vq}. 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 ${Vq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${Vq}@${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([Vq],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:Wq,binDir:n.binDir,resolvedBin:resolveBinOnPath(Wq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${Vq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${Vq} 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.`)}},Wq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
1309
+ `))}var Pq=__esmMin(()=>{af(),cv(),GI(),Xn(),kq(),jq(),qI()});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,Fq),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)??ph,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 Fq,RateLimitGate,Iq=__esmMin(()=>{xh(),jq(),Fq=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){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;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`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Lq,Rq,zq=__esmMin(()=>{_e(),cv(),xh(),GI(),DB(),qK(),vK(),LK(),YK(),Nq(),Tq(),hB(),hv(),Pq(),jq(),Iq(),Lq=4,Rq={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 ${ph}).`,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:Lq}).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??ph,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.`)),S||(log(),log(_K)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}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,Vq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${Vq}`,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`&&Bq.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 Bq,Vq,Hq=__esmMin(()=>{Xn(),Bq=[`/usr/`,`/opt/`,`/snap/`],Vq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,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 ${Uq}\`)\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 \`${Wq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(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===Uq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===Uq&&typeof n.version==`string`)return n.version}n=Hn(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 Uq,Wq,Gq,Kq,qq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),HI(),Gz(),Hq(),Yz(),$z(),Az(),Mz(),Uq=`@gjsify/cli`,Wq=`latest`,Gq={command:`self-update`,description:`Update the installed ${Uq} 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=zn(zn(n.prefix,`node_modules`,Uq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${Uq}: 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??Wq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${Uq}@${I} ...`);let W;try{W=await fetchPackument(Uq)}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 ${Uq}. 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 ${Uq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${Uq}@${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([Uq],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:Kq,binDir:n.binDir,resolvedBin:resolveBinOnPath(Kq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${Uq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${Uq} 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.`)}},Kq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
1310
1310
  /**
1311
1311
  * gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
1312
1312
  * on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
@@ -1882,28 +1882,28 @@ async function main() {
1882
1882
  }
1883
1883
 
1884
1884
  await main();
1885
- `}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 Kq,qq,Jq=__esmMin(()=>{_e(),af(),Xn(),Kq=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,qq={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=In(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=In(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`]??Kq;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`)}}}),Yq,Xq=__esmMin(()=>{_e(),af(),gz(),Yz(),Az(),Mz(),Yq={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=Bn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${qn}`)&&!Rn(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=zn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
1886
- `).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 Zq,Qq=__esmMin(()=>{_e(),af(),Xn(),Yz(),Zq={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=zn(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(`
1885
+ `}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 Jq,Yq,Xq=__esmMin(()=>{_e(),af(),Xn(),Jq=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,Yq={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=In(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=In(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`]??Jq;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`)}}}),Zq,Qq=__esmMin(()=>{_e(),af(),gz(),Yz(),Az(),Mz(),Zq={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=Bn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${qn}`)&&!Rn(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=zn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
1886
+ `).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 $q,eJ=__esmMin(()=>{_e(),af(),Xn(),Yz(),$q={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=zn(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(`
1887
1887
  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=Bn(n,t);return S===``||S===`..`||S.startsWith(`..${qn}`)||Rn(S)?null:qn===`/`?S:S.split(qn).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=Hn(t)){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}return compileGitignore(S.split(`
1888
- `),n)}var $q=__esmMin(()=>{af(),Xn()});function externalParserFor(t,n=!1){if(nJ.has(t))return null;let S=Wn(t).slice(1),C=tJ[t]??(S?eJ[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(zn(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?In(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=In(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(In(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Un(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(Hn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Bn(n,t).split(qn).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(zn(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=zn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(rJ.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=Hn(S);if(t===S)break;S=t;let n=readGitignoreFile(zn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(zn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=Hn(n)){if(existsSync(zn(n,`.git`))||existsSync(zn(n,`.jj`)))return n;if(Hn(n)===n)return null}}function configIn(t){for(let n of iJ){let S=zn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=In(t);;n=Hn(n)){let t=configIn(n);if(t)return t;if(Hn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=Hn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(Hn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=Hn(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(`
1889
- `,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,eJ,tJ,nJ,rJ,iJ,aJ=__esmMin(()=>{af(),Xn(),$q(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),eJ={...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`},tJ={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},nJ=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`]),rJ=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),iJ=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=In(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 oJ,sJ=__esmMin(()=>{_e(),af(),Xn(),xV(),aJ(),oJ={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`,In(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=>` ${Bn(n,t)||t}`).join(`
1890
- `);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}}}}),cJ,lJ=__esmMin(()=>{Xn(),xV(),cJ={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`,In(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}}}}),uJ,dJ=__esmMin(()=>{Xn(),xV(),uJ={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`,In(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`,In(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,fJ=__esmMin(()=>{Xd(),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 pJ=__esmMin(()=>{HI()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=zn(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 hJ){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 gJ.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(` ${_J.bold}${t.name}${_J.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=zn(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(` ${_J.bold}${t.name}${_J.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(` ${_J.bold}${n.name}${_J.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(`
1891
- [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 _J.red;case`minor`:return _J.yellow;case`patch`:return _J.green;case`prerelease`:return _J.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)+_J.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+_J.reset;ge.log(I),ge.log(` `.repeat(F+2)+_J.dim+`─`.repeat(n+S+C+N+16)+_J.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${_J.magenta}⚠ ${_J.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+_J.dim+`${H.occurrences.length}`.padEnd(S)+_J.reset+` `+_J.dim+renderDeclaredCell(H).padEnd(C)+_J.reset+` `+Y+H.latestVersion.padEnd(N)+_J.reset+` `+Y+H.diff+_J.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${_J.magenta}⚠${_J.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(`
1892
- Select upgrades: comma- or space-separated indices, `+_J.bold+`a`+_J.reset+` for all, ranges like `+_J.bold+`1-3`+_J.reset+`, or `+_J.bold+`ENTER`+_J.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=zn(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(`
1888
+ `),n)}var tJ=__esmMin(()=>{af(),Xn()});function externalParserFor(t,n=!1){if(iJ.has(t))return null;let S=Wn(t).slice(1),C=rJ[t]??(S?nJ[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(zn(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?In(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=In(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(In(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Un(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(Hn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Bn(n,t).split(qn).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(zn(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=zn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(aJ.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=Hn(S);if(t===S)break;S=t;let n=readGitignoreFile(zn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(zn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=Hn(n)){if(existsSync(zn(n,`.git`))||existsSync(zn(n,`.jj`)))return n;if(Hn(n)===n)return null}}function configIn(t){for(let n of oJ){let S=zn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=In(t);;n=Hn(n)){let t=configIn(n);if(t)return t;if(Hn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=Hn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(Hn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=Hn(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(`
1889
+ `,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,nJ,rJ,iJ,aJ,oJ,sJ=__esmMin(()=>{af(),Xn(),tJ(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),nJ={...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`},rJ={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},iJ=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`]),aJ=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),oJ=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=In(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 cJ,lJ=__esmMin(()=>{_e(),af(),Xn(),xV(),sJ(),cJ={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`,In(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=>` ${Bn(n,t)||t}`).join(`
1890
+ `);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}}}}),uJ,dJ=__esmMin(()=>{Xn(),xV(),uJ={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`,In(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}}}}),fJ,pJ=__esmMin(()=>{Xn(),xV(),fJ={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`,In(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`,In(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,mJ=__esmMin(()=>{Xd(),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 hJ=__esmMin(()=>{HI()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=zn(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 _J){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 vJ.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(` ${yJ.bold}${t.name}${yJ.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=zn(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(` ${yJ.bold}${t.name}${yJ.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(` ${yJ.bold}${n.name}${yJ.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(`
1891
+ [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 yJ.red;case`minor`:return yJ.yellow;case`patch`:return yJ.green;case`prerelease`:return yJ.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)+yJ.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+yJ.reset;ge.log(I),ge.log(` `.repeat(F+2)+yJ.dim+`─`.repeat(n+S+C+N+16)+yJ.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${yJ.magenta}⚠ ${yJ.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+yJ.dim+`${H.occurrences.length}`.padEnd(S)+yJ.reset+` `+yJ.dim+renderDeclaredCell(H).padEnd(C)+yJ.reset+` `+Y+H.latestVersion.padEnd(N)+yJ.reset+` `+Y+H.diff+yJ.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${yJ.magenta}⚠${yJ.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(`
1892
+ Select upgrades: comma- or space-separated indices, `+yJ.bold+`a`+yJ.reset+` for all, ranges like `+yJ.bold+`1-3`+yJ.reset+`, or `+yJ.bold+`ENTER`+yJ.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=zn(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(`
1893
1893
  `)?`
1894
1894
  `:``),W),`utf-8`),C++}}return C}function keepUntouchedLines(t,n,S){let C=t.split(`
1895
1895
  `),N=n.split(`
1896
1896
  `);return C.length===N.length?N.map((t,n)=>S.some(n=>t.includes(`"${n}"`))?t:C[n]).join(`
1897
- `):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:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(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 mJ,hJ,gJ,_J,vJ=__esmMin(()=>{_e(),af(),Xn(),o_(),fJ(),HI(),xh(),GI(),qI(),pJ(),mJ={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(In(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.`)}},hJ=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],gJ=new Set([`x`,`X`,`*`,``]),_J={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=In(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=In(t.baseDir,F),H=Un(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>bJ.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=Un(t.name,Wn(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
1897
+ `):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:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(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 gJ,_J,vJ,yJ,bJ=__esmMin(()=>{_e(),af(),Xn(),o_(),mJ(),HI(),xh(),GI(),qI(),hJ(),gJ={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(In(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.`)}},_J=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],vJ=new Set([`x`,`X`,`*`,``]),yJ={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=In(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=In(t.baseDir,F),H=Un(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>SJ.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=Un(t.name,Wn(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
1898
1898
  `)}\n`:`export {};
1899
- `,X=`${t.header}\n\n${Y}`,Z=zn(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 yJ,bJ,xJ=__esmMin(()=>{_e(),Vd(),Xn(),yJ=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],bJ=/\.(ts|tsx|mts|cts)$/}),SJ,CJ=__esmMin(()=>{_e(),xJ(),SJ={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:[...yJ],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)}}}),wJ,TJ=__esmMin(()=>{_e(),eu(),Xn(),cr(),gL(),dL(),af(),KG(),UR(),qI(),hv(),Fz(),wJ={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=process.cwd(),N=tscArgsUnderLink(n.length>0?n:S,existsSync(devLinkPath(devLinkRoot(C)))),F=[pathToFileURL(`${findWorkspaceRoot(C)??C}/__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=zn(Hn(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(C)),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,...N],{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,...N],{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(`
1900
- `).map(t=>t.trim()).filter(Boolean)}var EJ=__esmMin(()=>{af()});function isResolvableScript(t){return jJ.test(t)&&!DJ.some(n=>n.test(t))&&!AJ.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))OJ.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)OJ.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 DJ)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 AJ){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=>kJ.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 DJ,OJ,kJ,AJ,jJ,MJ=__esmMin(()=>{GI(),DJ=[/^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$/],OJ=[/\.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$/],kJ=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],AJ=[{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`}],jJ=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
1899
+ `,X=`${t.header}\n\n${Y}`,Z=zn(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 xJ,SJ,CJ=__esmMin(()=>{_e(),Vd(),Xn(),xJ=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],SJ=/\.(ts|tsx|mts|cts)$/}),wJ,TJ=__esmMin(()=>{_e(),CJ(),wJ={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:[...xJ],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)}}}),EJ,DJ=__esmMin(()=>{_e(),eu(),Xn(),cr(),gL(),dL(),af(),JG(),UR(),qI(),hv(),Fz(),EJ={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=process.cwd(),N=tscArgsUnderLink(n.length>0?n:S,existsSync(devLinkPath(devLinkRoot(C)))),F=[pathToFileURL(`${findWorkspaceRoot(C)??C}/__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=zn(Hn(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(C)),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,...N],{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,...N],{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(`
1900
+ `).map(t=>t.trim()).filter(Boolean)}var OJ=__esmMin(()=>{af()});function isResolvableScript(t){return NJ.test(t)&&!kJ.some(n=>n.test(t))&&!MJ.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))AJ.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)AJ.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 kJ)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 MJ){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=>jJ.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 kJ,AJ,jJ,MJ,NJ,PJ=__esmMin(()=>{GI(),kJ=[/^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$/],AJ=[/\.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$/],jJ=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],MJ=[{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`}],NJ=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
1901
1901
  `).filter(t=>!S.test(t)).join(`
1902
1902
  `)}function scriptNamePattern(t){let n=On.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(`
1903
- `),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===NJ||S===PJ||n.set(S,stripCommentLines(S,C));let S=t.get(NJ),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(PJ);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(IJ.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(NJ),manifestReads(S)&&C.push(PJ),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=zn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>FJ)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var NJ,PJ,FJ,IJ,escapeRe,LJ=__esmMin(()=>{cv(),af(),Xn(),NJ=`.github/workflows/main.yml`,PJ=`package.json`,FJ=2*1024*1024,IJ=/^(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(`
1903
+ `),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===FJ||S===IJ||n.set(S,stripCommentLines(S,C));let S=t.get(FJ),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(IJ);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(RJ.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(FJ),manifestReads(S)&&C.push(IJ),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=zn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>LJ)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var FJ,IJ,LJ,RJ,escapeRe,zJ=__esmMin(()=>{cv(),af(),Xn(),FJ=`.github/workflows/main.yml`,IJ=`package.json`,LJ=2*1024*1024,RJ=/^(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(`
1904
1904
  `).filter(Boolean)}function emit(t,n){if(t===`json`){process.stdout.write(JSON.stringify(n)+`
1905
1905
  `);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:
1906
- `),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(zJ.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 RJ,zJ,BJ=__esmMin(()=>{cv(),af(),EJ(),GI(),MJ(),LJ(),qI(),RJ={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)}},zJ=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),VJ=__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(()=>(UR(),HR));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(()=>(VR(),BR)),{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(()=>(UR(),HR));return spawnSupervised(t(),[n],I)}let[H,W]=_v[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=In(t,S),N=In(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=Hn(N);return F===In(t)?!1:C===F||C.startsWith(`${F}${qn}`)}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(In(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 HJ=__esmMin(()=>{_e(),af(),Xn(),Ue(),tB(),hv(),vv()});function readPackage$4(t){try{return JSON.parse(readFileSync(zn(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=zn(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(`
1906
+ `),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(VJ.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 BJ,VJ,HJ=__esmMin(()=>{cv(),af(),OJ(),GI(),PJ(),zJ(),qI(),BJ={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)}},VJ=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),UJ=__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(()=>(UR(),HR));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(()=>(VR(),BR)),{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(()=>(UR(),HR));return spawnSupervised(t(),[n],I)}let[H,W]=_v[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=In(t,S),N=In(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=Hn(N);return F===In(t)?!1:C===F||C.startsWith(`${F}${qn}`)}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(In(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 WJ=__esmMin(()=>{_e(),af(),Xn(),Ue(),tB(),hv(),vv()});function readPackage$4(t){try{return JSON.parse(readFileSync(zn(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=zn(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(`
1907
1907
  `),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.
1908
1908
  import { collectStoryModules, runStorybook } from '@gjsify/storybook';
1909
1909
  ${C}
@@ -1912,10 +1912,10 @@ await runStorybook({
1912
1912
  applicationId: ${JSON.stringify(n)},${F}
1913
1913
  stories: collectStoryModules([${N}]),
1914
1914
  });
1915
- `}var UJ,WJ=__esmMin(()=>{_e(),af(),Xn(),P_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),UJ={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=In(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=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(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 ${Bn(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 ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(FX(),PX)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));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(()=>(HJ(),VJ));await re({dir:N,dirLabel:Bn(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=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
1915
+ `}var GJ,KJ=__esmMin(()=>{_e(),af(),Xn(),P_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),GJ={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=In(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=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(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 ${Bn(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 ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(VX(),BX)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));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(()=>(WJ(),UJ));await re({dir:N,dirLabel:Bn(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=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
1916
1916
  publishes a page or a store listing. Add it, then run this again:
1917
1917
 
1918
- npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${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=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(mR(),dR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(FX(),PX));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(UR(),HR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var GJ=__esmMin(()=>{_e(),cv(),af(),Xn(),P_(),UR(),__name$1(generateEntry$3,`generateEntry`)}),KJ,qJ=__esmMin(()=>{Xn(),GJ(),KJ={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(`drafts`,{description:"build: include blog posts marked `draft: true`",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; without it the default falls back to gjs.",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=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});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??Hn(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 JJ=__esmMin(()=>{Xn(),sR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var YJ,XJ=__esmMin(()=>{_e(),af(),Xn(),JJ(),vv(),P_(),__name$1(readPackage$3,`readPackage`),YJ={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:gv,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:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(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`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(FX(),PX)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(HJ(),VJ));await X({dir:W,dirLabel:Bn(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(zn(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.
1918
+ npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${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=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(mR(),dR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(VX(),BX));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(UR(),HR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var qJ=__esmMin(()=>{_e(),cv(),af(),Xn(),P_(),UR(),__name$1(generateEntry$3,`generateEntry`)}),JJ,YJ=__esmMin(()=>{Xn(),qJ(),JJ={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(`drafts`,{description:"build: include blog posts marked `draft: true`",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; without it the default falls back to gjs.",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=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});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??Hn(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 XJ=__esmMin(()=>{Xn(),sR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var ZJ,QJ=__esmMin(()=>{_e(),af(),Xn(),XJ(),vv(),P_(),__name$1(readPackage$3,`readPackage`),ZJ={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:gv,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:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(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`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(VX(),BX)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(WJ(),UJ));await X({dir:W,dirLabel:Bn(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(zn(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.
1919
1919
  import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
1920
1920
 
1921
1921
  await runDevtoolsMcp(storybookProfile(${F}${I}));
@@ -1935,22 +1935,24 @@ await runDevtoolsMcp({
1935
1935
  version: ${JSON.stringify(C)},
1936
1936
  busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
1937
1937
  });
1938
- `}var ZJ,QJ=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),ZJ={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=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(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(()=>(FX(),PX));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(()=>(VR(),BR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1938
+ `}var $J,eY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),$J={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=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(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(()=>(VX(),BX));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(()=>(VR(),BR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1939
1939
  import system from 'system';
1940
1940
 
1941
1941
  import { runDevtoolsCli } from '@gjsify/devtools-mcp';
1942
1942
 
1943
1943
  system.exit(await runDevtoolsCli(system.programArgs));
1944
- `}var $J,eY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),$J={command:`devtools <operation> [operands..]`,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=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(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(()=>(FX(),PX));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(()=>(VR(),BR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(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.
1944
+ `}var tY,nY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),tY={command:`devtools <operation> [operands..]`,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=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(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(()=>(VX(),BX));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(()=>(VR(),BR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(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.
1945
1945
  import { runBrowserDevtools } from '@gjsify/devtools-browser';
1946
1946
 
1947
1947
  await runBrowserDevtools({
1948
1948
  applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
1949
1949
  });
1950
- `}var tY,nY=__esmMin(()=>{_e(),af(),Xn(),tY={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=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(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(()=>(FX(),PX));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(()=>(VR(),BR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function signJwt(t,n,S){let C=Math.floor(S/1e3),N=b64url(JSON.stringify({alg:`HS256`,typ:`JWT`})),F=b64url(JSON.stringify({iss:t,jti:randomBytes(16).toString(`hex`),iat:C,exp:C+oY})),I=createHmac(`sha256`,n).update(`${N}.${F}`).digest();return`${N}.${F}.${b64url(I)}`}function validationLines(t){if(typeof t!=`object`||!t)return[];let n=t.messages;if(!Array.isArray(n))return[];let S=[];for(let t of n){if(typeof t!=`object`||!t)continue;let n=t;n.type!==void 0&&n.type!==`error`||(typeof n.message==`string`?S.push(n.message):typeof n.description==`string`&&S.push(n.description))}return S}var rY,iY,aY,oY,sY,b64url,createAmoBackend,cY=__esmMin(()=>{gl(),af(),Xn(),EY(),rY=`amo`,iY=`https://addons.mozilla.org/api/v5`,aY=400,oY=60,sY=`the JWT was rejected — check AMO_WEB_EXT_API_KEY / AMO_WEB_EXT_API_SECRET (addons.mozilla.org → Developer Hub → Manage API Keys) and that this machine's clock is correct; AMO refuses a JWT whose iat/exp are off.`,b64url=t=>Buffer.from(t).toString(`base64url`),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(rY,t),I=n.now??(()=>Date.now()),H=`${iY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,aY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(rY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(rY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?sY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(rY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(rY,n):new StoreApiError(rY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(rY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${iY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(rY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(rY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${iY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(rY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}return{store:rY,upload,publish,status,operation,verifyCredentials}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(lY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${dY}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${uY}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${uY}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${dY}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${uY}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${uY}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${fY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var lY,uY,dY,fY,versionOf,pY=__esmMin(()=>{af(),EY(),lY=`https://oauth2.googleapis.com/token`,uY=`https://chromewebstore.googleapis.com`,dY=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,fY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var mY,hY,gY,_Y,vY,createEdgeBackend,yY=__esmMin(()=>{af(),EY(),mY=`edge`,hY=`https://api.addons.microsoftedge.microsoft.com`,gY=`00000000-0000-0000-0000-000000000000`,_Y=400,vY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(mY,t),C],I=`${hY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,_Y),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(mY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(mY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?vY:`${vY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(mY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(mY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(mY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(mY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(mY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(mY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${gY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:mY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return bY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=xY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return xY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=wY.includes(t)||/token|secret|key/.test(t)?CY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(CY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=TY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var bY,xY,SY,CY,wY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,TY,EY=__esmMin(()=>{cY(),pY(),yY(),bY=[`chrome`,`edge`,`amo`],xY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},SY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},CY=`<redacted>`,wY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${SY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
1950
+ `}var rY,iY=__esmMin(()=>{_e(),af(),Xn(),rY={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=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(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(()=>(VX(),BX));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(()=>(VR(),BR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function amoLocale(t){let[n=``,S]=t.replace(/_/g,`-`).split(`-`),C=n.toLowerCase(),N=aY.find(t=>t.toLowerCase()===(S===void 0?C:`${C}-${S.toLowerCase()}`));if(N!==void 0)return N;if(C===`en`)return`en-US`;if(aY.includes(C))return C;let F=aY.filter(t=>t.startsWith(`${C}-`));return F.length===1?F[0]:null}function readAmoListing(t){let n=zn(t,`amo`);if(!existsSync(n))throw Error(`${n} does not exist. Run \`gjsify webext listing --store amo\` first.`);let S=[],C={},N={},F={},I={},H=readdirSync(n).filter(t=>statSync(zn(n,t)).isDirectory()&&existsSync(zn(n,t,`description.txt`))).sort();for(let t of H){let H=zn(n,t),W=amoLocale(t);if(W===null){S.push(`language "${t}" has no AMO locale (known: ${aY.join(`, `)}).`);continue}let q=Object.entries(F).find(([,t])=>t===W);if(q!==void 0){S.push(`languages "${q[0]}" and "${t}" both map to AMO locale ${W}.`);continue}F[t]=W;let Y=readText(H,`description.txt`);Y===void 0||Y===``?S.push(`${t}/description.txt is missing or empty.`):C[W]=Y;let X=readText(H,`privacy.txt`);X!==void 0&&X!==``&&(N[W]=X);let Z=readText(H,`reviewer-notes.txt`);Z!==void 0&&Z!==``&&(I[t]=Z)}if(H.length===0&&S.push(`${n} holds no language directory with a description.txt.`),S.length>0)throw Error(`the AMO listing in ${n} cannot be sent:\n ${S.join(`
1951
+ `)}`);let W=`en`in I?`en`:Object.keys(I)[0];return{input:{description:C,...Object.keys(N).length>0?{privacyPolicy:N}:{},...W===void 0?{}:{approvalNotesText:I[W]}},locales:F}}var aY,readText,oY=__esmMin(()=>{af(),Xn(),aY=`ar.bg.ca.cak.cs.da.de.dsb.el.en-CA.en-GB.en-US.es.eu.fa.fi.fr.fy-NL.ga-IE.he.hsb.hu.id.it.ja.ka.kab.ko.mk.mn.nl.pl.pt-BR.pt-PT.ro.ru.sk.sl.sq.sv-SE.tr.uk.vi.zh-CN.zh-TW`.split(`.`),readText=(t,n)=>{let S=zn(t,n);return existsSync(S)?readFileSync(S,`utf8`).trim():void 0}});async function runListingUpload(t){let{approvalNotesText:n,...S}=readAmoListing(In(t.listingRoot)).input;if(t.notesVersion!==void 0&&n===void 0)throw Error(`--notes-version is set but no amo/<lang>/reviewer-notes.txt exists.`);let C={...S,...t.notesVersion!==void 0&&n!==void 0?{approvalNotes:{version:t.notesVersion,text:n}}:{}};if(t.dryRun){t.out(`addons.mozilla.org listing: dry run — nothing is sent, no request is made.`);let lines=(n,S)=>{for(let[C,N]of Object.entries(S))t.out(` would send ${n} [${C}]: ${N.length} chars`)};return lines(`description`,C.description),C.privacyPolicy!==void 0&&lines(`privacy_policy (eula_policy)`,C.privacyPolicy),C.approvalNotes!==void 0&&t.out(` would send approval_notes (version ${C.approvalNotes.version}): ${C.approvalNotes.text.length} chars`),t.out(` name and summary are never sent: AMO takes the name from the manifest, and the store summary is the manifest description.`),0}let N=t.backend();if(N.updateListing===void 0)throw Error(`this store has no listing API; only AMO takes listing texts.`);let F=await N.updateListing(C),I=0;for(let n of F.fields)n.verdict!==`match`&&(I+=1),t.out(` ${n.field}${n.locale===void 0?``:` [${n.locale}]`}: ${n.verdict} — ${n.detail}`);return t.out(I===0?`addons.mozilla.org listing: ${F.fields.length} field(s) written and read back, all match.`:`addons.mozilla.org listing: ${I} of ${F.fields.length} field(s) NOT confirmed by the read-back.`),I===0?0:1}var sY=__esmMin(()=>{Xn(),oY()});function signJwt(t,n,S){let C=Math.floor(S/1e3),N=b64url(JSON.stringify({alg:`HS256`,typ:`JWT`})),F=b64url(JSON.stringify({iss:t,jti:randomBytes(16).toString(`hex`),iat:C,exp:C+dY})),I=createHmac(`sha256`,n).update(`${N}.${F}`).digest();return`${N}.${F}.${b64url(I)}`}function validationLines(t){if(typeof t!=`object`||!t)return[];let n=t.messages;if(!Array.isArray(n))return[];let S=[];for(let t of n){if(typeof t!=`object`||!t)continue;let n=t;n.type!==void 0&&n.type!==`error`||(typeof n.message==`string`?S.push(n.message):typeof n.description==`string`&&S.push(n.description))}return S}var cY,lY,uY,dY,fY,b64url,sameText,pY,normalizeText,createAmoBackend,mY=__esmMin(()=>{gl(),af(),Xn(),MY(),cY=`amo`,lY=`https://addons.mozilla.org/api/v5`,uY=400,dY=60,fY=`the JWT was rejected — check AMO_WEB_EXT_API_KEY / AMO_WEB_EXT_API_SECRET (addons.mozilla.org → Developer Hub → Manage API Keys) and that this machine's clock is correct; AMO refuses a JWT whose iat/exp are off.`,b64url=t=>Buffer.from(t).toString(`base64url`),sameText=(t,n)=>normalizeText(t)===normalizeText(n),pY={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`},normalizeText=t=>t.replace(/<\/?a\b[^>]*>/gi,``).replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos));/gi,(t,n,S,C)=>{if(C!==void 0)return pY[C.toLowerCase()];let N=n===void 0?parseInt(S,16):Number(n);return N<=1114111?String.fromCodePoint(N):t}).replace(/\r\n/g,`
1952
+ `).trim(),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(cY,t),I=n.now??(()=>Date.now()),H=`${lY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,uY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(cY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(cY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?fY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(cY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(cY,n):new StoreApiError(cY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(cY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${lY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(cY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(cY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${lY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(cY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}let versionRef=t=>/^\d+$/.test(t)?t:`v${encodeURIComponent(t)}`;async function readBack(t,n){try{return{body:await json(await send(`GET`,t),n)}}catch(t){if(t instanceof StoreApiError)return{unread:t.message};throw t}}function compareLocales(t,n,S,C){return Object.entries(n).map(([n,N])=>{let F={field:t,locale:n,sent:N.length};if(C!==null)return{...F,verdict:`unread`,detail:C.unread};if(typeof S!=`object`||!S)return{...F,verdict:`unread`,detail:`AMO returned no per-locale ${t}.`};let I=S[n];return typeof I==`string`?sameText(I,N)?{...F,verdict:`match`,detail:`read back ${I.length} chars.`}:{...F,verdict:`mismatch`,detail:`AMO holds ${I.length} chars, sent ${N.length}.`}:{...F,verdict:`mismatch`,detail:`AMO holds no ${t} for ${n}.`}})}async function updateListing(t){await send(`PATCH`,`${H}/`,{json:{description:t.description}}),t.privacyPolicy!==void 0&&await send(`PATCH`,`${H}/eula_policy/`,{json:{privacy_policy:t.privacyPolicy}});let n=t.approvalNotes,S=n===void 0?``:`${H}/versions/${versionRef(n.version)}/`;n!==void 0&&await send(`PATCH`,S,{json:{approval_notes:n.text}});let C=[],N=await readBack(`${H}/`,`the add-on detail`),F=`unread`in N?N:null,I=`body`in N?N.body:{};if(C.push(...compareLocales(`description`,t.description,I.description,F)),t.privacyPolicy!==void 0){let n=await readBack(`${H}/eula_policy/`,`the eula_policy`);C.push(...compareLocales(`privacy_policy`,t.privacyPolicy,`body`in n?n.body.privacy_policy:void 0,`unread`in n?n:null))}if(n!==void 0){let t=await readBack(S,`the version detail`),N={field:`approval_notes`,sent:n.text.length};`unread`in t?C.push({...N,verdict:`unread`,detail:t.unread}):typeof t.body.approval_notes==`string`?sameText(t.body.approval_notes,n.text)?C.push({...N,verdict:`match`,detail:`read back ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`mismatch`,detail:`AMO holds ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`unread`,detail:`AMO returned no approval_notes.`})}return{fields:C}}return{store:cY,upload,publish,status,operation,verifyCredentials,updateListing}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(hY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${_Y}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${gY}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${gY}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${_Y}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${gY}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${gY}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${vY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var hY,gY,_Y,vY,versionOf,yY=__esmMin(()=>{af(),MY(),hY=`https://oauth2.googleapis.com/token`,gY=`https://chromewebstore.googleapis.com`,_Y=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,vY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var bY,xY,SY,CY,wY,createEdgeBackend,TY=__esmMin(()=>{af(),MY(),bY=`edge`,xY=`https://api.addons.microsoftedge.microsoft.com`,SY=`00000000-0000-0000-0000-000000000000`,CY=400,wY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(bY,t),C],I=`${xY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,CY),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(bY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(bY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?wY:`${wY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(bY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(bY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(bY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(bY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(bY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(bY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${SY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:bY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return EY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=DY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return DY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=AY.includes(t)||/token|secret|key/.test(t)?kY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(kY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=jY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var EY,DY,OY,kY,AY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,jY,MY=__esmMin(()=>{mY(),yY(),TY(),EY=[`chrome`,`edge`,`amo`],DY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},OY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},kY=`<redacted>`,AY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${OY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
1951
1953
  `)+`
1952
- Set them in the environment, never in package.json (ADR 0077 § Amendment 1).`),this.store=t,this.missing=n,this.name=`StoreCredentialsMissingError`}},StoreUnsupportedError=class extends Error{store;constructor(t,n){super(`gjsify webext submit: ${SY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${SY[t].label}: version ${n} is already there — nothing to submit.`),this.store=t,this.version=n,this.name=`StoreVersionAlreadyThereError`}},StoreInReviewError=class extends Error{store;constructor(t,n){super(`${SY[t].label}: a submission is in review — ${n}`),this.store=t,this.name=`StoreInReviewError`}},StoreApiError=class extends Error{store;httpStatus;constructor(t,n,S){super(`${SY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},TY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(kY,t)}function retryBackoffFor(t,n){return stepFrom(n?jY:AY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||NY.includes(n)?!0:n>=500&&n<600}function isThrottled(t){return t instanceof StoreApiError&&t.httpStatus===429}function retryDecision(t,n){return isRepeatableFailure(t)?n===`publish`&&t instanceof StoreApiError&&t.httpStatus===void 0?`verify-first`:`retry`:`fatal`}async function driveSubmission(t,n={}){let{backend:S}=t,C=t.upload.version,N=n.now??(()=>Date.now()),F=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),I=n.timeoutMs??6e5,H=n.secrets??[],W=N(),q=[],Y=0,X=0,Z=0,clean=t=>redactSecrets(t,H),note=t=>n.log?.(clean(`gjsify webext submit: ${t}`)),remaining=()=>I-(N()-W),endPhase=(t,n)=>{q.push({phase:t,requests:Z,elapsedMs:N()-W,detail:clean(n)}),Z=0},finish=(t,n)=>({store:S.store,version:C,verdict:t,exitCode:DY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:OY.includes(t)}),fromError=(t,n,S)=>{let C=n instanceof Error?n.message:String(n);return endPhase(t,C),n instanceof StoreVersionAlreadyThereError?finish(`already-there`,C):n instanceof StoreInReviewError?finish(`in-review`,C):S?finish(`failed`,`${C} — repeated 3x or until the ${I} ms deadline; the failure class is repeatable, so calling again later may work.`):finish(`rejected`,C)},call=async(t,n)=>{for(let S=0;;S++){Y++,Z++;try{return{kind:`value`,value:await n()}}catch(n){if(isIdempotentSkip(n))return{kind:`error`,error:n,exhausted:!1};let C=retryDecision(n,t);if(C===`fatal`)return{kind:`error`,error:n,exhausted:!1};if(C===`verify-first`)return{kind:`lost`,error:n};let N=remaining();if(S>=3||N<=0)return{kind:`error`,error:n,exhausted:!0};let I=Math.min(retryBackoffFor(S,isThrottled(n)),N);note(`${t} failed with a repeatable error, retry ${S+1} of 3 in ${I} ms — `+(n instanceof Error?n.message:String(n))),X++,await F(I)}}},aboutOurVersion=t=>t.version===void 0||t.version===C,waitFor=async(t,n,I,H)=>{let q=S.operation;if(q===void 0&&I!==void 0&&t===`publish`)return endPhase(n,H),{kind:`end`,result:finish(`unverifiable`,`${H} The publish was accepted and the ${S.store} backend declares no operation() to read ${I} with, so whether a submission exists cannot be established from here. It may well be in review — check the dashboard; the fix is operation() on that backend.`)};for(let H=0;;H++){if(q!==void 0&&I!==void 0){let N=await call(`read`,()=>q.call(S,t,I,C));if(N.kind===`error`)return{kind:`end`,result:fromError(n,N.error,N.exhausted)};if(N.kind===`value`&&N.value.state===`succeeded`)return{kind:`done`,detail:N.value.detail};N.kind===`value`&&note(`${t} operation ${I}: ${N.value.detail}`)}else{let C=await call(`read`,()=>S.status());if(C.kind===`error`)return{kind:`end`,result:fromError(n,C.error,C.exhausted)};if(C.kind===`value`){let S=C.value;if(S.state===`rejected`)return endPhase(n,S.detail),{kind:`end`,result:finish(`rejected`,S.detail)};if(t===`upload`&&S.ingesting!==!0||t===`publish`&&aboutOurVersion(S)&&(S.state===`published`||S.state===`in-review`))return{kind:`done`,detail:S.detail};note(`status while waiting for the ${t}: ${S.detail}`)}}let Y=remaining();if(Y<=0){let S=`the ${t} was accepted and had not resolved after ${N()-W} ms`+(I===void 0?``:` (operation ${I})`)+'. Nothing is lost: call `gjsify webext submit` again — it reads the store\'s state first and will report "already there" or "in review" if this one landed meanwhile. Raise --timeout to wait longer.';return endPhase(n,S),{kind:`end`,result:finish(`unresolved`,S)}}await F(Math.min(pollBackoffFor(H),Y))}};note(`${S.store}: uploading ${C} from ${t.upload.zipPath}`);let te=await call(`upload`,()=>S.upload(t.upload));if(te.kind===`error`)return fromError(`upload`,te.error,te.exhausted);if(te.kind===`lost`)return fromError(`upload`,te.error,!1);if(endPhase(`upload`,te.value.detail),!te.value.ingested){let t=await waitFor(`upload`,`await-upload`,te.value.operationId,te.value.detail);if(t.kind===`end`)return t.result;endPhase(`await-upload`,t.detail)}if(t.publish===void 0)return finish(`uploaded`,`${C} is in the ${S.store} draft and was NOT submitted — pass --submit to ask for review.`);let ne=t.publish,re=0;for(;;){note(`${S.store}: asking for review of ${C}`);let t=await call(`publish`,()=>S.publish(ne));if(t.kind===`error`)return fromError(`publish`,t.error,t.exhausted);if(t.kind===`lost`){let n=t.error instanceof Error?t.error.message:String(t.error);note(`the publish request got no answer (${n}) — asking the store whether it arrived`);let C=await call(`read`,()=>S.status());if(C.kind!==`value`)return fromError(`publish`,C.error,C.kind===`error`&&C.exhausted);let N=C.value;if(N.state===`rejected`)return endPhase(`publish`,N.detail),finish(`rejected`,N.detail);if(aboutOurVersion(N)&&(N.state===`in-review`||N.state===`published`))return endPhase(`publish`,N.detail),finish(N.state===`published`?`published`:`submitted`,`the publish request got no answer, and the store reports it arrived: ${N.detail}`);if(N.state===`draft`&&aboutOurVersion(N)&&re<MY&&remaining()>0){re++,X++,note(`the store still holds a draft (${N.detail}) — sending the publish request once more`);continue}let F=`the publish request got no answer (${n}) and the store's own state does not say whether it arrived: ${N.detail}. The request was NOT repeated — a second one would risk a second submission. Call \`gjsify webext submit\` again once the store settles; it reads the state first.`;return endPhase(`publish`,F),finish(`unresolved`,F)}let n=t.value;if(endPhase(`publish`,n.detail),n.state===`rejected`)return finish(`rejected`,n.detail);if(n.state===`published`)return finish(`published`,n.detail);if(n.state===`in-review`)return finish(`submitted`,n.detail);let N=await waitFor(`publish`,`await-publish`,n.operationId,n.detail);return N.kind===`end`?N.result:(endPhase(`await-publish`,N.detail),finish(`submitted`,N.detail))}}var DY,OY,kY,AY,jY,MY,stepFrom,NY,PY=__esmMin(()=>{EY(),DY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},OY=[`in-review`,`failed`,`unresolved`],kY=[2e3,4e3,8e3,15e3,3e4],AY=[1e3,2e3,4e3],jY=[5e3,15e3,3e4],MY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,NY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.id}.zip`)}function preflightStoreJson(t,n,S){let C;try{C=JSON.parse(t)}catch{return{problems:[`${S} is not valid JSON — regenerate it with \`gjsify webext listing\`.`],manual:[]}}let N=C;if(N.version!==1||!Array.isArray(N.fields))return{problems:[`${S} is not a store.json (version 1) — regenerate it with \`gjsify webext listing\`.`],manual:[]};if(N.store!==n)return{problems:[`${S} is for store "${String(N.store)}", expected "${n}".`],manual:[]};let F=[],I=[];for(let t of N.fields){let n=t.label??t.key??`(unnamed field)`;t.status===`manual`?I.push(n):t.required===!0&&t.status===`missing`&&F.push(`required field "${n}" is missing in ${S}.`)}return{problems:F,manual:I}}function secretsOf(t,n){return xY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function describeResult(t,n){let S=[`${n} ${t.version}: ${t.verdict} — ${t.detail}`];for(let n of t.phases)S.push(` ${n.phase}: ${n.detail} (${n.requests} request(s), ${n.elapsedMs} ms)`);return t.retryable&&S.push(` Calling again later, unchanged, can make progress.`),S}async function runSubmit(t){let{env:n,project:S}=t,C=asStoreId(t.store),N=C===null?[]:secretsOf(C,n),clean=t=>redactSecrets(t,N),out=n=>t.out(clean(n)),err=n=>t.err(clean(n));try{if(C===null)throw Error(`gjsify webext submit: unknown store "${t.store}".`);let F=SY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);if(t.submit&&!isTagRef(n.GITHUB_REF))throw Error(`gjsify webext submit: --submit asks the store for review and runs only on a tag ($GITHUB_REF must start with refs/tags/). Without --submit the zip is uploaded (AMO: validated, no version created).`);let I;if(t.timeoutSeconds!==void 0){if(!Number.isFinite(t.timeoutSeconds)||t.timeoutSeconds<0)throw Error(`gjsify webext submit: --timeout is a number of seconds, 0 or more.`);I=t.timeoutSeconds*1e3}let H=FY[C],W=zn(In(S.root,t.listingDir??`dist/listing`),H,`store.json`);if(!existsSync(W))throw Error(`gjsify webext submit: ${W} does not exist. Run \`gjsify webext listing --store ${H}\` first; it is the preflight for the listing the dashboard will ask about.`);let q=preflightStoreJson(readFileSync(W,`utf8`),H,W);if(q.problems.length>0)throw Error(`gjsify webext submit: preflight failed, nothing was sent:\n ${q.problems.join(`
1953
- `)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,te={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:Z},ne=(t.createBackend??createStoreBackend)(C,n,te);if(t.dryRun)return ne.verifyCredentials===void 0?(out(`${F.label}: dry run — credentials are set; this backend has no read-only check, so they are unverified. Nothing was uploaded.`),0):(await ne.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),0);let re=await driveSubmission({backend:ne,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:Z,secrets:N}),ie=re.exitCode===0?out:err;for(let t of describeResult(re,F.label))ie(t);return DY[re.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var FY,IY=__esmMin(()=>{af(),Xn(),EY(),PY(),FY={chrome:`cws`,edge:`edge`,amo:`amo`}});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/${Un(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/${Un(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(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var LY=__esmMin(()=>{af(),Xn(),wH()});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(()=>(mR(),dR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++RY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++RY}`;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(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(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(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var RY,zY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),RY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(KY.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(BY,n=>{let S=HY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!qY.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:WY.test(n)?`esm`:`iife`,output:F}),n.replace(HY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(VY,t=>{if(!GY.test(t))return t;let n=UY.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace(UY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var BY,VY,HY,UY,WY,GY,KY,qY,JY=__esmMin(()=>{Xn(),BY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,VY=/<link\b[^>]*>/gi,HY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,UY=/\bhref\s*=\s*(["'])([^"']+)\1/i,WY=/\btype\s*=\s*["']module["']/i,GY=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,KY=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,qY=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=YY?n:YY}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(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=zn(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:zn(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:zn(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,zn(H,t.output))}writeFileSync(zn(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=zn(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,zn(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(zn(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(`
1954
- - `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var YY,XY=__esmMin(()=>{_e(),af(),Xn(),lG(),LY(),zY(),JY(),YY=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!ZY.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${ZY.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?$Y.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 ZY,QY,$Y,eX=__esmMin(()=>{ZY=[`chrome`,`edge`,`firefox`,`opera`,`safari`],QY=[`chrome-mv3`,`firefox-mv3`],$Y=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=>Rn(t)?t:In(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??[...QY];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=nX.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${nX.join(`, `)} exists.`):W=zn(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(!rX.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??tX;(!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(!rX.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=zn(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 ${zn(n,`package.json`)}:\n - ${C.join(`
1955
- - `)}`);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 resolveSubmitProject(t,n){let S=t.gjsify?.webext;if(S!==void 0&&!isRecord(S))throw Error("gjsify webext: `gjsify.webext` must be an object.");let C=S??{},N=[],F=C.targets??[...QY],I=[];if(!Array.isArray(F)||F.length===0)N.push("`targets` must be a non-empty array of target names.");else for(let t of F)try{I.push(parseWebextTarget(String(t)))}catch(t){N.push(t.message.replace(/^gjsify webext: /,``))}if(N.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${N.join(`
1956
- - `)}`);return{root:n,name:C.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,outDir:Rn(C.outDir??`.output`)?C.outDir:In(n,C.outDir??`.output`)}}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 tX,nX,rX,iX=__esmMin(()=>{af(),Xn(),eX(),tX=[16,32,48,128],nX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],rX=/^[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 zn(S.XDG_CACHE_HOME||zn(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=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var aX,oX=__esmMin(()=>{af(),o_(),Xn(),dL(),eX(),aX="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=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function loadSubmitProject(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveSubmitProject(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(()=>(FX(),PX)),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?In(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=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var sX,cX,lX,uX,dX,fX,pX,mX,hX=__esmMin(()=>{_e(),af(),Xn(),GJ(),IY(),XY(),iX(),oX(),sX={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},cX={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},lX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},uX={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,sX).option(`out-dir`,cX).option(`define`,lX).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)},dX={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,sX).option(`out-dir`,cX).option(`define`,lX),handler:t=>runBuild(t,!0)},fX={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`,{...sX,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,lX).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?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(aX);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?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(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(()=>(HJ(),VJ));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(()=>(HJ(),VJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),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})}},pX={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}},mX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,type:`string`,choices:[`chrome`,`edge`,`amo`],demandOption:!0}).option(`zip`,{description:"The zip to upload (default: what `webext zip` writes for the store's target).",type:`string`}).option(`dry-run`,{description:`Check the credentials with one read call; upload nothing.`,type:`boolean`,default:!1}).option(`submit`,{description:`Ask for review after the upload. Refused unless $GITHUB_REF is a tag.`,type:`boolean`,default:!1}).option(`timeout`,{description:`Seconds to wait for the store to resolve an upload or submission (default: 600).`,type:`number`}).option(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-dir`,{description:"Where `webext listing` wrote store.json (default: dist/listing).",type:`string`}).epilog(`Credentials come from the environment only (see ADR 0077 § Amendment 1). Exit codes: 0 done or nothing to do, 1 rejected or failed, 3 accepted but unresolved (run again), 4 unverifiable. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. A submission stuck in review is cancelled in the Chrome dashboard (:cancelSubmission); this command never does.`),handler:async t=>{let n=process.cwd(),S=await runSubmit({store:t.store,zip:t.zip?In(n,t.zip):void 0,dryRun:t.dryRun,submit:t.submit,timeoutSeconds:t.timeout,listingDir:t.listingDir,sourceZip:t.source?In(n,t.source):void 0,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),gX,_X=__esmMin(()=>{hX(),gX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(uX.command,uX.description,uX.builder,uX.handler).command(dX.command,dX.description,dX.builder,dX.handler).command(fX.command,fX.description,fX.builder,fX.handler).command(pX.command,pX.description,pX.builder,pX.handler).command(mX.command,mX.description,mX.builder,mX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!yX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${vX} is not set. Create one with \`${wW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(wW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${wW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${wW} failed with ${describeExit(S)}.`)}var vX,yX,bX=__esmMin(()=>{af(),NW(),hv(),vX=`SNAPCRAFT_STORE_CREDENTIALS`,yX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),xX,SX,CX,wX=__esmMin(()=>{Xn(),bX(),xX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},SX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},CX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),TX,EX=__esmMin(()=>{wX(),TX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(xX.command,xX.description,xX.builder,xX.handler).command(SX.command,SX.description,SX.builder,SX.handler).command(CX.command,CX.description,CX.builder,CX.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())DX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var DX,OX,formatFor,kX,AX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),DX=new Set([`node_modules`,`dist`,`lib`,`.git`]),OX=new Map,formatFor=t=>{let n=OX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return OX.set(t,S),S},kX={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=>Rn(t)?t:In(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),Un(n),formatFor(Hn(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.`)}}}),jX,MX=__esmMin(()=>{AX(),jX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(kX.command,kX.description,kX.builder,kX.handler).demandCommand(1).strict()}}),NX=__esmMin(()=>{yR(),xR(),wR(),OR(),GR(),JR(),rB(),aB(),sB(),_B(),AB(),YB(),QB(),nV(),aV(),nH(),RG(),GG(),EB(),ZG(),eK(),oK(),hB(),dK(),qK(),QK(),oq(),vq(),bq(),Cq(),Tq(),jq(),Lq(),Gq(),Jq(),Xq(),Qq(),sJ(),lJ(),dJ(),vJ(),CJ(),TJ(),BJ(),WJ(),qJ(),XJ(),QJ(),eY(),nY(),_X(),EX(),MX()}),PX=__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=ch(t);await n.scriptName(wh).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(JB.command,JB.description,JB.builder,JB.handler).command(YG.command,YG.description,YG.builder,YG.handler).command(QG.command,QG.description,QG.builder,QG.handler).command($G.command,$G.description,$G.builder,$G.handler).command(vR.command,vR.description,vR.builder,vR.handler).command(bR.command,bR.description,bR.builder,bR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(DR.command,DR.description,DR.builder,DR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(qR.command,qR.description,qR.builder,qR.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(iB.command,iB.description,iB.builder,iB.handler).command(oB.command,oB.description,oB.builder,oB.handler).command(gB.command,gB.description,gB.builder,gB.handler).command(kB.command,kB.description,kB.builder,kB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(tV.command,tV.description,tV.builder,tV.handler).command(iV.command,iV.description,iV.builder,iV.handler).command(tH.command,tH.description,tH.builder,tH.handler).command(IG.command,IG.description,IG.builder,IG.handler).command(WG.command,WG.description,WG.builder,WG.handler).command(aK.command,aK.description,aK.builder,aK.handler).command(mB.command,mB.description,mB.builder,mB.handler).command(cK.command,cK.description,cK.builder,cK.handler).command(KK.command,KK.description,KK.builder,KK.handler).command(yq.command,yq.description,yq.builder,yq.handler).command(ZK.command,ZK.description,ZK.builder,ZK.handler).command(aq.command,aq.description,aq.builder,aq.handler).command(_q.command,_q.description,_q.builder,_q.handler).command(Sq.command,Sq.description,Sq.builder,Sq.handler).command(wq.command,wq.description,wq.builder,wq.handler).command(Aq.command,Aq.description,Aq.builder,Aq.handler).command(Iq.command,Iq.description,Iq.builder,Iq.handler).command(Uq.command,Uq.description,Uq.builder,Uq.handler).command(qq.command,qq.description,qq.builder,qq.handler).command(Zq.command,Zq.description,Zq.builder,Zq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command(mJ.command,mJ.description,mJ.builder,mJ.handler).command(oJ.command,oJ.description,oJ.builder,oJ.handler).command(cJ.command,cJ.description,cJ.builder,cJ.handler).command(uJ.command,uJ.description,uJ.builder,uJ.handler).command(SJ.command,SJ.description,SJ.builder,SJ.handler).command(wJ.command,wJ.description,wJ.builder,wJ.handler).command(RJ.command,RJ.description,RJ.builder,RJ.handler).command(UJ.command,UJ.description,UJ.builder,UJ.handler).command(KJ.command,KJ.description,KJ.builder,KJ.handler).command(YJ.command,YJ.description,YJ.builder,YJ.handler).command(ZJ.command,ZJ.description,ZJ.builder,ZJ.handler).command($J.command,$J.description,$J.builder,$J.handler).command(tY.command,tY.description,tY.builder,tY.handler).command(gX.command,gX.description,gX.builder,gX.handler).command(TX.command,TX.description,TX.builder,TX.handler).command(jX.command,jX.description,jX.builder,jX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var FX=__esmMin(()=>{lh(),uh(),Ch(),NX(),Th(),P_(),$z()});FX(),P_(),tB();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(),P_();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 IX=globalThis.process,LX=Number(IX?.exitCode);Number.isInteger(LX)&&LX!==0&&IX.exit(LX);
1954
+ Set them in the environment, never in package.json (ADR 0077 § Amendment 1).`),this.store=t,this.missing=n,this.name=`StoreCredentialsMissingError`}},StoreUnsupportedError=class extends Error{store;constructor(t,n){super(`gjsify webext submit: ${OY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${OY[t].label}: version ${n} is already there — nothing to submit.`),this.store=t,this.version=n,this.name=`StoreVersionAlreadyThereError`}},StoreInReviewError=class extends Error{store;constructor(t,n){super(`${OY[t].label}: a submission is in review — ${n}`),this.store=t,this.name=`StoreInReviewError`}},StoreApiError=class extends Error{store;httpStatus;constructor(t,n,S){super(`${OY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},jY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(FY,t)}function retryBackoffFor(t,n){return stepFrom(n?LY:IY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||zY.includes(n)?!0:n>=500&&n<600}function isThrottled(t){return t instanceof StoreApiError&&t.httpStatus===429}function retryDecision(t,n){return isRepeatableFailure(t)?n===`publish`&&t instanceof StoreApiError&&t.httpStatus===void 0?`verify-first`:`retry`:`fatal`}async function driveSubmission(t,n={}){let{backend:S}=t,C=t.upload.version,N=n.now??(()=>Date.now()),F=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),I=n.timeoutMs??6e5,H=n.secrets??[],W=N(),q=[],Y=0,X=0,Z=0,clean=t=>redactSecrets(t,H),note=t=>n.log?.(clean(`gjsify webext submit: ${t}`)),remaining=()=>I-(N()-W),endPhase=(t,n)=>{q.push({phase:t,requests:Z,elapsedMs:N()-W,detail:clean(n)}),Z=0},finish=(t,n)=>({store:S.store,version:C,verdict:t,exitCode:NY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:PY.includes(t)}),fromError=(t,n,S)=>{let C=n instanceof Error?n.message:String(n);return endPhase(t,C),n instanceof StoreVersionAlreadyThereError?finish(`already-there`,C):n instanceof StoreInReviewError?finish(`in-review`,C):S?finish(`failed`,`${C} — repeated 3x or until the ${I} ms deadline; the failure class is repeatable, so calling again later may work.`):finish(`rejected`,C)},call=async(t,n)=>{for(let S=0;;S++){Y++,Z++;try{return{kind:`value`,value:await n()}}catch(n){if(isIdempotentSkip(n))return{kind:`error`,error:n,exhausted:!1};let C=retryDecision(n,t);if(C===`fatal`)return{kind:`error`,error:n,exhausted:!1};if(C===`verify-first`)return{kind:`lost`,error:n};let N=remaining();if(S>=3||N<=0)return{kind:`error`,error:n,exhausted:!0};let I=Math.min(retryBackoffFor(S,isThrottled(n)),N);note(`${t} failed with a repeatable error, retry ${S+1} of 3 in ${I} ms — `+(n instanceof Error?n.message:String(n))),X++,await F(I)}}},aboutOurVersion=t=>t.version===void 0||t.version===C,waitFor=async(t,n,I,H)=>{let q=S.operation;if(q===void 0&&I!==void 0&&t===`publish`)return endPhase(n,H),{kind:`end`,result:finish(`unverifiable`,`${H} The publish was accepted and the ${S.store} backend declares no operation() to read ${I} with, so whether a submission exists cannot be established from here. It may well be in review — check the dashboard; the fix is operation() on that backend.`)};for(let H=0;;H++){if(q!==void 0&&I!==void 0){let N=await call(`read`,()=>q.call(S,t,I,C));if(N.kind===`error`)return{kind:`end`,result:fromError(n,N.error,N.exhausted)};if(N.kind===`value`&&N.value.state===`succeeded`)return{kind:`done`,detail:N.value.detail};N.kind===`value`&&note(`${t} operation ${I}: ${N.value.detail}`)}else{let C=await call(`read`,()=>S.status());if(C.kind===`error`)return{kind:`end`,result:fromError(n,C.error,C.exhausted)};if(C.kind===`value`){let S=C.value;if(S.state===`rejected`)return endPhase(n,S.detail),{kind:`end`,result:finish(`rejected`,S.detail)};if(t===`upload`&&S.ingesting!==!0||t===`publish`&&aboutOurVersion(S)&&(S.state===`published`||S.state===`in-review`))return{kind:`done`,detail:S.detail};note(`status while waiting for the ${t}: ${S.detail}`)}}let Y=remaining();if(Y<=0){let S=`the ${t} was accepted and had not resolved after ${N()-W} ms`+(I===void 0?``:` (operation ${I})`)+'. Nothing is lost: call `gjsify webext submit` again — it reads the store\'s state first and will report "already there" or "in review" if this one landed meanwhile. Raise --timeout to wait longer.';return endPhase(n,S),{kind:`end`,result:finish(`unresolved`,S)}}await F(Math.min(pollBackoffFor(H),Y))}};note(`${S.store}: uploading ${C} from ${t.upload.zipPath}`);let te=await call(`upload`,()=>S.upload(t.upload));if(te.kind===`error`)return fromError(`upload`,te.error,te.exhausted);if(te.kind===`lost`)return fromError(`upload`,te.error,!1);if(endPhase(`upload`,te.value.detail),!te.value.ingested){let t=await waitFor(`upload`,`await-upload`,te.value.operationId,te.value.detail);if(t.kind===`end`)return t.result;endPhase(`await-upload`,t.detail)}if(t.publish===void 0)return finish(`uploaded`,`${C} is in the ${S.store} draft and was NOT submitted — pass --submit to ask for review.`);let ne=t.publish,re=0;for(;;){note(`${S.store}: asking for review of ${C}`);let t=await call(`publish`,()=>S.publish(ne));if(t.kind===`error`)return fromError(`publish`,t.error,t.exhausted);if(t.kind===`lost`){let n=t.error instanceof Error?t.error.message:String(t.error);note(`the publish request got no answer (${n}) — asking the store whether it arrived`);let C=await call(`read`,()=>S.status());if(C.kind!==`value`)return fromError(`publish`,C.error,C.kind===`error`&&C.exhausted);let N=C.value;if(N.state===`rejected`)return endPhase(`publish`,N.detail),finish(`rejected`,N.detail);if(aboutOurVersion(N)&&(N.state===`in-review`||N.state===`published`))return endPhase(`publish`,N.detail),finish(N.state===`published`?`published`:`submitted`,`the publish request got no answer, and the store reports it arrived: ${N.detail}`);if(N.state===`draft`&&aboutOurVersion(N)&&re<RY&&remaining()>0){re++,X++,note(`the store still holds a draft (${N.detail}) — sending the publish request once more`);continue}let F=`the publish request got no answer (${n}) and the store's own state does not say whether it arrived: ${N.detail}. The request was NOT repeated — a second one would risk a second submission. Call \`gjsify webext submit\` again once the store settles; it reads the state first.`;return endPhase(`publish`,F),finish(`unresolved`,F)}let n=t.value;if(endPhase(`publish`,n.detail),n.state===`rejected`)return finish(`rejected`,n.detail);if(n.state===`published`)return finish(`published`,n.detail);if(n.state===`in-review`)return finish(`submitted`,n.detail);let N=await waitFor(`publish`,`await-publish`,n.operationId,n.detail);return N.kind===`end`?N.result:(endPhase(`await-publish`,N.detail),finish(`submitted`,N.detail))}}var NY,PY,FY,IY,LY,RY,stepFrom,zY,BY=__esmMin(()=>{MY(),NY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},PY=[`in-review`,`failed`,`unresolved`],FY=[2e3,4e3,8e3,15e3,3e4],IY=[1e3,2e3,4e3],LY=[5e3,15e3,3e4],RY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,zY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.id}.zip`)}function preflightStoreJson(t,n,S){let C;try{C=JSON.parse(t)}catch{return{problems:[`${S} is not valid JSON — regenerate it with \`gjsify webext listing\`.`],manual:[]}}let N=C;if(N.version!==1||!Array.isArray(N.fields))return{problems:[`${S} is not a store.json (version 1) — regenerate it with \`gjsify webext listing\`.`],manual:[]};if(N.store!==n)return{problems:[`${S} is for store "${String(N.store)}", expected "${n}".`],manual:[]};let F=[],I=[];for(let t of N.fields){let n=t.label??t.key??`(unnamed field)`;t.status===`manual`?I.push(n):t.required===!0&&t.status===`missing`&&F.push(`required field "${n}" is missing in ${S}.`)}return{problems:F,manual:I}}function findReviewerNotes(t,n){let S=zn(t,n);if(!existsSync(S))return;let C=readdirSync(S).filter(t=>statSync(zn(S,t)).isDirectory()).sort();for(let t of[`en`,...C.filter(t=>t!==`en`)]){if(!C.includes(t))continue;let n=readText(zn(S,t),`reviewer-notes.txt`);if(n!==void 0&&n!==``)return{text:n,path:zn(S,t,`reviewer-notes.txt`)}}}function secretsOf(t,n){return DY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function describeResult(t,n){let S=[`${n} ${t.version}: ${t.verdict} — ${t.detail}`];for(let n of t.phases)S.push(` ${n.phase}: ${n.detail} (${n.requests} request(s), ${n.elapsedMs} ms)`);return t.retryable&&S.push(` Calling again later, unchanged, can make progress.`),S}async function runSubmit(t){let{env:n,project:S}=t,C=asStoreId(t.store),N=C===null?[]:secretsOf(C,n),clean=t=>redactSecrets(t,N),out=n=>t.out(clean(n)),err=n=>t.err(clean(n));try{if(C===null)throw Error(`gjsify webext submit: unknown store "${t.store}".`);let F=OY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);if(t.submit&&!isTagRef(n.GITHUB_REF))throw Error(`gjsify webext submit: --submit asks the store for review and runs only on a tag ($GITHUB_REF must start with refs/tags/). Without --submit the zip is uploaded (AMO: validated, no version created).`);let I;if(t.timeoutSeconds!==void 0){if(!Number.isFinite(t.timeoutSeconds)||t.timeoutSeconds<0)throw Error(`gjsify webext submit: --timeout is a number of seconds, 0 or more.`);I=t.timeoutSeconds*1e3}if(t.listingOnly){if(C!==`amo`)throw Error(`gjsify webext submit: --listing-only applies to AMO only; Chrome and Edge have no listing API.`);if(t.submit||t.zip!==void 0||t.sourceZip!==void 0)throw Error(`gjsify webext submit: --listing-only sends texts only; drop --submit, --zip and --source.`);let N=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0;return await runListingUpload({listingRoot:In(S.root,t.listingDir??`dist/listing`),dryRun:t.dryRun,notesVersion:t.notesVersion,backend:()=>(t.createBackend??createStoreBackend)(C,n,{fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:N}),out})}if(t.notesVersion!==void 0)throw Error(`gjsify webext submit: --notes-version belongs to --listing-only.`);let H=VY[C],W=zn(In(S.root,t.listingDir??`dist/listing`),H,`store.json`);if(!existsSync(W))throw Error(`gjsify webext submit: ${W} does not exist. Run \`gjsify webext listing --store ${H}\` first; it is the preflight for the listing the dashboard will ask about.`);let q=preflightStoreJson(readFileSync(W,`utf8`),H,W);if(q.problems.length>0)throw Error(`gjsify webext submit: preflight failed, nothing was sent:\n ${q.problems.join(`
1955
+ `)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=C===`edge`||C===`amo`?findReviewerNotes(In(S.root,t.listingDir??`dist/listing`),H):void 0;Z===void 0&&C===`edge`&&t.submit&&err("warning: no reviewer-notes.txt under the listing dir; Edge reviewers expect certification notes. Run `gjsify webext listing --store edge` first. Continuing without notes.");let te=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,ne={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:te},re=(t.createBackend??createStoreBackend)(C,n,ne);if(t.dryRun)return re.verifyCredentials===void 0?(out(`${F.label}: dry run — credentials are set; this backend has no read-only check, so they are unverified. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0):(await re.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0);let ie=await driveSubmission({backend:re,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X,notes:Z?.text}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:te,secrets:N}),ae=ie.exitCode===0?out:err;for(let t of describeResult(ie,F.label))ae(t);return NY[ie.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var VY,HY=__esmMin(()=>{af(),Xn(),sY(),MY(),oY(),BY(),VY={chrome:`cws`,edge:`edge`,amo:`amo`}});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/${Un(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/${Un(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(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var UY=__esmMin(()=>{af(),Xn(),wH()});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(()=>(mR(),dR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++WY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++WY}`;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(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(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(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var WY,GY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),WY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(QY.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(KY,n=>{let S=JY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!$Y.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:XY.test(n)?`esm`:`iife`,output:F}),n.replace(JY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(qY,t=>{if(!ZY.test(t))return t;let n=YY.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace(YY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var KY,qY,JY,YY,XY,ZY,QY,$Y,eX=__esmMin(()=>{Xn(),KY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,qY=/<link\b[^>]*>/gi,JY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,YY=/\bhref\s*=\s*(["'])([^"']+)\1/i,XY=/\btype\s*=\s*["']module["']/i,ZY=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,QY=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,$Y=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=tX?n:tX}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(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=zn(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:zn(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:zn(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,zn(H,t.output))}writeFileSync(zn(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=zn(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,zn(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(zn(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(`
1956
+ - `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var tX,nX=__esmMin(()=>{_e(),af(),Xn(),dG(),UY(),GY(),eX(),tX=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!rX.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${rX.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?aX.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 rX,iX,aX,oX=__esmMin(()=>{rX=[`chrome`,`edge`,`firefox`,`opera`,`safari`],iX=[`chrome-mv3`,`firefox-mv3`],aX=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=>Rn(t)?t:In(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??[...iX];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=cX.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${cX.join(`, `)} exists.`):W=zn(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(!lX.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??sX;(!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(!lX.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=zn(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 ${zn(n,`package.json`)}:\n - ${C.join(`
1957
+ - `)}`);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 resolveSubmitProject(t,n){let S=t.gjsify?.webext;if(S!==void 0&&!isRecord(S))throw Error("gjsify webext: `gjsify.webext` must be an object.");let C=S??{},N=[],F=C.targets??[...iX],I=[];if(!Array.isArray(F)||F.length===0)N.push("`targets` must be a non-empty array of target names.");else for(let t of F)try{I.push(parseWebextTarget(String(t)))}catch(t){N.push(t.message.replace(/^gjsify webext: /,``))}if(N.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${N.join(`
1958
+ - `)}`);return{root:n,name:C.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,outDir:Rn(C.outDir??`.output`)?C.outDir:In(n,C.outDir??`.output`)}}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 sX,cX,lX,uX=__esmMin(()=>{af(),Xn(),oX(),sX=[16,32,48,128],cX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],lX=/^[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 zn(S.XDG_CACHE_HOME||zn(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=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var dX,fX=__esmMin(()=>{af(),o_(),Xn(),dL(),oX(),dX="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=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function loadSubmitProject(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveSubmitProject(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(()=>(VX(),BX)),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?In(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=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var pX,mX,hX,gX,_X,vX,yX,bX,xX=__esmMin(()=>{_e(),af(),Xn(),qJ(),HY(),nX(),uX(),fX(),pX={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},mX={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},hX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},gX={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,pX).option(`out-dir`,mX).option(`define`,hX).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)},_X={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,pX).option(`out-dir`,mX).option(`define`,hX),handler:t=>runBuild(t,!0)},vX={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`,{...pX,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,hX).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?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(dX);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?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(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(()=>(WJ(),UJ));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(()=>(WJ(),UJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),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})}},yX={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}},bX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,type:`string`,choices:[`chrome`,`edge`,`amo`],demandOption:!0}).option(`zip`,{description:"The zip to upload (default: what `webext zip` writes for the store's target).",type:`string`}).option(`dry-run`,{description:`Check the credentials with one read call; upload nothing.`,type:`boolean`,default:!1}).option(`submit`,{description:`Ask for review after the upload. Refused unless $GITHUB_REF is a tag.`,type:`boolean`,default:!1}).option(`timeout`,{description:`Seconds to wait for the store to resolve an upload or submission (default: 600).`,type:`number`}).option(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-only`,{description:`AMO only: send description and privacy policy from --listing-dir (not the zip), then read each back. With --dry-run: lengths only, no network.`,type:`boolean`,default:!1}).option(`notes-version`,{description:`With --listing-only: also send the reviewer notes (approval_notes) to this version id or number.`,type:`string`}).option(`listing-dir`,{description:"Where `webext listing` wrote store.json (default: dist/listing).",type:`string`}).epilog(`Credentials come from the environment only (see ADR 0077 § Amendment 1). Exit codes: 0 done or nothing to do, 1 rejected or failed, 3 accepted but unresolved (run again), 4 unverifiable. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. A submission stuck in review is cancelled in the Chrome dashboard (:cancelSubmission); this command never does.`),handler:async t=>{let n=process.cwd(),S=await runSubmit({store:t.store,zip:t.zip?In(n,t.zip):void 0,dryRun:t.dryRun,submit:t.submit,timeoutSeconds:t.timeout,listingDir:t.listingDir,sourceZip:t.source?In(n,t.source):void 0,listingOnly:t.listingOnly,notesVersion:t.notesVersion,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),SX,CX=__esmMin(()=>{xX(),SX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(gX.command,gX.description,gX.builder,gX.handler).command(_X.command,_X.description,_X.builder,_X.handler).command(vX.command,vX.description,vX.builder,vX.handler).command(yX.command,yX.description,yX.builder,yX.handler).command(bX.command,bX.description,bX.builder,bX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!TX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${wX} is not set. Create one with \`${TW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(TW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${TW} failed with ${describeExit(S)}.`)}var wX,TX,EX=__esmMin(()=>{af(),FW(),hv(),wX=`SNAPCRAFT_STORE_CREDENTIALS`,TX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),DX,OX,kX,AX=__esmMin(()=>{Xn(),EX(),DX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},OX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},kX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),jX,MX=__esmMin(()=>{AX(),jX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(DX.command,DX.description,DX.builder,DX.handler).command(OX.command,OX.description,OX.builder,OX.handler).command(kX.command,kX.description,kX.builder,kX.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())NX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var NX,PX,formatFor,FX,IX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),NX=new Set([`node_modules`,`dist`,`lib`,`.git`]),PX=new Map,formatFor=t=>{let n=PX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return PX.set(t,S),S},FX={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=>Rn(t)?t:In(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),Un(n),formatFor(Hn(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.`)}}}),LX,RX=__esmMin(()=>{IX(),LX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(FX.command,FX.description,FX.builder,FX.handler).demandCommand(1).strict()}}),zX=__esmMin(()=>{yR(),xR(),wR(),OR(),GR(),JR(),rB(),aB(),sB(),_B(),AB(),YB(),QB(),nV(),aV(),nH(),BG(),qG(),EB(),$G(),nK(),cK(),hB(),pK(),YK(),eq(),cq(),bq(),Sq(),Tq(),Dq(),Nq(),zq(),qq(),Xq(),Qq(),eJ(),lJ(),dJ(),pJ(),bJ(),TJ(),DJ(),HJ(),KJ(),YJ(),QJ(),eY(),nY(),iY(),CX(),MX(),RX()}),BX=__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=ch(t);await n.scriptName(wh).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(JB.command,JB.description,JB.builder,JB.handler).command(ZG.command,ZG.description,ZG.builder,ZG.handler).command(eK.command,eK.description,eK.builder,eK.handler).command(tK.command,tK.description,tK.builder,tK.handler).command(vR.command,vR.description,vR.builder,vR.handler).command(bR.command,bR.description,bR.builder,bR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(DR.command,DR.description,DR.builder,DR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(qR.command,qR.description,qR.builder,qR.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(iB.command,iB.description,iB.builder,iB.handler).command(oB.command,oB.description,oB.builder,oB.handler).command(gB.command,gB.description,gB.builder,gB.handler).command(kB.command,kB.description,kB.builder,kB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(tV.command,tV.description,tV.builder,tV.handler).command(iV.command,iV.description,iV.builder,iV.handler).command(tH.command,tH.description,tH.builder,tH.handler).command(RG.command,RG.description,RG.builder,RG.handler).command(KG.command,KG.description,KG.builder,KG.handler).command(sK.command,sK.description,sK.builder,sK.handler).command(mB.command,mB.description,mB.builder,mB.handler).command(uK.command,uK.description,uK.builder,uK.handler).command(JK.command,JK.description,JK.builder,JK.handler).command(xq.command,xq.description,xq.builder,xq.handler).command($K.command,$K.description,$K.builder,$K.handler).command(sq.command,sq.description,sq.builder,sq.handler).command(yq.command,yq.description,yq.builder,yq.handler).command(wq.command,wq.description,wq.builder,wq.handler).command(Eq.command,Eq.description,Eq.builder,Eq.handler).command(Mq.command,Mq.description,Mq.builder,Mq.handler).command(Rq.command,Rq.description,Rq.builder,Rq.handler).command(Gq.command,Gq.description,Gq.builder,Gq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command($q.command,$q.description,$q.builder,$q.handler).command(Zq.command,Zq.description,Zq.builder,Zq.handler).command(gJ.command,gJ.description,gJ.builder,gJ.handler).command(cJ.command,cJ.description,cJ.builder,cJ.handler).command(uJ.command,uJ.description,uJ.builder,uJ.handler).command(fJ.command,fJ.description,fJ.builder,fJ.handler).command(wJ.command,wJ.description,wJ.builder,wJ.handler).command(EJ.command,EJ.description,EJ.builder,EJ.handler).command(BJ.command,BJ.description,BJ.builder,BJ.handler).command(GJ.command,GJ.description,GJ.builder,GJ.handler).command(JJ.command,JJ.description,JJ.builder,JJ.handler).command(ZJ.command,ZJ.description,ZJ.builder,ZJ.handler).command($J.command,$J.description,$J.builder,$J.handler).command(tY.command,tY.description,tY.builder,tY.handler).command(rY.command,rY.description,rY.builder,rY.handler).command(SX.command,SX.description,SX.builder,SX.handler).command(jX.command,jX.description,jX.builder,jX.handler).command(LX.command,LX.description,LX.builder,LX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var VX=__esmMin(()=>{lh(),uh(),Ch(),zX(),Th(),P_(),$z()});VX(),P_(),tB();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(),P_();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 HX=globalThis.process,UX=Number(HX?.exitCode);Number.isInteger(UX)&&UX!==0&&HX.exit(UX);