@gjsify/cli 0.59.1 → 0.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.gjs.mjs +123 -121
- package/lib/commands/publish.d.ts +25 -0
- package/lib/commands/publish.js +108 -2
- package/lib/utils/discover-showcases.js +5 -0
- package/lib/utils/publish-hold.d.ts +89 -0
- package/lib/utils/publish-hold.js +213 -0
- package/lib/utils/publish-status.d.ts +83 -0
- package/lib/utils/publish-status.js +193 -0
- package/package.json +20 -20
- package/showcases.json +0 -42
package/dist/cli.gjs.mjs
CHANGED
|
@@ -145,7 +145,7 @@ fi
|
|
|
145
145
|
`)}`:``;n.fail(N(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(C).length,Object.keys(C).join(`, `)+S))}},F.unknownArguments=function unknownArguments(S,C,I,H,W=!0){let q=t.getInternalMethods().getCommandInstance().getCommands(),Y=[],X=t.getInternalMethods().getContext();if(Object.keys(S).forEach(n=>{!pp.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=>{pp.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 pp,mp=__esmMin(()=>{$f(),Yf(),fp(),ip(),pp=[`$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,gp,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,YargsInstance,Fm=__esmMin(()=>{_e(),rp(),Yf(),_l(),op(),$f(),dp(),mp(),ip(),bl(),ep(),Xf(),tp(),ap(),__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)},Zp=Symbol(`copyDoubleDash`),Qp=Symbol(`copyDoubleDash`),$p=Symbol(`deleteFromParserHintObject`),em=Symbol(`emitWarning`),tm=Symbol(`freeze`),nm=Symbol(`getDollarZero`),im=Symbol(`getParserConfiguration`),am=Symbol(`getUsageConfiguration`),om=Symbol(`guessLocale`),sm=Symbol(`guessVersion`),cm=Symbol(`parsePositionalNumbers`),lm=Symbol(`pkgUp`),um=Symbol(`populateParserHintArray`),dm=Symbol(`populateParserHintSingleValueDictionary`),fm=Symbol(`populateParserHintArrayDictionary`),pm=Symbol(`populateParserHintDictionary`),mm=Symbol(`sanitizeKey`),hm=Symbol(`setKey`),gm=Symbol(`unfreeze`),_m=Symbol(`validateAsync`),vm=Symbol(`getCommandInstance`),ym=Symbol(`getContext`),bm=Symbol(`getHasOutput`),xm=Symbol(`getLoggerInstance`),Sm=Symbol(`getParseContext`),Cm=Symbol(`getUsageInstance`),wm=Symbol(`getValidationInstance`),Tm=Symbol(`hasParseCallback`),Em=Symbol(`isGlobalContext`),Dm=Symbol(`postProcess`),Om=Symbol(`rebase`),km=Symbol(`reset`),Am=Symbol(`runYargsParserAndExecuteCommands`),jm=Symbol(`runValidation`),Mm=Symbol(`setHasOutput`),Nm=Symbol(`kTrackManuallySetKeys`),Pm=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,hp.set(this,void 0),gp.set(this,void 0),vp.set(this,{commands:[],fullCommands:[]}),yp.set(this,null),bp.set(this,null),xp.set(this,`show-hidden`),Sp.set(this,null),Cp.set(this,!0),wp.set(this,{}),Tp.set(this,!0),Ep.set(this,[]),Dp.set(this,void 0),Op.set(this,{}),kp.set(this,!1),Ap.set(this,null),jp.set(this,!0),Mp.set(this,void 0),Np.set(this,``),Pp.set(this,void 0),Fp.set(this,void 0),Ip.set(this,{}),Lp.set(this,null),Rp.set(this,null),zp.set(this,{}),Bp.set(this,{}),Vp.set(this,void 0),Hp.set(this,!1),Up.set(this,void 0),Wp.set(this,!1),Gp.set(this,!1),Kp.set(this,!1),qp.set(this,void 0),Jp.set(this,{}),Yp.set(this,null),Xp.set(this,void 0),__classPrivateFieldSet(this,Up,C,`f`),__classPrivateFieldSet(this,Vp,t,`f`),__classPrivateFieldSet(this,gp,n,`f`),__classPrivateFieldSet(this,Fp,S,`f`),__classPrivateFieldSet(this,Dp,new GlobalMiddleware(this),`f`),this.$0=this[nm](),this[km](),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`),`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`),`f`),__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`),`f`),__classPrivateFieldGet(this,Pp,`f`).showHiddenOpt=__classPrivateFieldGet(this,xp,`f`),__classPrivateFieldSet(this,Mp,this[Qp](),`f`),__classPrivateFieldGet(this,Up,`f`).y18n.setLocale(Pm)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,Ap,`f`)&&(this[$p](__classPrivateFieldGet(this,Ap,`f`)),__classPrivateFieldSet(this,Ap,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,Ap,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,Ap,`f`)),this.describe(__classPrivateFieldGet(this,Ap,`f`),n||__classPrivateFieldGet(this,qp,`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,xp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,Pp,`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[fm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`array`,t),this[Nm](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`boolean`,t),this[Nm](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,qp,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,qp,`f`).fail(__classPrivateFieldGet(this,Up,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,qp,`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[fm](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 gl(`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 gl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,Pp,`f`).key[S]=!0,__classPrivateFieldGet(this,Dp,`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 gl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Xp,`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,gp,`f`),this[im]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).configObjects=(__classPrivateFieldGet(this,Pp,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,Pp,`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,bp,t||__classPrivateFieldGet(this,bp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,bp,`f`),n),S&&__classPrivateFieldGet(this,yp,`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,Fp,`f`)||__classPrivateFieldGet(this,Up,`f`).require;return __classPrivateFieldGet(this,hp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,Up,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`count`,t),this[Nm](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,Pp,`f`).defaultDescription[t]=__classPrivateFieldGet(this,qp,`f`).functionDescription(n)),n=n.call()),this[dm](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,Pp,`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,Up,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Up,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,Up,`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[dm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,Pp,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[hm](t,!0),__classPrivateFieldGet(this,qp,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Cp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,Pp,`f`).envPrefix:__classPrivateFieldGet(this,Pp,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,qp,`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,qp,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldSet(this,Sp,n,`f`),__classPrivateFieldGet(this,Tp,`f`)&&__classPrivateFieldGet(this,Up,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Tp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new gl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,qp,`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,yp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,yp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,Pp,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Cp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Tp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,Op,`f`),__classPrivateFieldGet(this,Bp,`f`))}getHelp(){if(__classPrivateFieldSet(this,kp,!0,`f`),!__classPrivateFieldGet(this,qp,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[Am](__classPrivateFieldGet(this,Vp,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,qp,`f`).help())}let t=__classPrivateFieldGet(this,hp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,qp,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,qp,`f`).help())}getOptions(){return __classPrivateFieldGet(this,Pp,`f`)}getStrict(){return __classPrivateFieldGet(this,Wp,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,Gp,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,Kp,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,Pp,`f`).local.includes(t)||__classPrivateFieldGet(this,Pp,`f`).local.push(t)}):__classPrivateFieldGet(this,Pp,`f`).local=__classPrivateFieldGet(this,Pp,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,Bp,`f`)[n]||__classPrivateFieldGet(this,Op,`f`)[n];__classPrivateFieldGet(this,Bp,`f`)[n]&&delete __classPrivateFieldGet(this,Bp,`f`)[n];let C={};return __classPrivateFieldGet(this,Op,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,Pp,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Xp,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[om](),__classPrivateFieldGet(this,Up,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Cp,!1,`f`),__classPrivateFieldGet(this,Up,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,Dp,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[dm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`number`,t),this[Nm](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[Nm](t),__classPrivateFieldGet(this,Yp,`f`)&&(t===`version`||n?.alias===`version`)&&this[em]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
146
146
|
`),void 0,`versionWarning`),__classPrivateFieldGet(this,Pp,`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,Pp,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,qp,`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[tm](),t===void 0&&(t=__classPrivateFieldGet(this,Vp,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,Rp,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,Lp,n,`f`),n=!1),n||__classPrivateFieldSet(this,Vp,t,`f`),__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldSet(this,Tp,!1,`f`);let C=this[Am](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,yp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`).call(this,__classPrivateFieldGet(this,Sp,`f`),t,__classPrivateFieldGet(this,Np,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,Np,`f`)),t}).finally(()=>{this[gm](),this.parsed=N}):(__classPrivateFieldGet(this,Lp,`f`)&&__classPrivateFieldGet(this,Lp,`f`).call(this,__classPrivateFieldGet(this,Sp,`f`),C,__classPrivateFieldGet(this,Np,`f`)),this[gm](),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 gl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Ip,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[lm](n||__classPrivateFieldGet(this,gp,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,gp,`f`),this[im]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Up,`f`)),__classPrivateFieldGet(this,Pp,`f`).configObjects=(__classPrivateFieldGet(this,Pp,`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,vp,`f`).fullCommands[__classPrivateFieldGet(this,vp,`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,qp,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Hp,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,Pp,`f`).narg[t]||this[dm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,Mp,`f`).log(__classPrivateFieldGet(this,yp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,bp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,kp,!0,`f`),!__classPrivateFieldGet(this,qp,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[Am](__classPrivateFieldGet(this,Vp,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,qp,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,hp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,qp,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,qp,`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,qp,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,qp,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Wp,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Gp,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Kp,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[um](`string`,t),this[Nm](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,Up,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Cp,!1,`f`),__classPrivateFieldGet(this,Up,`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,Up,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new gl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,qp,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Jp,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Yp,`f`)&&(this[$p](__classPrivateFieldGet(this,Yp,`f`)),__classPrivateFieldGet(this,qp,`f`).version(void 0),__classPrivateFieldSet(this,Yp,null,`f`)),arguments.length===0)S=this[sm](),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,Yp,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,qp,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,qp,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Yp,`f`)),this.describe(__classPrivateFieldGet(this,Yp,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,qp,`f`).wrap(t),this}[(hp=new WeakMap,gp=new WeakMap,vp=new WeakMap,yp=new WeakMap,bp=new WeakMap,xp=new WeakMap,Sp=new WeakMap,Cp=new WeakMap,wp=new WeakMap,Tp=new WeakMap,Ep=new WeakMap,Dp=new WeakMap,Op=new WeakMap,kp=new WeakMap,Ap=new WeakMap,jp=new WeakMap,Mp=new WeakMap,Np=new WeakMap,Pp=new WeakMap,Fp=new WeakMap,Ip=new WeakMap,Lp=new WeakMap,Rp=new WeakMap,zp=new WeakMap,Bp=new WeakMap,Vp=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap,Xp=new WeakMap,Zp)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[Qp](){return{log:(...t)=>{this[Tm]()||ge.log(...t),__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldGet(this,Np,`f`).length&&__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+`
|
|
147
147
|
`,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Tm]()||ge.error(...t),__classPrivateFieldSet(this,kp,!0,`f`),__classPrivateFieldGet(this,Np,`f`).length&&__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+`
|
|
148
|
-
`,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)}}}[$p](t){objectKeys(__classPrivateFieldGet(this,Pp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Pp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,qp,`f`).getDescriptions()[t]}[em](t,n,S){__classPrivateFieldGet(this,wp,`f`)[S]||(__classPrivateFieldGet(this,Up,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,wp,`f`)[S]=!0)}[tm](){__classPrivateFieldGet(this,Ep,`f`).push({options:__classPrivateFieldGet(this,Pp,`f`),configObjects:__classPrivateFieldGet(this,Pp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Tp,`f`),groups:__classPrivateFieldGet(this,Op,`f`),strict:__classPrivateFieldGet(this,Wp,`f`),strictCommands:__classPrivateFieldGet(this,Gp,`f`),strictOptions:__classPrivateFieldGet(this,Kp,`f`),completionCommand:__classPrivateFieldGet(this,bp,`f`),output:__classPrivateFieldGet(this,Np,`f`),exitError:__classPrivateFieldGet(this,Sp,`f`),hasOutput:__classPrivateFieldGet(this,kp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Lp,`f`),parseContext:__classPrivateFieldGet(this,Rp,`f`)}),__classPrivateFieldGet(this,qp,`f`).freeze(),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,hp,`f`).freeze(),__classPrivateFieldGet(this,Dp,`f`).freeze()}[nm](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Up,`f`).process.argv()[0])?__classPrivateFieldGet(this,Up,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Up,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[Om](__classPrivateFieldGet(this,gp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Up,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Up,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Up,`f`).path.dirname(__classPrivateFieldGet(this,Up,`f`).process.execPath())}/`,``)),t}[im](){return __classPrivateFieldGet(this,Ip,`f`)}[am](){return __classPrivateFieldGet(this,Jp,`f`)}[om](){if(!__classPrivateFieldGet(this,Cp,`f`))return;let t=__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[sm](){return this[lm]().version||`unknown`}[cm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Up,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[lm](t){let n=t||`*`;if(__classPrivateFieldGet(this,zp,`f`)[n])return __classPrivateFieldGet(this,zp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Up,`f`).mainFilename;__classPrivateFieldGet(this,Up,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Up,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Up,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Up,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Up,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,zp,`f`)[n]=S||{},__classPrivateFieldGet(this,zp,`f`)[n]}[um](t,n){n=[].concat(n),n.forEach(n=>{n=this[mm](n),__classPrivateFieldGet(this,Pp,`f`)[t].push(n)})}[dm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=S})}[fm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=(__classPrivateFieldGet(this,Pp,`f`)[t][n]||[]).concat(S)})}[pm](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[mm](S),C)}[mm](t){return t===`__proto__`?`___proto___`:t}[hm](t,n){return this[dm](this[hm].bind(this),`key`,t,n),this}[gm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Ep,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Up,`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,Pp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Tp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,Op,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Np,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Sp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,kp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,Wp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Gp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Kp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,bp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Lp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Rp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Pp,`f`).configObjects=te,__classPrivateFieldGet(this,qp,`f`).unfreeze(),__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,hp,`f`).unfreeze(),__classPrivateFieldGet(this,Dp,`f`).unfreeze()}[_m](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[vm].bind(this),getContext:this[ym].bind(this),getHasOutput:this[bm].bind(this),getLoggerInstance:this[xm].bind(this),getParseContext:this[Sm].bind(this),getParserConfiguration:this[im].bind(this),getUsageConfiguration:this[am].bind(this),getUsageInstance:this[Cm].bind(this),getValidationInstance:this[wm].bind(this),hasParseCallback:this[Tm].bind(this),isGlobalContext:this[Em].bind(this),postProcess:this[Dm].bind(this),reset:this[km].bind(this),runValidation:this[jm].bind(this),runYargsParserAndExecuteCommands:this[Am].bind(this),setHasOutput:this[Mm].bind(this)}}[vm](){return __classPrivateFieldGet(this,hp,`f`)}[ym](){return __classPrivateFieldGet(this,vp,`f`)}[bm](){return __classPrivateFieldGet(this,kp,`f`)}[xm](){return __classPrivateFieldGet(this,Mp,`f`)}[Sm](){return __classPrivateFieldGet(this,Rp,`f`)||{}}[Cm](){return __classPrivateFieldGet(this,qp,`f`)}[wm](){return __classPrivateFieldGet(this,Xp,`f`)}[Tm](){return!!__classPrivateFieldGet(this,Lp,`f`)}[Em](){return __classPrivateFieldGet(this,jp,`f`)}[Dm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Zp](t)),(this[im]()[`parse-positional-numbers`]||this[im]()[`parse-positional-numbers`]===void 0)&&(t=this[cm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)),t)}[km](t={}){__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Pp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Pp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Bp,`f`),Object.keys(__classPrivateFieldGet(this,Op,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,Op,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,Op,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Pp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Pp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Pp,`f`).envPrefix,__classPrivateFieldSet(this,Pp,n,`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`)?__classPrivateFieldGet(this,qp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):validation(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`)?__classPrivateFieldGet(this,hp,`f`).reset():command(__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Dp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,yp,`f`)||__classPrivateFieldSet(this,yp,completion(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,hp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,Dp,`f`).reset(),__classPrivateFieldSet(this,bp,null,`f`),__classPrivateFieldSet(this,Np,``,`f`),__classPrivateFieldSet(this,Sp,null,`f`),__classPrivateFieldSet(this,kp,!1,`f`),this.parsed=!1,this}[Om](t,n){return __classPrivateFieldGet(this,Up,`f`).path.relative(t,n)}[Am](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,Pp,`f`).__=__classPrivateFieldGet(this,Up,`f`).y18n.__,__classPrivateFieldGet(this,Pp,`f`).configuration=this[im]();let I=!!__classPrivateFieldGet(this,Pp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Pp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Up,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Pp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Rp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Ap,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Yp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,qp,`f`).clearCachedHelpMessage();try{if(this[om](),n)return this[Dm](q,I,!!S,!1);__classPrivateFieldGet(this,Ap,`f`)&&[__classPrivateFieldGet(this,Ap,`f`)].concat(X[__classPrivateFieldGet(this,Ap,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,jp,!1,`f`);let H=__classPrivateFieldGet(this,hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,yp,`f`)?.completionKey?[__classPrivateFieldGet(this,yp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,yp,`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,bp,`f`)){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Dm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,bp,`f`)){t=F;break}!__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Hp,`f`)&&t&&!re&&__classPrivateFieldGet(this,Xp,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,bp,`f`)&&q._.includes(__classPrivateFieldGet(this,bp,`f`))&&!ne&&(__classPrivateFieldGet(this,Tp,`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[Dm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,yp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,yp,`f`).getCompletion(n,(t,n)=>{if(t)throw new gl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t)}),this.exit(0)}),this[Dm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,kp,`f`)||(Z?(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,qp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Pp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Pp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new gl(W.error.message);if(!ne){let t=this[jm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!0)),Y=this[_m](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof gl)__classPrivateFieldGet(this,qp,`f`).fail(t.message,t);else throw t}return this[Dm](Y??q,I,!!S,!0)}[jm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new gl(S.message);__classPrivateFieldGet(this,Xp,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Xp,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Gp,`f`)&&(I=__classPrivateFieldGet(this,Xp,`f`).unknownCommands(F)),__classPrivateFieldGet(this,Wp,`f`)&&!I?__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Kp,`f`)&&__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Xp,`f`).limitedChoices(F),__classPrivateFieldGet(this,Xp,`f`).implications(F),__classPrivateFieldGet(this,Xp,`f`).conflicting(F)}}[Mm](){__classPrivateFieldSet(this,kp,!0,`f`)}[Nm](t){if(typeof t==`string`)__classPrivateFieldGet(this,Pp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Pp,`f`).key[n]=!0}}}),Im,Lm=__esmMin(()=>{Jf(),Fm(),Im=YargsFactory(qf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Rm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.59.1`,"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 zm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Bm=__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):Vm}function parseNpmrc(t){let n={registry:Vm,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 Vm,Hm=__esmMin(()=>{Vm=`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 Um=__esmMin(()=>{Bm(),__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 Wm=__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 Gm=__esmMin(()=>{zm(),Bm(),Hm(),Um()});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 Km=__esmMin(()=>{zm(),Bm(),Um(),Wm()});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 qm=__esmMin(()=>{zm(),Hm()}),Jm=__esmMin(()=>{zm(),Hm(),Wm(),Gm(),Km(),qm()});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 Ym===void 0&&(Ym=`0.59.1`),Ym}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Ym,Xm=__esmMin(()=>{Md(),jn(),Hn(),Jm()}),Zm,Qm=__esmMin(()=>{Zm=`gjsify`}),$m=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Al(),__toCommonJS(El)),N=(Md(),__toCommonJS(Ad)),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)})),eh=__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})),th=__commonJSMin(((t,n)=>{let S=eh();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}}}})),nh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Pl(),__toCommonJS(jl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=$m(),W=th();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)}})),rh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),ih=__commonJSMin(((t,n)=>{var S=(yu(),__toCommonJS(hu)),C=rh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
|
|
148
|
+
`,`f`),__classPrivateFieldSet(this,Np,__classPrivateFieldGet(this,Np,`f`)+t.join(` `),`f`)}}}[$p](t){objectKeys(__classPrivateFieldGet(this,Pp,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,Pp,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,qp,`f`).getDescriptions()[t]}[em](t,n,S){__classPrivateFieldGet(this,wp,`f`)[S]||(__classPrivateFieldGet(this,Up,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,wp,`f`)[S]=!0)}[tm](){__classPrivateFieldGet(this,Ep,`f`).push({options:__classPrivateFieldGet(this,Pp,`f`),configObjects:__classPrivateFieldGet(this,Pp,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Tp,`f`),groups:__classPrivateFieldGet(this,Op,`f`),strict:__classPrivateFieldGet(this,Wp,`f`),strictCommands:__classPrivateFieldGet(this,Gp,`f`),strictOptions:__classPrivateFieldGet(this,Kp,`f`),completionCommand:__classPrivateFieldGet(this,bp,`f`),output:__classPrivateFieldGet(this,Np,`f`),exitError:__classPrivateFieldGet(this,Sp,`f`),hasOutput:__classPrivateFieldGet(this,kp,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Lp,`f`),parseContext:__classPrivateFieldGet(this,Rp,`f`)}),__classPrivateFieldGet(this,qp,`f`).freeze(),__classPrivateFieldGet(this,Xp,`f`).freeze(),__classPrivateFieldGet(this,hp,`f`).freeze(),__classPrivateFieldGet(this,Dp,`f`).freeze()}[nm](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Up,`f`).process.argv()[0])?__classPrivateFieldGet(this,Up,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Up,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[Om](__classPrivateFieldGet(this,gp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Up,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Up,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,Up,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Up,`f`).path.dirname(__classPrivateFieldGet(this,Up,`f`).process.execPath())}/`,``)),t}[im](){return __classPrivateFieldGet(this,Ip,`f`)}[am](){return __classPrivateFieldGet(this,Jp,`f`)}[om](){if(!__classPrivateFieldGet(this,Cp,`f`))return;let t=__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Up,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[sm](){return this[lm]().version||`unknown`}[cm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,Up,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[lm](t){let n=t||`*`;if(__classPrivateFieldGet(this,zp,`f`)[n])return __classPrivateFieldGet(this,zp,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,Up,`f`).mainFilename;__classPrivateFieldGet(this,Up,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,Up,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,Up,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,Up,`f`)),S=JSON.parse(__classPrivateFieldGet(this,Up,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,zp,`f`)[n]=S||{},__classPrivateFieldGet(this,zp,`f`)[n]}[um](t,n){n=[].concat(n),n.forEach(n=>{n=this[mm](n),__classPrivateFieldGet(this,Pp,`f`)[t].push(n)})}[dm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=S})}[fm](t,n,S,C){this[pm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,Pp,`f`)[t][n]=(__classPrivateFieldGet(this,Pp,`f`)[t][n]||[]).concat(S)})}[pm](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[mm](S),C)}[mm](t){return t===`__proto__`?`___proto___`:t}[hm](t,n){return this[dm](this[hm].bind(this),`key`,t,n),this}[gm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Ep,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,Up,`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,Pp,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Tp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,Op,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,Np,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Sp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,kp,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,Wp,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,Gp,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,Kp,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,bp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,Lp,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,Rp,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,Pp,`f`).configObjects=te,__classPrivateFieldGet(this,qp,`f`).unfreeze(),__classPrivateFieldGet(this,Xp,`f`).unfreeze(),__classPrivateFieldGet(this,hp,`f`).unfreeze(),__classPrivateFieldGet(this,Dp,`f`).unfreeze()}[_m](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[vm].bind(this),getContext:this[ym].bind(this),getHasOutput:this[bm].bind(this),getLoggerInstance:this[xm].bind(this),getParseContext:this[Sm].bind(this),getParserConfiguration:this[im].bind(this),getUsageConfiguration:this[am].bind(this),getUsageInstance:this[Cm].bind(this),getValidationInstance:this[wm].bind(this),hasParseCallback:this[Tm].bind(this),isGlobalContext:this[Em].bind(this),postProcess:this[Dm].bind(this),reset:this[km].bind(this),runValidation:this[jm].bind(this),runYargsParserAndExecuteCommands:this[Am].bind(this),setHasOutput:this[Mm].bind(this)}}[vm](){return __classPrivateFieldGet(this,hp,`f`)}[ym](){return __classPrivateFieldGet(this,vp,`f`)}[bm](){return __classPrivateFieldGet(this,kp,`f`)}[xm](){return __classPrivateFieldGet(this,Mp,`f`)}[Sm](){return __classPrivateFieldGet(this,Rp,`f`)||{}}[Cm](){return __classPrivateFieldGet(this,qp,`f`)}[wm](){return __classPrivateFieldGet(this,Xp,`f`)}[Tm](){return!!__classPrivateFieldGet(this,Lp,`f`)}[Em](){return __classPrivateFieldGet(this,jp,`f`)}[Dm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Zp](t)),(this[im]()[`parse-positional-numbers`]||this[im]()[`parse-positional-numbers`]===void 0)&&(t=this[cm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)),t)}[km](t={}){__classPrivateFieldSet(this,Pp,__classPrivateFieldGet(this,Pp,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,Pp,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,Pp,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,Bp,`f`),Object.keys(__classPrivateFieldGet(this,Op,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,Op,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,Op,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,Pp,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,Pp,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,Pp,`f`).envPrefix,__classPrivateFieldSet(this,Pp,n,`f`),__classPrivateFieldSet(this,qp,__classPrivateFieldGet(this,qp,`f`)?__classPrivateFieldGet(this,qp,`f`).reset(S):usage(this,__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,Xp,__classPrivateFieldGet(this,Xp,`f`)?__classPrivateFieldGet(this,Xp,`f`).reset(S):validation(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldSet(this,hp,__classPrivateFieldGet(this,hp,`f`)?__classPrivateFieldGet(this,hp,`f`).reset():command(__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,Xp,`f`),__classPrivateFieldGet(this,Dp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,yp,`f`)||__classPrivateFieldSet(this,yp,completion(this,__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldGet(this,hp,`f`),__classPrivateFieldGet(this,Up,`f`)),`f`),__classPrivateFieldGet(this,Dp,`f`).reset(),__classPrivateFieldSet(this,bp,null,`f`),__classPrivateFieldSet(this,Np,``,`f`),__classPrivateFieldSet(this,Sp,null,`f`),__classPrivateFieldSet(this,kp,!1,`f`),this.parsed=!1,this}[Om](t,n){return __classPrivateFieldGet(this,Up,`f`).path.relative(t,n)}[Am](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,Pp,`f`).__=__classPrivateFieldGet(this,Up,`f`).y18n.__,__classPrivateFieldGet(this,Pp,`f`).configuration=this[im]();let I=!!__classPrivateFieldGet(this,Pp,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,Pp,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,Up,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,Pp,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,Rp,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,Ap,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Yp,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,qp,`f`).clearCachedHelpMessage();try{if(this[om](),n)return this[Dm](q,I,!!S,!1);__classPrivateFieldGet(this,Ap,`f`)&&[__classPrivateFieldGet(this,Ap,`f`)].concat(X[__classPrivateFieldGet(this,Ap,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,jp,!1,`f`);let H=__classPrivateFieldGet(this,hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,yp,`f`)?.completionKey?[__classPrivateFieldGet(this,yp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,yp,`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,bp,`f`)){let t=__classPrivateFieldGet(this,hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Dm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,bp,`f`)){t=F;break}!__classPrivateFieldGet(this,hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Hp,`f`)&&t&&!re&&__classPrivateFieldGet(this,Xp,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,bp,`f`)&&q._.includes(__classPrivateFieldGet(this,bp,`f`))&&!ne&&(__classPrivateFieldGet(this,Tp,`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[Dm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,yp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,yp,`f`).getCompletion(n,(t,n)=>{if(t)throw new gl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t)}),this.exit(0)}),this[Dm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,kp,`f`)||(Z?(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,Mp,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Tp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,qp,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,Pp,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,Pp,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new gl(W.error.message);if(!ne){let t=this[jm](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!0)),Y=this[_m](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Dp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof gl)__classPrivateFieldGet(this,qp,`f`).fail(t.message,t);else throw t}return this[Dm](Y??q,I,!!S,!0)}[jm](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new gl(S.message);__classPrivateFieldGet(this,Xp,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Xp,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,Gp,`f`)&&(I=__classPrivateFieldGet(this,Xp,`f`).unknownCommands(F)),__classPrivateFieldGet(this,Wp,`f`)&&!I?__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,Kp,`f`)&&__classPrivateFieldGet(this,Xp,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Xp,`f`).limitedChoices(F),__classPrivateFieldGet(this,Xp,`f`).implications(F),__classPrivateFieldGet(this,Xp,`f`).conflicting(F)}}[Mm](){__classPrivateFieldSet(this,kp,!0,`f`)}[Nm](t){if(typeof t==`string`)__classPrivateFieldGet(this,Pp,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,Pp,`f`).key[n]=!0}}}),Im,Lm=__esmMin(()=>{Jf(),Fm(),Im=YargsFactory(qf)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var Rm=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.60.0`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var zm=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,Bm=__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):Vm}function parseNpmrc(t){let n={registry:Vm,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 Vm,Hm=__esmMin(()=>{Vm=`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 Um=__esmMin(()=>{Bm(),__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 Wm=__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 Gm=__esmMin(()=>{zm(),Bm(),Hm(),Um()});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 Km=__esmMin(()=>{zm(),Bm(),Um(),Wm()});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 qm=__esmMin(()=>{zm(),Hm()}),Jm=__esmMin(()=>{zm(),Hm(),Wm(),Gm(),Km(),qm()});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 Ym===void 0&&(Ym=`0.60.0`),Ym}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=wn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=wn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Ym,Xm=__esmMin(()=>{Md(),jn(),Hn(),Jm()}),Zm,Qm=__esmMin(()=>{Zm=`gjsify`}),$m=__commonJSMin(((t,n)=>{let S=(jn(),__toCommonJS(gn)),C=(Al(),__toCommonJS(El)),N=(Md(),__toCommonJS(Ad)),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)})),eh=__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})),th=__commonJSMin(((t,n)=>{let S=eh();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}}}})),nh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(Pl(),__toCommonJS(jl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(jn(),__toCommonJS(gn)),H=$m(),W=th();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)}})),rh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),ih=__commonJSMin(((t,n)=>{var S=(yu(),__toCommonJS(hu)),C=rh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
|
|
149
149
|
`)},set:function(t){S=t}});var F=null,I=Object.getOwnPropertyDescriptor(this,`stack`),H=I.get,W=I.value;delete I.value,delete I.writable,I.set=function(t){F=t},I.get=function(){var t=(F||(H?H.call(this):W)).split(/\r?\n+/g);F||(t[0]=this.name+`: `+this.message);var S=1;for(var C in n)if(n.hasOwnProperty(C)){var N=n[C];if(`line`in N){var I=N.line(this[C]);I&&t.splice(S++,0,` `+I)}`stack`in N&&N.stack(this[C],t)}return t.join(`
|
|
150
150
|
`)},Object.defineProperty(this,"stack",I)};return Object.setPrototypeOf?(Object.setPrototypeOf(N.prototype,Error.prototype),Object.setPrototypeOf(N,Error)):S.inherits(N,Error),N};N.append=function(t,n){return{message:function(S,C){return S||=n,S&&(C[0]+=` `+t.replace(`%s`,S.toString())),C}}},N.line=function(t,n){return{line:function(S){return S||=n,S?t.replace(`%s`,S.toString()):null}}},n.exports=N})),ah=__commonJSMin(((t,n)=>{let hexify=t=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return`0x`+(n.length%2?`0`:``)+n},parseError=(t,n,S)=>{if(!n)return{message:t.message+` while parsing empty string`,position:0};let C=t.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),N=C?+C[2]:t.message.match(/^Unexpected end of JSON.*/i)?n.length-1:null,F=C?t.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(C[1])} (${hexify(C[1])})`):t.message;if(N!=null){let t=N<=S?0:N-S,C=N+S>=n.length?n.length:N+S,I=(t===0?``:`...`)+n.slice(t,C)+(C===n.length?``:`...`);return{message:F+` while parsing ${n===I?``:`near `}${JSON.stringify(I)}`,position:N}}else return{message:F+` while parsing '${n.slice(0,S*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(t,n,S,C){S||=20;let N=parseError(t,n,S);super(N.message),Object.assign(this,N),this.code=`EJSONPARSE`,this.systemError=t,Error.captureStackTrace(this,C||this.constructor)}get name(){return this.constructor.name}set name(t){}get[Symbol.toStringTag](){return this.constructor.name}};let S=Symbol.for(`indent`),C=Symbol.for(`newline`),N=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,F=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(t,n,I)=>{let H=stripBOM(t);I||=20;try{let[,t=`
|
|
151
151
|
`,I=` `]=H.match(F)||H.match(N)||[,``,``],W=JSON.parse(H,n);return W&&typeof W==`object`&&(W[C]=t,W[S]=I),W}catch(n){if(typeof t!=`string`&&!Buffer.isBuffer(t)){let S=Array.isArray(t)&&t.length===0;throw Object.assign(TypeError(`Cannot parse ${S?`an empty array`:String(t)}`),{code:`EJSONPARSE`,systemError:n})}throw new JSONParseError(n,H,I,parseJson)}},stripBOM=t=>String(t).replace(/^\uFEFF/,``);n.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(t,n)=>{try{return JSON.parse(stripBOM(t),n)}catch{}}})),oh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
|
|
@@ -762,37 +762,37 @@ var S=Object.getOwnPropertySymbols,C=Object.prototype.hasOwnProperty,N=Object.pr
|
|
|
762
762
|
`+n;let C=S[0],N=n.slice(C.length);return C+t+(N?`
|
|
763
763
|
`+N:``)}function processStubPlugin(t={}){let n=composeBanner((t.captureBundleUrl?VA:``)+GA+UA+JA+giRuntimePathsStub(t.giRuntimePaths??[],t.giSystemProbes??[]),t.userBanner??``);return{name:`gjsify-process-stub`,renderChunk:{order:`post`,handler(t,S){return S.isEntry?{code:n+`
|
|
764
764
|
`+t,map:null}:null}}}}var JA,YA=__esmMin(()=>{HA(),WA(),KA(),qA(),JA=`if(typeof globalThis.process==="undefined"){const _s=globalThis.imports.system,_G=globalThis.imports.gi.GLib;const _h=t=>t?[0,0]:[0,0];_h.bigint=()=>0n;let _pc;const _p=()=>{if(_pc)return _pc;_pc={platform:"linux",arch:"x64"};try{if(_G.getenv("OS")==="Windows_NT"||_G.getenv("SystemRoot")){const a=(_G.getenv("PROCESSOR_ARCHITECTURE")||"").toLowerCase();_pc={platform:"win32",arch:a==="arm64"?"arm64":a==="x86"?"ia32":"x64"};return _pc}const _r=_G.spawn_sync(null,["uname","-sm"],null,_G.SpawnFlags.SEARCH_PATH,null);if(_r&&_r[0]&&_r[1]){const _t=new TextDecoder().decode(_r[1]).trim().split(/\\s+/);if(_t.length>1){const s=_t[0],m=_t[_t.length-1].toLowerCase();_pc={platform:s==="Linux"?"linux":s==="Darwin"?"darwin":/^CYGWIN/i.test(s)?"cygwin":/^(MINGW|MSYS|Windows)/i.test(s)?"win32":s.toLowerCase(),arch:m==="x86_64"||m==="amd64"?"x64":m==="aarch64"||m==="arm64"?"arm64":/^i[3-6]86$/.test(m)?"ia32":m.startsWith("arm")?"arm":m}}}}catch(e){/* no GLib spawn, or spawn refused: the linux/x64 fallback stands */}return _pc};globalThis.process={get platform(){return _p().platform},get arch(){return _p().arch},version:"v20.0.0",env:new Proxy({},{get(_,p){return typeof p==="string"?(_G.getenv(p)??undefined):undefined},set(_,p,v){if(typeof p==="string")_G.setenv(p,String(v),true);return true},has(_,p){return typeof p==="string"&&_G.getenv(p)!==null},deleteProperty(_,p){if(typeof p==="string")_G.unsetenv(p);return true},ownKeys(){return _G.listenv()??[]},getOwnPropertyDescriptor(_,p){const v=_G.getenv(p);return v!==null?{value:v,writable:true,enumerable:true,configurable:true}:undefined}}),argv:_s?.programArgs?["gjs",_s.programInvocationName||"",..._s.programArgs]:["gjs"],versions:{},config:{},cwd(){return _G.get_current_dir()||"/"},exit(c){_s.exit(c??0)},stderr:{write(s){globalThis.printerr(s)}},stdout:{write(s){globalThis.print(s)}},stdin:null,exitCode:undefined,nextTick(fn,...a){Promise.resolve().then(()=>fn(...a))},hrtime:_h,};}`});async function pickBundler(){let t=globalThis.process?.env?.GJSIFY_CSS_BACKEND;if(t===`npm`)return loadNpmBundler();if(t===`native`){let t=await tryLoadNativeBundler();if(!t)throw Error(`GJSIFY_CSS_BACKEND=native but @gjsify/lightningcss-native is not loadable`+(ZA?`\n${ZA.message}`:``));return t}return await tryLoadNativeBundler()||(ZA&&ge.debug(ZA.message),loadNpmBundler())}async function tryLoadNativeBundler(){if(!isGjs())return null;try{let t=await import(pathToFileURL(createRequire(import.meta.url).resolve(`@gjsify/lightningcss-native`)).href);if(!t.hasNativeLightningcss())return null;let n;try{let t=pathToFileURL(createRequire(import.meta.url).resolve(`@gjsify/utils/native-library`)).href;({openNativeLibrary:n}=await import(t))}catch(t){return ZA=t instanceof Error?t:Error(String(t)),null}return ZA=n(`GjsifyLightningcss`),ZA?null:async(n,S,C)=>{let N;try{N=await flattenCssImports(n,C)}catch(t){throw ge.error(`[gjsify-css-as-string] ${t.message}`),t}let F=targetsToBrowserslist(S);return t.transform({filename:n,code:N,targets:F,minify:!1,sourceMap:!1})}}catch{return null}}async function loadNpmBundler(){let{bundleAsync:t}=await import(`lightningcss`);return async(n,S,C)=>({code:(await t({filename:n,targets:S,minify:!1,errorRecovery:!0,resolver:createCssBundleResolver(C)})).code})}function isAssetReference(t){return/^(data|https?|file):/i.test(t)||QA.test(t)}function createCssBundleResolver(t){return{resolve(n,S){if(bn(n))return t(stripQuery(n)),n;if(n.startsWith(`./`)||n.startsWith(`../`)){let C=vn(wn(S),n);return t(C),C}let C=createRequire(pathToFileURL(S).href);try{let S=C.resolve(n);return t(S),S}catch(t){if(isAssetReference(n))return n;throw Error(`cannot resolve @import "${n}" from ${S} (${t.message}). If it is a workspace/npm package, ensure it is installed and exposes the CSS file via its package.json "exports".`)}}}}function stripQuery(t){let n=t.search(/[?#]/);return n===-1?t:t.slice(0,n)}async function replaceAllAsync(t,n,S){let C=[...t.matchAll(n)];if(C.length===0)return t;let N=``,F=0;for(let n of C){let C=n.index??0;N+=t.slice(F,C),N+=await S(n[0],...n.slice(1)),F=C+n[0].length}return N+=t.slice(F),N}async function flattenCssImports(t,n){let S=new Set,C=createCssBundleResolver(n),inline=async(t,N)=>{let F=bn(t)?stripQuery(t):vn(t);if(S.has(F))return``;S.add(F),n(F);let I=await readFile$1(F,`utf8`);return N||(I=I.replace(/@charset[^;]*;/gi,``)),replaceAllAsync(I,$A,async(t,n,S)=>{let N=C.resolve(n,F);if(N===n)return t;let I=S?.trim();if(I){if(/\b(layer|supports)\s*\(/i.test(I))throw Error(`@import "${n}" in ${F} uses a layer()/supports() condition, which the GJS-native CSS backend does not support. Inline the import manually or drop the condition.`);return`@media ${I} {\n${await inline(N,!1)}\n}`}return inline(N,!1)})};return inline(t,!0)}function targetsToBrowserslist(t){if(!t)return;let n=[];for(let[S,C]of Object.entries(t)){if(typeof C!=`number`)continue;let t=C>>>16&255;if(t===0)continue;let N=S===`ios_saf`?`ios`:S;n.push(`${N} >= ${t}`)}return n.length?n.join(`, `):void 0}function cssAsStringPlugin(t={}){let{targets:n,bundle:S=!0}=t;return{name:`gjsify-css-as-string`,load:{filter:{id:/\.(css|s[ac]ss)$/},async handler(t){let declare=t=>declareBuildInput(this,t);declare(stripQuery(t));let C;return C=/\.s[ac]ss$/.test(t)?await compileSass(t):S?new TextDecoder(`utf-8`).decode(await loadAndBundleCss(t,n,declare)):await readFile$1(t,`utf8`),{code:`export default ${JSON.stringify(C)};`,moduleType:`js`}}}}}async function compileSass(t){ej||=import(`sass`);try{return(await ej).compile(t,{style:`expanded`}).css}catch(n){throw Error(`gjsify css-as-string: failed to compile Sass file ${t}. Is the \`sass\` package installed? (${n.message})`)}}async function loadAndBundleCss(t,n,S){XA||=pickBundler();let{code:C}=await(await XA)(t,n,S);return C}var XA,ZA,QA,$A,ej,tj=__esmMin(()=>{_e(),hd(),Al(),jn(),Hn(),t_(),eC(),XA=null,ZA=null,QA=/\.(woff2?|ttf|otf|eot|svg|png|jpe?g|gif|webp|avif|ico)(\?|#|$)/i,$A=/@import\s+(?:url\(\s*)?["']?([^"')\s;]+)["']?\s*\)?\s*([^;]*);/g,ej=null});function parse$1(t){let n={ecmaVersion:`latest`,allowHashBang:!0,allowAwaitOutsideFunction:!0};try{return parse$2(t,{...n,sourceType:`module`})}catch{}try{return parse$2(t,{...n,sourceType:`script`,allowReturnOutsideFunction:!0})}catch{return null}}function freeConsoleAssignmentInsertion(t){if(!nj.test(t))return null;let n=parse$1(t);if(!n)return null;let S=!1,C=!1,bindsConsole=t=>!!t&&extractBindingNames(t).includes(`console`);if(full(n,t=>{switch(t.type){case`VariableDeclarator`:bindsConsole(t.id)&&(S=!0);break;case`FunctionDeclaration`:case`FunctionExpression`:case`ArrowFunctionExpression`:(bindsConsole(t.id)||t.params.some(t=>bindsConsole(t)))&&(S=!0);break;case`ClassDeclaration`:case`ClassExpression`:bindsConsole(t.id)&&(S=!0);break;case`CatchClause`:bindsConsole(t.param)&&(S=!0);break;case`ImportSpecifier`:case`ImportDefaultSpecifier`:case`ImportNamespaceSpecifier`:t.local.name===`console`&&(S=!0);break;case`AssignmentExpression`:bindsConsole(t.left)&&(C=!0);break}}),!C||S)return null;let N=0;for(let t of n.body){if(t.type!==`ExpressionStatement`||!(`directive`in t))break;N=t.end}return N}function bindConsoleLocally(t){let n=freeConsoleAssignmentInsertion(t);if(n===null)return null;let S=n===0?``:`;`;return`${t.slice(0,n)}${S}${ij}${t.slice(n)}`}function consoleAssignPlugin(){return{name:`gjsify-console-assign`,transform:{filter:{id:rj},handler(t,n){if(!rj.test(n))return null;let S=bindConsoleLocally(t);return S===null?null:{code:S,map:null}}}}}var nj,rj,ij,aj=__esmMin(()=>{Ax(),Mx(),Jx(),nj=/(?:^|[^.\w$])console\s*=(?![=>])/,rj=/\.(?:m|c)?jsx?$/,ij=`var console = globalThis.console;`,__name$1(parse$1,`parse`)});function isScopeRoot(t){switch(t.type){case`Program`:case`FunctionDeclaration`:case`FunctionExpression`:case`ArrowFunctionExpression`:case`TSDeclareFunction`:case`TSDeclareMethod`:case`TSEmptyBodyFunctionExpression`:return!0;default:return!1}}function bindingNames(t){switch(t.type){case`VariableDeclarator`:return t.id?extractBindingNames(asAcornNode(t.id)):[];case`FunctionDeclaration`:case`FunctionExpression`:case`ArrowFunctionExpression`:case`TSDeclareFunction`:case`TSDeclareMethod`:case`TSEmptyBodyFunctionExpression`:{let n=t.id?.name===void 0?[]:[t.id.name];for(let S of t.params??[])n.push(...extractBindingNames(asAcornNode(S)));return n}case`ClassDeclaration`:case`ClassExpression`:return t.id?.name===void 0?[]:[t.id.name];case`CatchClause`:return t.param?extractBindingNames(asAcornNode(t.param)):[];case`ImportSpecifier`:case`ImportDefaultSpecifier`:case`ImportNamespaceSpecifier`:return t.local?.name===void 0?[]:[t.local.name];default:return[]}}function hoistsOutward(t,n){switch(t.type){case`FunctionDeclaration`:case`ClassDeclaration`:case`TSDeclareFunction`:return t.id?.name===n;default:return!1}}function freeTarget(t){return t.type===`AssignmentExpression`?t.left?.type===`Identifier`&&lj.has(t.operator??``)?t.left:null:(t.type===`ForInStatement`||t.type===`ForOfStatement`)&&t.left?.type===`Identifier`?t.left:null}function collectAssignments(t){let n=[],S=new Map,C=!1,N=[{node:t,roots:[]}];for(;N.length>0;){let{node:t,roots:F}=N.pop(),I=isScopeRoot(t)?[t,...F]:F;t.type===`WithStatement`&&(C=!0);for(let n of bindingNames(t)){let C=I[0];if(C&&(addBinding(S,C,n),hoistsOutward(t,n))){let t=I[1];t&&addBinding(S,t,n)}}let H=freeTarget(t);H&&H.name!==void 0&&!sj.has(H.name)&&n.push({name:H.name,start:H.start,end:H.end,roots:I});for(let n of childrenOf(t))N.push({node:n,roots:I})}return C?null:n.filter(({name:t,roots:n})=>!n.some(n=>S.get(n)?.has(t))).map(({name:t,start:n,end:S})=>({name:t,start:n,end:S}))}function addBinding(t,n,S){let C=t.get(n);if(C){C.add(S);return}t.set(n,new Set([S]))}function childrenOf(t){let n=[];for(let S of Object.values(t)){if(Array.isArray(S)){for(let t of S)pushIfNode(t,n);continue}pushIfNode(S,n)}return n}function pushIfNode(t,n){typeof t!=`object`||!t||typeof t.type==`string`&&n.push(t)}function findImplicitGlobalAssignments(t,n){let S;try{S=parseSource(t,n)}catch{return null}return collectAssignments(S)}function rewriteImplicitGlobalAssignments(t,n){let S=findImplicitGlobalAssignments(t,n);if(!S||S.length===0)return null;let C=t;for(let t of[...S].sort((t,n)=>n.start-t.start))C=C.slice(0,t.start)+cj+t.name+C.slice(t.end);return C}function implicitGlobalAssignPlugin(){return{name:oj,transform:{filter:{id:tC},handler(t,n){if(!tC.test(n))return null;let S=rewriteImplicitGlobalAssignments(t,n);return S===null?null:{code:S,map:null}}}}}var oj,sj,cj,lj,asAcornNode,uj=__esmMin(()=>{Jx(),mS(),lC(),oj=`gjsify-implicit-global-assign`,sj=new Set([`undefined`,`NaN`,`Infinity`,`arguments`,`eval`,`globalThis`,`exports`,`module`,`require`,`__filename`,`__dirname`]),cj=`globalThis.`,lj=new Set([`=`]),asAcornNode=t=>t});function inputShebangStripPlugin(){return{name:`gjsify-input-shebang-strip`,transform:{order:`pre`,handler(t){return t.startsWith(`#!`)?{code:t.replace(pj,``),map:null}:null}}}}function shebangPlugin(t={}){if(!t.enabled)return null;let n=t.line??`#!/usr/bin/env -S gjs -m`;return{name:`gjsify-shebang`,renderChunk:{order:`post`,handler(t,S){return!S.isEntry||t.startsWith(`#!`)?null:{code:n+`
|
|
765
|
-
`+t,map:null}}}}}function expandEnvTemplate(t,n=process.env){return t.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g,(t,S,C)=>{let N=n[S];return N!==void 0&&N!==``?N:C??``})}function resolveShebangLine(t,n=dj){if(t===void 0||t===!1)return null;if(t===!0)return n;let S=expandEnvTemplate(t);return S.trim()?S.startsWith(`#!`)?S:`#!`+S:null}var dj,fj,pj,mj=__esmMin(()=>{dj=`#!/usr/bin/env -S gjs -m`,fj=`#!/usr/bin/env node`,pj=/^#![^\n]*\n/});function resolveShim(t){let n=vn(hj,`../shims/${t}.js`);if(existsSync(n))return n;try{return createRequire(import.meta.url).resolve(`@gjsify/rolldown-plugin-gjsify/shims/${t}`)}catch(S){throw Error(`@gjsify/rolldown-plugin-gjsify: cannot locate the "${t}" shim. Tried ${n} and the "./shims/${t}" subpath export.`,{cause:S})}}function flattenAliases$4(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}function createGjsExternalsPredicate(t=[]){let n=[`cairo`,`gettext`,`system`,...t];return t=>isRegisterSubpath(t)||isGjsifyShim(t)?!1:!!(t.startsWith(`gi://`)||n.includes(t))}function isGjsifyShim(t){return/@gjsify\/rolldown-plugin-gjsify\/shims\/[^?]+$/.test(t)?!0:/[\\/]rolldown-plugin-gjsify[\\/](?:lib|src)[\\/]shims[\\/]/.test(t)}function isRegisterSubpath(t){return!!(/\/register(?:\/[^?]*)?$/.test(t)||/[/\\]register(?:[/\\][^/\\]+)?\.(?:[mc]?js|ts)$/.test(t))}var hj,setupForGjs,gj=__esmMin(()=>{Hn(),jn(),Md(),Al(),bS(),xS(),kS(),FS(),zS(),GS(),QS(),pC(),yT(),BA(),cv(),Ny(),lC(),YA(),tj(),aj(),uj(),mj(),vS(),hj=wn(fileURLToPath(import.meta.url)),setupForGjs=async t=>{let n=t.userExternal??[],S=[`cairo`,`gettext`,`system`,...n.filter(t=>!isRegisterSubpath(t)&&!isGjsifyShim(t))],C=createGjsExternalsPredicate(n),N=t.pluginOptions.format??`esm`,F=t.pluginOptions.exclude??[],I=await globToEntryPoints(t.input,F),H=resolveShim(`unicorn-magic`),W={...getAliasesForGjs({external:C}),"unicorn-magic":H,...t.pluginOptions.aliases,...t.userAliases},q=t.pluginOptions.consoleShim===!1?null:resolveShim(`console-gjs`),Y=[];t.pluginOptions.autoGlobalsInject&&Y.push(t.pluginOptions.autoGlobalsInject);let X=wrapInputWithSideEffects(I,Y,{preserveDefaultExport:t.pluginOptions.preserveDefaultExport===!0,exitOnReportedCode:!0}),Z={input:X.input,platform:`neutral`,external:S,resolve:{mainFields:N===`esm`?[`browser`,`module`,`main`]:[`browser`,`main`,`module`],conditionNames:[`browser`]},transform:{target:`firefox140`,define:{global:`globalThis`,window:`globalThis`,"process.env.READABLE_STREAM":`"disable"`,"process.env.NODE_ENV":`"production"`},...q?{inject:{console:[q,`console`]}}:{}},output:{...t.output,format:N,sourcemap:!1,codeSplitting:!1},treeshake:!0},te=getBundleDirFromOutput(t.output),ne={"random-access-file":`random-access-file/index.js`,...flattenAliases$4(W)},re=[deepkitPlugin({reflection:t.pluginOptions.reflection})];return t.pluginOptions.dialect===`react-native`&&re.push(reactNativeSupportGatePlugin()),{options:Z,prePlugins:re,plugins:[...X.plugin?[X.plugin]:[],inputShebangStripPlugin(),...q?[consoleAssignPlugin()]:[],implicitGlobalAssignPlugin(),giOptionalPlugin(`gjs`),platformResolvePlugin({suffixes:desktopSuffixChain(desktopOsSuffix()),refusedSuffixes:US,siblingIndex:!0}),...t.pluginOptions.dialect===`react-native`?[reactNativeAliasPlugin()]:[],aliasPlugin({entries:ne}),napiNodeAddonPlugin({runtimeResolve:N===`esm`}),externalsPlugin(C,{name:`gjsify-gjs-externalize`}),blueprintPlugin(),cssAsStringPlugin({targets:{firefox:60<<16}}),nodeModulesPathRewritePlugin({bundleDir:te,runtimeResolve:N===`esm`}),...t.pluginOptions.skipProcessStub?[]:[processStubPlugin({userBanner:t.userBanner,captureBundleUrl:N===`esm`,giSystemProbes:t.giSystemProbes})],(()=>{let n=resolveShebangLine(t.shebang);return shebangPlugin({enabled:n!==null,line:n??void 0})})(),unresolvedWorkspaceImportPlugin({target:`gjs`,aliases:ne,isExternal:C,...t.pluginOptions.toolchainAnchor===void 0?{}:{toolchainAnchor:t.pluginOptions.toolchainAnchor}})]}},__name$1(flattenAliases$4,`flattenAliases`)});function gjsImportsEmptyPlugin(t={}){let n=t.emptyGirs??!0?/^(@girs\/|gi:\/\/)/:/^gi:\/\//,isVocabulary=t=>/^@girs\/[^/]+\/vocabulary$/.test(t);return{name:`gjsify-gjs-imports-empty`,resolveId:{order:`pre`,filter:{id:n},handler(t){return!n.test(t)||isVocabulary(t)?null:{id:_j}}},load(t){return t===_j?{code:`export {}; export default {};`,moduleSideEffects:!1}:null}}}var _j,vj=__esmMin(()=>{gS(),_j=`${hS}empty-gjs-import`});function readdirSafe(t){try{return readdirSync(t)}catch{return[]}}function hasNodeBinary(t){for(let n of readdirSafe(t))if(n.endsWith(`.node`)||readdirSafe(xn(t,n)).some(t=>t.endsWith(`.node`)))return!0;return!1}function isNodeAddonPackage(t,n){if(isGjsifyNativeBridge(n))return!1;if(n.gypfile===!0||n.binary!==null&&typeof n.binary==`object`||existsSync(xn(t,`binding.gyp`)))return!0;let S={...n.dependencies,...n.optionalDependencies};return bj.some(t=>t in S)||isNapiRsPackageJson(n)?!0:hasNodeBinary(xn(t,`prebuilds`))||hasNodeBinary(xn(t,`build`))}function packageNameOf(t){if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`\0`)||t.includes(`:`))return null;let n=t.split(`/`);return t.startsWith(`@`)?n.length>=2&&n[1]?`${n[0]}/${n[1]}`:null:n[0]||null}function packageRootFor(t,n){let S=wn(t);for(let t=0;t<64;t++){let t=xn(S,`package.json`);if(existsSync(t))try{let C=JSON.parse(readFileSync(t,`utf8`));if(C.name===n)return{root:S,pkg:C}}catch{}let C=wn(S);if(C===S)break;S=C}return null}function nodeNativeExternalPlugin(){let t=new Map;return{name:`gjsify-node-native-external`,resolveId:{order:`pre`,filter:{id:yj},async handler(n,S){let C=packageNameOf(n);if(C===null)return null;let N=typeof S==`string`?S:void 0,F=`${C}\0${N===void 0?``:wn(N)}`,I=t.get(F);if(I===void 0){I=!1;let S=await this.resolve(n,N,{skipSelf:!0});if(S&&!S.external&&bn(S.id)&&existsSync(S.id)){let t=packageRootFor(S.id,C);I=t!==null&&isNodeAddonPackage(t.root,t.pkg)}t.set(F,I)}return I?{id:n,external:!0}:null}}}}var yj,bj,xj=__esmMin(()=>{Md(),jn(),kS(),yj=/^[^.\\/:\s\x00][^:\s\x00]*$/,bj=[`node-gyp-build`,`node-gyp-build-optional-packages`,`bindings`,`prebuild-install`,`node-pre-gyp`,`@mapbox/node-pre-gyp`,`cmake-js`]});function assertReverseBridgeRoutes(){let t=createRequire(import.meta.url),resolves=n=>{try{return t.resolve(n),!0}catch{return!1}};for(let[t,n]of Object.entries(Tj))if(resolves(t)&&!resolves(n))throw Error(`@gjsify/rolldown-plugin-gjsify: the reverse-bridge entry route for "${t}" is dangling — "${n}" does not resolve, while "${t}" does. Without the route this build silently takes ${t}'s "node" export condition, which is why the route exists; update REVERSE_BRIDGE_ENTRY_ROUTES in app/node.ts to the entry the --app gjs build resolves.`)}function enableGjsRegistersForNode(t){let n={};for(let[S,C]of Object.entries(t))C===`@gjsify/empty`&&wj.test(S)||(n[S]=C);for(let[t,S]of Object.entries(rv))wj.test(t)&&(n[t]=S);return Object.assign(n,Tj),n}function isGjsSourceBuild(t){return!!(t.nodeGiGlobalsInject||t.registerInject)}function flattenAliases$3(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var Sj,Cj,wj,Tj,setupForNode,Ej=__esmMin(()=>{Al(),bS(),BA(),yT(),sv(),cv(),Ny(),lC(),tj(),vj(),jS(),FS(),uj(),zS(),xj(),GS(),QS(),pC(),vS(),Sj=`@gjsify/node-gi/globals`,Cj=Object.values(av),wj=/\/register(\/|$)/,Tj={"solid-js":`solid-js/dist/solid.js`},setupForNode=async t=>{let n=t.userExternal??[],S=[...X_,`@gjsify/node-gi`,`@gjsify/node-gi/gi`,Sj,...Cj,...n],external=t=>!!(S.includes(t)||t===`@gjsify/node-gi`||t.startsWith(`@gjsify/node-gi/`)),C=t.pluginOptions.format??`esm`,N=t.pluginOptions.exclude??[],F=await globToEntryPoints(t.input,N),I=[];t.pluginOptions.nodeGiGlobalsInject&&I.push(Sj);let H=t.pluginOptions.autoGlobalsInject;H&&I.push(H);let W=wrapInputWithSideEffects(F,I),q=W.input,Y=isGjsSourceBuild({...t.pluginOptions,registerInject:H});Y&&assertReverseBridgeRoutes();let X=getAliasesForNode({external}),Z=flattenAliases$3({...Y?enableGjsRegistersForNode(X):X,...t.pluginOptions.aliases,...t.userAliases}),te=getBundleDirFromOutput(t.output),ne={input:q,platform:`node`,external:S,resolve:{mainFields:C===`esm`?[`module`,`main`,`browser`]:[`main`,`module`,`browser`],conditionNames:C===`esm`?[`node`]:[`require`]},transform:{target:`node24`,define:{global:`globalThis`}},output:{...t.output,format:C,sourcemap:!1,banner:void 0,codeSplitting:!1},treeshake:!0},re=[deepkitPlugin({reflection:t.pluginOptions.reflection})];return t.pluginOptions.dialect===`react-native`&&re.push(reactNativeSupportGatePlugin()),{options:ne,prePlugins:re,plugins:[...W.plugin?[W.plugin]:[],giOptionalPlugin(`node`),gjsGiNodePlugin(),gjsBuiltinModulesNodePlugin(av),implicitGlobalAssignPlugin(),gjsImportsEmptyPlugin({emptyGirs:!Y}),platformResolvePlugin({suffixes:desktopSuffixChain(desktopOsSuffix()),refusedSuffixes:US,siblingIndex:!0}),...t.pluginOptions.dialect===`react-native`?[reactNativeAliasPlugin()]:[],nodeNativeExternalPlugin(),aliasPlugin({entries:Z}),blueprintPlugin(),cssAsStringPlugin(t.pluginOptions.nodeGiGlobalsInject?{targets:{firefox:60<<16}}:{}),nodeModulesPathRewritePlugin({bundleDir:te}),unresolvedWorkspaceImportPlugin({target:`node`,aliases:Z,isExternal:external})]}},__name$1(flattenAliases$3,`flattenAliases`)});function importLine(t,n){let S=t.specifiers?.[n];return S===void 0?`import { ${n} as namespace } from ${JSON.stringify(t.renderer)};\n`:`import * as namespace from ${JSON.stringify(S)};\n`}function giRendererShimSource(t,n,S){return importLine(t,n)+`const RENDERER = ${JSON.stringify(t.renderer)};\nconst APP = ${JSON.stringify(t.app)};\nconst NS = ${JSON.stringify(n)};\nconst VERSION = ${JSON.stringify(S)};\nexport default new Proxy(namespace, {\n get(target, property, receiver) {\n if (typeof property === 'symbol' || property === 'then' || property in target) {\n return Reflect.get(target, property, receiver);\n }\n throw new Error(\n 'the ' + NS + ' arm (version ' + VERSION + ') on --app ' + APP + ': ' + RENDERER +\n ' has no ' + String(property) + '. A renderer implements a fraction of the GIR ' +\n 'vocabulary, and every absent member is a declared remainder (ADR 0034 clause 3) ' +\n 'rather than an oversight — refused by name here because reading it would be ' +\n 'undefined and \`class X extends undefined\` throws far from the import that asked ' +\n 'for it. It has: ' + Object.keys(target).sort().join(', ') + '.'\n );\n },\n});\n`}function giRendererPlugin(t){let n=Object.keys(t.namespaces).sort().map(n=>`${n} (version ${t.namespaces[n]})`).join(`, `);return{name:`gjsify-gi-renderer`,resolveId:{order:`pre`,filter:{id:/^gi:\/\//},handler(S){let C=parseGiSpecifier$1(S);if(C===null)return null;let N=t.namespaces[C.namespace];if(N===void 0)throw Error(`gjsify build --app ${t.app}: \`${S}\` has no widget renderer. --gi-renderer answers ${n} out of ${t.renderer} and nothing else — there is no GObject introspection on this target, so a namespace with no renderer counterpart cannot be substituted for. Drop --gi-renderer to keep the previous behaviour (every \`gi://\` import becomes an empty module), or gate the import to a target that has GI (\`--app gjs\`, \`--app node\`).`);if(C.version!==void 0&&C.version!==N)throw Error(`gjsify build --app ${t.app}: \`${S}\` asks for ${C.namespace} version ${C.version}; this arm answers version ${N} — the version ${t.renderer}'s vocabulary is held against. GJS throws on a version it has no typelib for, so accepting it here would make this target the only place a wrong version passes.`);return{id:`${Dj}${C.namespace}`}}},load(n){if(!n.startsWith(Dj))return null;let S=n.slice(Dj.length),C=t.namespaces[S];return C===void 0?null:{code:giRendererShimSource(t,S,C),moduleSideEffects:!1}}}}var Dj,Oj=__esmMin(()=>{gS(),jS(),Dj=`${hS}gi-renderer:`});function blueprintTemplateExit(t,n){return n===void 0?{refusal:`On --app ${t} it is the projected tree of the renderer --gi-renderer composes, and that flag is off. Pass --gi-renderer, or import the file without \`?template\`.`}:{renderer:n.renderer.replace(/^@gjsify\//,``)}}var kj=__esmMin(()=>{});function flattenAliases$2(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var setupForBrowser,Aj=__esmMin(()=>{bS(),yT(),BA(),sv(),Ny(),vj(),GS(),Oj(),kj(),tj(),zS(),uj(),setupForBrowser=async t=>{let n=[...t.userExternal??[]],S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=t.pluginOptions.giRenderer?q_.browser:void 0,F={};for(let[t,n]of Object.entries(tv))F[t]=n,F[`node:${t}`]=n;let I={},H={...getDerivedAliasesSync(`browser`),...F,...I,...t.pluginOptions.aliases,...t.userAliases},W={input:C,platform:`browser`,external:n,resolve:{mainFields:[`browser`,`module`,`main`],conditionNames:[`import`,`browser`]},transform:{target:`esnext`,define:{global:`globalThis`,window:`globalThis`,"process.env.NODE_ENV":`"production"`}},output:{...t.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},q=flattenAliases$2(H);return{options:W,prePlugins:[deepkitPlugin({reflection:t.pluginOptions.reflection})],plugins:[platformResolvePlugin({suffixes:browserSuffixChain(),refusedSuffixes:WS,siblingIndex:!0}),...N?[giRendererPlugin({app:`browser`,...N})]:[],gjsImportsEmptyPlugin({emptyGirs:!N}),aliasPlugin({entries:q}),blueprintPlugin({template:blueprintTemplateExit(`browser`,N)}),implicitGlobalAssignPlugin(),cssAsStringPlugin(),unresolvedWorkspaceImportPlugin({target:`browser`,aliases:q,isExternal:t=>n.includes(t)})]}},__name$1(flattenAliases$2,`flattenAliases`)});function flattenAliases$1(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var jj,setupForNativescript,Mj=__esmMin(()=>{bS(),BA(),yT(),sv(),Ny(),vj(),Oj(),kj(),GS(),zS(),uj(),jj=/^@nativescript\/core(?:\/|$)/,setupForNativescript=async t=>{let n=[...t.userExternal??[],jj],isExternal=t=>n.some(n=>typeof n==`string`?n===t:n.test(t)),S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=t.pluginOptions.giRenderer?q_.nativescript:void 0,F=detectNativescriptPlatform(),I={};for(let[t,n]of Object.entries(nv))I[t]=n,I[`node:${t}`]=n;let H={},W={...getDerivedAliasesSync(`nativescript`),...I,...H,...t.pluginOptions.aliases,...t.userAliases},q={input:C,platform:`browser`,external:n,resolve:{mainFields:[`nativescript`,`module`,`main`],conditionNames:[`import`,`nativescript`]},transform:{target:`esnext`,define:{global:`globalThis`,...nativescriptPlatformDefines(F,{dev:!1})}},output:{...t.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},Y=flattenAliases$1(W);return{options:q,prePlugins:[deepkitPlugin({reflection:t.pluginOptions.reflection})],plugins:[...N?[giRendererPlugin({app:`nativescript`,...N})]:[],gjsImportsEmptyPlugin({emptyGirs:!N}),platformResolvePlugin({suffixes:nativescriptSuffixChain(F)}),aliasPlugin({entries:Y}),blueprintPlugin({template:blueprintTemplateExit(`nativescript`,N)}),implicitGlobalAssignPlugin(),unresolvedWorkspaceImportPlugin({target:`nativescript`,aliases:Y,isExternal})]}},__name$1(flattenAliases$1,`flattenAliases`)}),Nj=__esmMin(()=>{gj(),Ej(),Aj(),Mj()});function isExternalSpecifier(t){return!(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.startsWith(`\0`)||t.startsWith(`data:`))}function computeCommonRoot(t){let n=t===void 0?[]:typeof t==`string`?[t]:Array.isArray(t)?t:Object.values(t);if(n.length===0)return`src`;let S=n.map(t=>t.split(`/`).filter(Boolean)),C=S[0],N=0;for(;N<C.length;N++){let t=C[N];if(!S.every(n=>n[N]===t))break}if(N===0)return`src`;let F=C.slice(0,N);return S.some(t=>t.length>N)?F.join(`/`):F.slice(0,-1).join(`/`)||`src`}function flattenAliases(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var setupLib,Pj=__esmMin(()=>{BA(),bS(),tj(),xS(),Ny(),setupLib=async t=>{let n=t.pluginOptions.format??t.pluginOptions.library??`esm`,S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=computeCommonRoot(C),F={...t.pluginOptions.aliases,...t.userAliases};return{options:{input:C,platform:`neutral`,resolve:{mainFields:n===`esm`?[`module`,`main`]:[`main`],conditionNames:n===`esm`?[`module`,`import`]:[`require`]},transform:{target:`esnext`},output:{...t.output,format:n,preserveModules:!0,preserveModulesRoot:N,sourcemap:!1},treeshake:!1},prePlugins:[],plugins:[aliasPlugin({entries:flattenAliases(F)}),externalsPlugin(isExternalSpecifier,{name:`gjsify-lib-externalize`}),cssAsStringPlugin(),blueprintPlugin()]}}}),Fj=__esmMin(()=>{Pj()});function mimeForExtension(t){return Ij[t.toLowerCase()]??`application/octet-stream`}function textLoaderPlugin(t={}){let n=t.loaders??{},S=Object.entries(n),C=S.filter(([,t])=>t===`text`).map(([t])=>t),N=S.filter(([,t])=>t===`dataurl`).map(([t])=>t),F=[...C,...N];if(F.length===0)return null;let I=F.map(t=>t.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),H=RegExp(`\\.(?:${I.join(`|`)})$`),W=new Map(S.map(([t,n])=>[t.toLowerCase(),n]));return{name:`gjsify-asset-loader`,async load(t){if(!H.test(t))return null;let n=t.lastIndexOf(`.`),S=n>=0?t.slice(n).toLowerCase():``;if((W.get(S)??`text`)===`dataurl`){let n=await readFile$1(t),C=mimeForExtension(S),N=n.toString(`base64`);return{code:`export default ${JSON.stringify(`data:${C};base64,${N}`)};`,moduleType:`js`}}let C=await readFile$1(t,`utf8`);return{code:`export default ${JSON.stringify(C)};`,moduleType:`js`}}}}var Ij,Lj=__esmMin(()=>{hd(),Ij={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".avif":`image/avif`,".bmp":`image/bmp`,".tiff":`image/tiff`,".tif":`image/tiff`,".wasm":`application/wasm`}}),Rj=__esmMin(()=>{Md(),jn()}),gjsifyPlugin,zj=__esmMin(()=>{Nj(),Fj(),gjsifyPlugin=async(t,n={})=>{if(n.library)switch(n.library){case`esm`:case`cjs`:return await setupLib({input:t.input,output:t.output,userAliases:t.userAliases,pluginOptions:n});default:throw TypeError(`Unknown library type: `+n.library)}let S=n.app??`gjs`;switch(S){case`gjs`:return await setupForGjs({input:t.input,output:t.output,userExternal:t.userExternal,userBanner:t.userBanner,userAliases:t.userAliases,shebang:t.shebang,giSystemProbes:t.giSystemProbes,pluginOptions:n});case`node`:return await setupForNode({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});case`browser`:return await setupForBrowser({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});case`nativescript`:return await setupForNativescript({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});default:throw TypeError(`Unknown app platform: `+S)}}}),Bj=__esmMin(()=>{V_(),yS(),Nj(),Fj(),lC(),YA(),qA(),FS(),aj(),uj(),tj(),Lj(),mj(),bS(),vj(),xS(),zS(),kS(),xj(),GS(),Rj(),QS(),pC(),fC(),zj(),zj(),sv()});function normalizeWindowsPath(t=``){return t&&t.replace(/\\/g,`/`).replace(Vj,t=>t.toUpperCase())}function cwd(){return typeof process<`u`&&typeof process.cwd==`function`?process.cwd().replace(/\\/g,`/`):`/`}function normalizeString(t,n){let S=``,C=0,N=-1,F=0,I=null;for(let H=0;H<=t.length;++H){if(H<t.length)I=t[H];else if(I===`/`)break;else I=`/`;if(I===`/`){if(!(N===H-1||F===1))if(F===2){if(S.length<2||C!==2||S[S.length-1]!==`.`||S[S.length-2]!==`.`){if(S.length>2){let t=S.lastIndexOf(`/`);t===-1?(S=``,C=0):(S=S.slice(0,t),C=S.length-1-S.lastIndexOf(`/`)),N=H,F=0;continue}else if(S.length>0){S=``,C=0,N=H,F=0;continue}}n&&(S+=S.length>0?`/..`:`..`,C=2)}else S.length>0?S+=`/${t.slice(N+1,H)}`:S=t.slice(N+1,H),C=H-N-1;N=H,F=0}else I===`.`&&F!==-1?++F:F=-1}return S}var Vj,Hj,Uj,Wj,normalize,Gj,resolve,isAbsolute,Kj=__esmMin(()=>{Vj=/^[A-Za-z]:\//,Hj=/^[/\\]{2}/,Uj=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,Wj=/^[A-Za-z]:$/,normalize=function(t){if(t.length===0)return`.`;t=normalizeWindowsPath(t);let n=t.match(Hj),S=isAbsolute(t),C=t[t.length-1]===`/`;return t=normalizeString(t,!S),t.length===0?S?`/`:C?`./`:`.`:(C&&(t+=`/`),Wj.test(t)&&(t+=`/`),n?S?`//${t}`:`//./${t}`:S&&!isAbsolute(t)?`/${t}`:t)},Gj=__name$1(function(...t){let n=``;for(let S of t)if(S)if(n.length>0){let t=n[n.length-1]===`/`,C=S[0]===`/`;t&&C?n+=S.slice(1):n+=t||C?S:`/${S}`}else n+=S;return normalize(n)},`join`),resolve=function(...t){t=t.map(t=>normalizeWindowsPath(t));let n=``,S=!1;for(let C=t.length-1;C>=-1&&!S;C--){let N=C>=0?t[C]:cwd();!N||N.length===0||(n=`${N}/${n}`,S=isAbsolute(N))}return n=normalizeString(n,!S),S&&!isAbsolute(n)?`/${n}`:n.length>0?n:`.`},isAbsolute=function(t){return Uj.test(t)}}),qj=__esmMin(()=>{Kj()});function i$2(t,n={}){return{sample:n.indent===void 0&&n.preserveIndentation!==!1&&t.slice(0,n?.sampleSize||1024),whiteSpace:n.preserveWhitespace===!1?void 0:{start:Yj.exec(t)?.[0]||``,end:Xj.exec(t)?.[0]||``}}}function a$4(t,n,S){!n||typeof n!=`object`||Object.defineProperty(n,Jj,{enumerable:!1,configurable:!0,writable:!0,value:i$2(t,S)})}var Jj,Yj,Xj,Zj=__esmMin(()=>{Jj=Symbol.for(`__confbox_fmt__`),Yj=/^(\s+)/,Xj=/(\s+)$/,__name$1(i$2,`i`),__name$1(a$4,`a`)});function e$1(t,n=!1){let S=t.length,C=0,N=``,F=0,I=16,H=0,W=0,q=0,Y=0,X=0;function h(n,S){let N=0,F=0;for(;N<n||!S;){let n=t.charCodeAt(C);if(n>=48&&n<=57)F=F*16+n-48;else if(n>=65&&n<=70)F=F*16+n-65+10;else if(n>=97&&n<=102)F=F*16+n-97+10;else break;C++,N++}return N<n&&(F=-1),F}function g(t){C=t,N=``,F=0,I=16,X=0}function _(){let n=C;if(t.charCodeAt(C)===48)C++;else for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;if(C<t.length&&t.charCodeAt(C)===46)if(C++,C<t.length&&r$2(t.charCodeAt(C)))for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;else return X=3,t.substring(n,C);let S=C;if(C<t.length&&(t.charCodeAt(C)===69||t.charCodeAt(C)===101))if(C++,(C<t.length&&t.charCodeAt(C)===43||t.charCodeAt(C)===45)&&C++,C<t.length&&r$2(t.charCodeAt(C))){for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;S=C}else X=3;return t.substring(n,S)}function v(){let n=``,N=C;for(;;){if(C>=S){n+=t.substring(N,C),X=2;break}let F=t.charCodeAt(C);if(F===34){n+=t.substring(N,C),C++;break}if(F===92){if(n+=t.substring(N,C),C++,C>=S){X=2;break}switch(t.charCodeAt(C++)){case 34:n+=`"`;break;case 92:n+=`\\`;break;case 47:n+=`/`;break;case 98:n+=`\b`;break;case 102:n+=`\f`;break;case 110:n+=`
|
|
765
|
+
`+t,map:null}}}}}function expandEnvTemplate(t,n=process.env){return t.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g,(t,S,C)=>{let N=n[S];return N!==void 0&&N!==``?N:C??``})}function resolveShebangLine(t,n=dj){if(t===void 0||t===!1)return null;if(t===!0)return n;let S=expandEnvTemplate(t);return S.trim()?S.startsWith(`#!`)?S:`#!`+S:null}var dj,fj,pj,mj=__esmMin(()=>{dj=`#!/usr/bin/env -S gjs -m`,fj=`#!/usr/bin/env node`,pj=/^#![^\n]*\n/});function resolveShim(t){let n=vn(hj,`../shims/${t}.js`);if(existsSync(n))return n;try{return createRequire(import.meta.url).resolve(`@gjsify/rolldown-plugin-gjsify/shims/${t}`)}catch(S){throw Error(`@gjsify/rolldown-plugin-gjsify: cannot locate the "${t}" shim. Tried ${n} and the "./shims/${t}" subpath export.`,{cause:S})}}function flattenAliases$4(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}function createGjsExternalsPredicate(t=[]){let n=[`cairo`,`gettext`,`system`,...t];return t=>isRegisterSubpath(t)||isGjsifyShim(t)?!1:!!(t.startsWith(`gi://`)||n.includes(t))}function isGjsifyShim(t){return/@gjsify\/rolldown-plugin-gjsify\/shims\/[^?]+$/.test(t)?!0:/[\\/]rolldown-plugin-gjsify[\\/](?:lib|src)[\\/]shims[\\/]/.test(t)}function isRegisterSubpath(t){return!!(/\/register(?:\/[^?]*)?$/.test(t)||/[/\\]register(?:[/\\][^/\\]+)?\.(?:[mc]?js|ts)$/.test(t))}var hj,setupForGjs,gj=__esmMin(()=>{Hn(),jn(),Md(),Al(),bS(),xS(),kS(),FS(),zS(),GS(),QS(),pC(),yT(),BA(),cv(),Ny(),lC(),YA(),tj(),aj(),uj(),mj(),vS(),hj=wn(fileURLToPath(import.meta.url)),setupForGjs=async t=>{let n=t.userExternal??[],S=[`cairo`,`gettext`,`system`,...n.filter(t=>!isRegisterSubpath(t)&&!isGjsifyShim(t))],C=createGjsExternalsPredicate(n),N=t.pluginOptions.format??`esm`,F=t.pluginOptions.exclude??[],I=await globToEntryPoints(t.input,F),H=resolveShim(`unicorn-magic`),W={...getAliasesForGjs({external:C}),"unicorn-magic":H,...t.pluginOptions.aliases,...t.userAliases},q=t.pluginOptions.consoleShim===!1?null:resolveShim(`console-gjs`),Y=[];t.pluginOptions.autoGlobalsInject&&Y.push(t.pluginOptions.autoGlobalsInject);let X=wrapInputWithSideEffects(I,Y,{preserveDefaultExport:t.pluginOptions.preserveDefaultExport===!0,exitOnReportedCode:!0}),Z={input:X.input,platform:`neutral`,external:S,resolve:{mainFields:N===`esm`?[`browser`,`module`,`main`]:[`browser`,`main`,`module`],conditionNames:[`browser`]},transform:{target:`firefox140`,define:{global:`globalThis`,window:`globalThis`,"process.env.READABLE_STREAM":`"disable"`,"process.env.NODE_ENV":`"production"`},...q?{inject:{console:[q,`console`]}}:{}},output:{...t.output,format:N,sourcemap:!1,codeSplitting:!1},treeshake:!0},te=getBundleDirFromOutput(t.output),ne={"random-access-file":`random-access-file/index.js`,...flattenAliases$4(W)},re=[deepkitPlugin({reflection:t.pluginOptions.reflection})];return t.pluginOptions.dialect===`react-native`&&re.push(reactNativeSupportGatePlugin()),{options:Z,prePlugins:re,plugins:[...X.plugin?[X.plugin]:[],inputShebangStripPlugin(),...q?[consoleAssignPlugin()]:[],implicitGlobalAssignPlugin(),giOptionalPlugin(`gjs`),platformResolvePlugin({suffixes:desktopSuffixChain(desktopOsSuffix()),refusedSuffixes:US,siblingIndex:!0}),...t.pluginOptions.dialect===`react-native`?[reactNativeAliasPlugin()]:[],aliasPlugin({entries:ne}),napiNodeAddonPlugin({runtimeResolve:N===`esm`}),externalsPlugin(C,{name:`gjsify-gjs-externalize`}),blueprintPlugin(),cssAsStringPlugin({targets:{firefox:60<<16}}),nodeModulesPathRewritePlugin({bundleDir:te,runtimeResolve:N===`esm`}),...t.pluginOptions.skipProcessStub?[]:[processStubPlugin({userBanner:t.userBanner,captureBundleUrl:N===`esm`,giSystemProbes:t.giSystemProbes})],(()=>{let n=resolveShebangLine(t.shebang);return shebangPlugin({enabled:n!==null,line:n??void 0})})(),unresolvedWorkspaceImportPlugin({target:`gjs`,aliases:ne,isExternal:C,...t.pluginOptions.toolchainAnchor===void 0?{}:{toolchainAnchor:t.pluginOptions.toolchainAnchor}})]}},__name$1(flattenAliases$4,`flattenAliases`)});function gjsImportsEmptyPlugin(t={}){let n=t.emptyGirs??!0?/^(@girs\/|gi:\/\/)/:/^gi:\/\//,isVocabulary=t=>/^@girs\/[^/]+\/vocabulary$/.test(t);return{name:`gjsify-gjs-imports-empty`,resolveId:{order:`pre`,filter:{id:n},handler(t){return!n.test(t)||isVocabulary(t)?null:{id:_j}}},load(t){return t===_j?{code:`export {}; export default {};`,moduleSideEffects:!1}:null}}}var _j,vj=__esmMin(()=>{gS(),_j=`${hS}empty-gjs-import`});function readdirSafe(t){try{return readdirSync(t)}catch{return[]}}function hasNodeBinary(t){for(let n of readdirSafe(t))if(n.endsWith(`.node`)||readdirSafe(xn(t,n)).some(t=>t.endsWith(`.node`)))return!0;return!1}function isNodeAddonPackage(t,n){if(isGjsifyNativeBridge(n))return!1;if(n.gypfile===!0||n.binary!==null&&typeof n.binary==`object`||existsSync(xn(t,`binding.gyp`)))return!0;let S={...n.dependencies,...n.optionalDependencies};return bj.some(t=>t in S)||isNapiRsPackageJson(n)?!0:hasNodeBinary(xn(t,`prebuilds`))||hasNodeBinary(xn(t,`build`))}function packageNameOf(t){if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`\0`)||t.includes(`:`))return null;let n=t.split(`/`);return t.startsWith(`@`)?n.length>=2&&n[1]?`${n[0]}/${n[1]}`:null:n[0]||null}function packageRootFor(t,n){let S=wn(t);for(let t=0;t<64;t++){let t=xn(S,`package.json`);if(existsSync(t))try{let C=JSON.parse(readFileSync(t,`utf8`));if(C.name===n)return{root:S,pkg:C}}catch{}let C=wn(S);if(C===S)break;S=C}return null}function nodeNativeExternalPlugin(){let t=new Map;return{name:`gjsify-node-native-external`,resolveId:{order:`pre`,filter:{id:yj},async handler(n,S){let C=packageNameOf(n);if(C===null)return null;let N=typeof S==`string`?S:void 0,F=`${C}\0${N===void 0?``:wn(N)}`,I=t.get(F);if(I===void 0){I=!1;let S=await this.resolve(n,N,{skipSelf:!0});if(S&&!S.external&&bn(S.id)&&existsSync(S.id)){let t=packageRootFor(S.id,C);I=t!==null&&isNodeAddonPackage(t.root,t.pkg)}t.set(F,I)}return I?{id:n,external:!0}:null}}}}var yj,bj,xj=__esmMin(()=>{Md(),jn(),kS(),yj=/^[^.\\/:\s\x00][^:\s\x00]*$/,bj=[`node-gyp-build`,`node-gyp-build-optional-packages`,`bindings`,`prebuild-install`,`node-pre-gyp`,`@mapbox/node-pre-gyp`,`cmake-js`]});function assertReverseBridgeRoutes(){let t=createRequire(import.meta.url),resolves=n=>{try{return t.resolve(n),!0}catch{return!1}};for(let[t,n]of Object.entries(Tj))if(resolves(t)&&!resolves(n))throw Error(`@gjsify/rolldown-plugin-gjsify: the reverse-bridge entry route for "${t}" is dangling — "${n}" does not resolve, while "${t}" does. Without the route this build silently takes ${t}'s "node" export condition, which is why the route exists; update REVERSE_BRIDGE_ENTRY_ROUTES in app/node.ts to the entry the --app gjs build resolves.`)}function enableGjsRegistersForNode(t){let n={};for(let[S,C]of Object.entries(t))C===`@gjsify/empty`&&wj.test(S)||(n[S]=C);for(let[t,S]of Object.entries(rv))wj.test(t)&&(n[t]=S);return Object.assign(n,Tj),n}function isGjsSourceBuild(t){return!!(t.nodeGiGlobalsInject||t.registerInject)}function flattenAliases$3(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var Sj,Cj,wj,Tj,setupForNode,Ej=__esmMin(()=>{Al(),bS(),BA(),yT(),sv(),cv(),Ny(),lC(),tj(),vj(),jS(),FS(),uj(),zS(),xj(),GS(),QS(),pC(),vS(),Sj=`@gjsify/node-gi/globals`,Cj=Object.values(av),wj=/\/register(\/|$)/,Tj={"solid-js":`solid-js/dist/solid.js`},setupForNode=async t=>{let n=t.userExternal??[],S=[...X_,`@gjsify/node-gi`,`@gjsify/node-gi/gi`,Sj,...Cj,...n],external=t=>!!(S.includes(t)||t===`@gjsify/node-gi`||t.startsWith(`@gjsify/node-gi/`)),C=t.pluginOptions.format??`esm`,N=t.pluginOptions.exclude??[],F=await globToEntryPoints(t.input,N),I=[];t.pluginOptions.nodeGiGlobalsInject&&I.push(Sj);let H=t.pluginOptions.autoGlobalsInject;H&&I.push(H);let W=wrapInputWithSideEffects(F,I),q=W.input,Y=isGjsSourceBuild({...t.pluginOptions,registerInject:H});Y&&assertReverseBridgeRoutes();let X=getAliasesForNode({external}),Z=flattenAliases$3({...Y?enableGjsRegistersForNode(X):X,...t.pluginOptions.aliases,...t.userAliases}),te=getBundleDirFromOutput(t.output),ne={input:q,platform:`node`,external:S,resolve:{mainFields:C===`esm`?[`module`,`main`,`browser`]:[`main`,`module`,`browser`],conditionNames:C===`esm`?[`node`]:[`require`]},transform:{target:`node24`,define:{global:`globalThis`}},output:{...t.output,format:C,sourcemap:!1,banner:void 0,codeSplitting:!1},treeshake:!0},re=[deepkitPlugin({reflection:t.pluginOptions.reflection})];return t.pluginOptions.dialect===`react-native`&&re.push(reactNativeSupportGatePlugin()),{options:ne,prePlugins:re,plugins:[...W.plugin?[W.plugin]:[],giOptionalPlugin(`node`),gjsGiNodePlugin(),gjsBuiltinModulesNodePlugin(av),implicitGlobalAssignPlugin(),gjsImportsEmptyPlugin({emptyGirs:!Y}),platformResolvePlugin({suffixes:desktopSuffixChain(desktopOsSuffix()),refusedSuffixes:US,siblingIndex:!0}),...t.pluginOptions.dialect===`react-native`?[reactNativeAliasPlugin()]:[],nodeNativeExternalPlugin(),aliasPlugin({entries:Z}),blueprintPlugin(),cssAsStringPlugin(t.pluginOptions.nodeGiGlobalsInject?{targets:{firefox:60<<16}}:{}),nodeModulesPathRewritePlugin({bundleDir:te}),unresolvedWorkspaceImportPlugin({target:`node`,aliases:Z,isExternal:external})]}},__name$1(flattenAliases$3,`flattenAliases`)});function importLine(t,n){let S=t.specifiers?.[n];return S===void 0?`import { ${n} as namespace } from ${JSON.stringify(t.renderer)};\n`:`import * as namespace from ${JSON.stringify(S)};\n`}function giRendererShimSource(t,n,S){return importLine(t,n)+`const RENDERER = ${JSON.stringify(t.renderer)};\nconst APP = ${JSON.stringify(t.app)};\nconst NS = ${JSON.stringify(n)};\nconst VERSION = ${JSON.stringify(S)};\nexport default new Proxy(namespace, {\n get(target, property, receiver) {\n if (typeof property === 'symbol' || property === 'then' || property in target) {\n return Reflect.get(target, property, receiver);\n }\n throw new Error(\n 'the ' + NS + ' arm (version ' + VERSION + ') on --app ' + APP + ': ' + RENDERER +\n ' has no ' + String(property) + '. A renderer implements a fraction of the GIR ' +\n 'vocabulary, and every absent member is a declared remainder (ADR 0034 clause 3) ' +\n 'rather than an oversight — refused by name here because reading it would be ' +\n 'undefined and \`class X extends undefined\` throws far from the import that asked ' +\n 'for it. It has: ' + Object.keys(target).sort().join(', ') + '.'\n );\n },\n});\n`}function giRendererPlugin(t){let n=Object.keys(t.namespaces).sort().map(n=>`${n} (version ${t.namespaces[n]})`).join(`, `);return{name:`gjsify-gi-renderer`,resolveId:{order:`pre`,filter:{id:/^gi:\/\//},handler(S){let C=parseGiSpecifier$1(S);if(C===null)return null;let N=t.namespaces[C.namespace];if(N===void 0)throw Error(`gjsify build --app ${t.app}: \`${S}\` has no widget renderer. --gi-renderer answers ${n} out of ${t.renderer} and nothing else — there is no GObject introspection on this target, so a namespace with no renderer counterpart cannot be substituted for. Drop --gi-renderer to keep the previous behaviour (every \`gi://\` import becomes an empty module), or gate the import to a target that has GI (\`--app gjs\`, \`--app node\`).`);if(C.version!==void 0&&C.version!==N)throw Error(`gjsify build --app ${t.app}: \`${S}\` asks for ${C.namespace} version ${C.version}; this arm answers version ${N} — the version ${t.renderer}'s vocabulary is held against. GJS throws on a version it has no typelib for, so accepting it here would make this target the only place a wrong version passes.`);return{id:`${Dj}${C.namespace}`}}},load(n){if(!n.startsWith(Dj))return null;let S=n.slice(Dj.length),C=t.namespaces[S];return C===void 0?null:{code:giRendererShimSource(t,S,C),moduleSideEffects:!1}}}}var Dj,Oj=__esmMin(()=>{gS(),jS(),Dj=`${hS}gi-renderer:`});function blueprintTemplateExit(t,n){return n===void 0?{refusal:`On --app ${t} it is the projected tree of the renderer --gi-renderer composes, and that flag is off. Pass --gi-renderer, or import the file without \`?template\`.`}:{renderer:n.renderer.replace(/^@gjsify\//,``)}}var kj=__esmMin(()=>{});function flattenAliases$2(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var setupForBrowser,Aj=__esmMin(()=>{bS(),yT(),BA(),sv(),Ny(),vj(),GS(),Oj(),kj(),tj(),zS(),uj(),setupForBrowser=async t=>{let n=[...t.userExternal??[]],S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=t.pluginOptions.giRenderer?q_.browser:void 0,F={};for(let[t,n]of Object.entries(tv))F[t]=n,F[`node:${t}`]=n;let I={},H={...getDerivedAliasesSync(`browser`),...F,...I,...t.pluginOptions.aliases,...t.userAliases},W={input:C,platform:`browser`,external:n,resolve:{mainFields:[`browser`,`module`,`main`],conditionNames:[`import`,`browser`]},transform:{target:`esnext`,define:{global:`globalThis`,window:`globalThis`,"process.env.NODE_ENV":`"production"`}},output:{...t.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},q=flattenAliases$2(H);return{options:W,prePlugins:[deepkitPlugin({reflection:t.pluginOptions.reflection})],plugins:[platformResolvePlugin({suffixes:browserSuffixChain(),refusedSuffixes:WS,siblingIndex:!0}),...N?[giRendererPlugin({app:`browser`,...N})]:[],gjsImportsEmptyPlugin({emptyGirs:!N}),aliasPlugin({entries:q}),blueprintPlugin({template:blueprintTemplateExit(`browser`,N)}),implicitGlobalAssignPlugin(),cssAsStringPlugin(),unresolvedWorkspaceImportPlugin({target:`browser`,aliases:q,isExternal:t=>n.includes(t)})]}},__name$1(flattenAliases$2,`flattenAliases`)});function flattenAliases$1(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var jj,Mj,nativescriptCoreExternalPlugin,setupForNativescript,Nj=__esmMin(()=>{bS(),BA(),yT(),sv(),Ny(),vj(),Oj(),kj(),GS(),zS(),uj(),jj=/^@nativescript\/core(?:\/|$)/,Mj=`gjsify-nativescript-core-external`,nativescriptCoreExternalPlugin=()=>({name:Mj,resolveId:t=>jj.test(t)?{id:t,external:!0}:null}),setupForNativescript=async t=>{let n=t.userExternal??[],isExternal=t=>n.some(n=>n===t)||jj.test(t),S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=t.pluginOptions.giRenderer?q_.nativescript:void 0,F=detectNativescriptPlatform(),I={};for(let[t,n]of Object.entries(nv))I[t]=n,I[`node:${t}`]=n;let H={},W={...getDerivedAliasesSync(`nativescript`),...I,...H,...t.pluginOptions.aliases,...t.userAliases},q={input:C,platform:`browser`,external:n,resolve:{mainFields:[`nativescript`,`module`,`main`],conditionNames:[`import`,`nativescript`]},transform:{target:`esnext`,define:{global:`globalThis`,...nativescriptPlatformDefines(F,{dev:!1})}},output:{...t.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},Y=flattenAliases$1(W);return{options:q,prePlugins:[deepkitPlugin({reflection:t.pluginOptions.reflection})],plugins:[nativescriptCoreExternalPlugin(),...N?[giRendererPlugin({app:`nativescript`,...N})]:[],gjsImportsEmptyPlugin({emptyGirs:!N}),platformResolvePlugin({suffixes:nativescriptSuffixChain(F)}),aliasPlugin({entries:Y}),blueprintPlugin({template:blueprintTemplateExit(`nativescript`,N)}),implicitGlobalAssignPlugin(),unresolvedWorkspaceImportPlugin({target:`nativescript`,aliases:Y,isExternal})]}},__name$1(flattenAliases$1,`flattenAliases`)}),Pj=__esmMin(()=>{gj(),Ej(),Aj(),Nj()});function isExternalSpecifier(t){return!(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.startsWith(`\0`)||t.startsWith(`data:`))}function computeCommonRoot(t){let n=t===void 0?[]:typeof t==`string`?[t]:Array.isArray(t)?t:Object.values(t);if(n.length===0)return`src`;let S=n.map(t=>t.split(`/`).filter(Boolean)),C=S[0],N=0;for(;N<C.length;N++){let t=C[N];if(!S.every(n=>n[N]===t))break}if(N===0)return`src`;let F=C.slice(0,N);return S.some(t=>t.length>N)?F.join(`/`):F.slice(0,-1).join(`/`)||`src`}function flattenAliases(t){let n={};for(let[S,C]of Object.entries(t))C&&(n[S]=C);return n}var setupLib,Fj=__esmMin(()=>{BA(),bS(),tj(),xS(),Ny(),setupLib=async t=>{let n=t.pluginOptions.format??t.pluginOptions.library??`esm`,S=t.pluginOptions.exclude??[],C=await globToEntryPoints(t.input,S),N=computeCommonRoot(C),F={...t.pluginOptions.aliases,...t.userAliases};return{options:{input:C,platform:`neutral`,resolve:{mainFields:n===`esm`?[`module`,`main`]:[`main`],conditionNames:n===`esm`?[`module`,`import`]:[`require`]},transform:{target:`esnext`},output:{...t.output,format:n,preserveModules:!0,preserveModulesRoot:N,sourcemap:!1},treeshake:!1},prePlugins:[],plugins:[aliasPlugin({entries:flattenAliases(F)}),externalsPlugin(isExternalSpecifier,{name:`gjsify-lib-externalize`}),cssAsStringPlugin(),blueprintPlugin()]}}}),Ij=__esmMin(()=>{Fj()});function mimeForExtension(t){return Lj[t.toLowerCase()]??`application/octet-stream`}function textLoaderPlugin(t={}){let n=t.loaders??{},S=Object.entries(n),C=S.filter(([,t])=>t===`text`).map(([t])=>t),N=S.filter(([,t])=>t===`dataurl`).map(([t])=>t),F=[...C,...N];if(F.length===0)return null;let I=F.map(t=>t.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),H=RegExp(`\\.(?:${I.join(`|`)})$`),W=new Map(S.map(([t,n])=>[t.toLowerCase(),n]));return{name:`gjsify-asset-loader`,async load(t){if(!H.test(t))return null;let n=t.lastIndexOf(`.`),S=n>=0?t.slice(n).toLowerCase():``;if((W.get(S)??`text`)===`dataurl`){let n=await readFile$1(t),C=mimeForExtension(S),N=n.toString(`base64`);return{code:`export default ${JSON.stringify(`data:${C};base64,${N}`)};`,moduleType:`js`}}let C=await readFile$1(t,`utf8`);return{code:`export default ${JSON.stringify(C)};`,moduleType:`js`}}}}var Lj,Rj=__esmMin(()=>{hd(),Lj={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".avif":`image/avif`,".bmp":`image/bmp`,".tiff":`image/tiff`,".tif":`image/tiff`,".wasm":`application/wasm`}}),zj=__esmMin(()=>{Md(),jn()}),gjsifyPlugin,Bj=__esmMin(()=>{Pj(),Ij(),gjsifyPlugin=async(t,n={})=>{if(n.library)switch(n.library){case`esm`:case`cjs`:return await setupLib({input:t.input,output:t.output,userAliases:t.userAliases,pluginOptions:n});default:throw TypeError(`Unknown library type: `+n.library)}let S=n.app??`gjs`;switch(S){case`gjs`:return await setupForGjs({input:t.input,output:t.output,userExternal:t.userExternal,userBanner:t.userBanner,userAliases:t.userAliases,shebang:t.shebang,giSystemProbes:t.giSystemProbes,pluginOptions:n});case`node`:return await setupForNode({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});case`browser`:return await setupForBrowser({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});case`nativescript`:return await setupForNativescript({input:t.input,output:t.output,userExternal:t.userExternal,userAliases:t.userAliases,pluginOptions:n});default:throw TypeError(`Unknown app platform: `+S)}}}),Vj=__esmMin(()=>{V_(),yS(),Pj(),Ij(),lC(),YA(),qA(),FS(),aj(),uj(),tj(),Rj(),mj(),bS(),vj(),Oj(),xS(),zS(),kS(),xj(),GS(),zj(),QS(),pC(),fC(),Bj(),Bj(),sv()});function normalizeWindowsPath(t=``){return t&&t.replace(/\\/g,`/`).replace(Hj,t=>t.toUpperCase())}function cwd(){return typeof process<`u`&&typeof process.cwd==`function`?process.cwd().replace(/\\/g,`/`):`/`}function normalizeString(t,n){let S=``,C=0,N=-1,F=0,I=null;for(let H=0;H<=t.length;++H){if(H<t.length)I=t[H];else if(I===`/`)break;else I=`/`;if(I===`/`){if(!(N===H-1||F===1))if(F===2){if(S.length<2||C!==2||S[S.length-1]!==`.`||S[S.length-2]!==`.`){if(S.length>2){let t=S.lastIndexOf(`/`);t===-1?(S=``,C=0):(S=S.slice(0,t),C=S.length-1-S.lastIndexOf(`/`)),N=H,F=0;continue}else if(S.length>0){S=``,C=0,N=H,F=0;continue}}n&&(S+=S.length>0?`/..`:`..`,C=2)}else S.length>0?S+=`/${t.slice(N+1,H)}`:S=t.slice(N+1,H),C=H-N-1;N=H,F=0}else I===`.`&&F!==-1?++F:F=-1}return S}var Hj,Uj,Wj,Gj,normalize,Kj,resolve,isAbsolute,qj=__esmMin(()=>{Hj=/^[A-Za-z]:\//,Uj=/^[/\\]{2}/,Wj=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,Gj=/^[A-Za-z]:$/,normalize=function(t){if(t.length===0)return`.`;t=normalizeWindowsPath(t);let n=t.match(Uj),S=isAbsolute(t),C=t[t.length-1]===`/`;return t=normalizeString(t,!S),t.length===0?S?`/`:C?`./`:`.`:(C&&(t+=`/`),Gj.test(t)&&(t+=`/`),n?S?`//${t}`:`//./${t}`:S&&!isAbsolute(t)?`/${t}`:t)},Kj=__name$1(function(...t){let n=``;for(let S of t)if(S)if(n.length>0){let t=n[n.length-1]===`/`,C=S[0]===`/`;t&&C?n+=S.slice(1):n+=t||C?S:`/${S}`}else n+=S;return normalize(n)},`join`),resolve=function(...t){t=t.map(t=>normalizeWindowsPath(t));let n=``,S=!1;for(let C=t.length-1;C>=-1&&!S;C--){let N=C>=0?t[C]:cwd();!N||N.length===0||(n=`${N}/${n}`,S=isAbsolute(N))}return n=normalizeString(n,!S),S&&!isAbsolute(n)?`/${n}`:n.length>0?n:`.`},isAbsolute=function(t){return Wj.test(t)}}),Jj=__esmMin(()=>{qj()});function i$2(t,n={}){return{sample:n.indent===void 0&&n.preserveIndentation!==!1&&t.slice(0,n?.sampleSize||1024),whiteSpace:n.preserveWhitespace===!1?void 0:{start:Xj.exec(t)?.[0]||``,end:Zj.exec(t)?.[0]||``}}}function a$4(t,n,S){!n||typeof n!=`object`||Object.defineProperty(n,Yj,{enumerable:!1,configurable:!0,writable:!0,value:i$2(t,S)})}var Yj,Xj,Zj,Qj=__esmMin(()=>{Yj=Symbol.for(`__confbox_fmt__`),Xj=/^(\s+)/,Zj=/(\s+)$/,__name$1(i$2,`i`),__name$1(a$4,`a`)});function e$1(t,n=!1){let S=t.length,C=0,N=``,F=0,I=16,H=0,W=0,q=0,Y=0,X=0;function h(n,S){let N=0,F=0;for(;N<n||!S;){let n=t.charCodeAt(C);if(n>=48&&n<=57)F=F*16+n-48;else if(n>=65&&n<=70)F=F*16+n-65+10;else if(n>=97&&n<=102)F=F*16+n-97+10;else break;C++,N++}return N<n&&(F=-1),F}function g(t){C=t,N=``,F=0,I=16,X=0}function _(){let n=C;if(t.charCodeAt(C)===48)C++;else for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;if(C<t.length&&t.charCodeAt(C)===46)if(C++,C<t.length&&r$2(t.charCodeAt(C)))for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;else return X=3,t.substring(n,C);let S=C;if(C<t.length&&(t.charCodeAt(C)===69||t.charCodeAt(C)===101))if(C++,(C<t.length&&t.charCodeAt(C)===43||t.charCodeAt(C)===45)&&C++,C<t.length&&r$2(t.charCodeAt(C))){for(C++;C<t.length&&r$2(t.charCodeAt(C));)C++;S=C}else X=3;return t.substring(n,S)}function v(){let n=``,N=C;for(;;){if(C>=S){n+=t.substring(N,C),X=2;break}let F=t.charCodeAt(C);if(F===34){n+=t.substring(N,C),C++;break}if(F===92){if(n+=t.substring(N,C),C++,C>=S){X=2;break}switch(t.charCodeAt(C++)){case 34:n+=`"`;break;case 92:n+=`\\`;break;case 47:n+=`/`;break;case 98:n+=`\b`;break;case 102:n+=`\f`;break;case 110:n+=`
|
|
766
766
|
`;break;case 114:n+=`\r`;break;case 116:n+=` `;break;case 117:let t=h(4,!0);t>=0?n+=String.fromCharCode(t):X=4;break;default:X=5}N=C;continue}if(F>=0&&F<=31)if(n$3(F)){n+=t.substring(N,C),X=2;break}else X=6;C++}return n}function y(){if(N=``,X=0,F=C,W=H,Y=q,C>=S)return F=S,I=17;let n=t.charCodeAt(C);if(t$1(n)){do C++,N+=String.fromCharCode(n),n=t.charCodeAt(C);while(t$1(n));return I=15}if(n$3(n))return C++,N+=String.fromCharCode(n),n===13&&t.charCodeAt(C)===10&&(C++,N+=`
|
|
767
|
-
`),H++,q=C,I=14;switch(n){case 123:return C++,I=1;case 125:return C++,I=2;case 91:return C++,I=3;case 93:return C++,I=4;case 58:return C++,I=6;case 44:return C++,I=5;case 34:return C++,N=v(),I=10;case 47:let W=C-1;if(t.charCodeAt(C+1)===47){for(C+=2;C<S&&!n$3(t.charCodeAt(C));)C++;return N=t.substring(W,C),I=12}if(t.charCodeAt(C+1)===42){C+=2;let n=S-1,F=!1;for(;C<n;){let n=t.charCodeAt(C);if(n===42&&t.charCodeAt(C+1)===47){C+=2,F=!0;break}C++,n$3(n)&&(n===13&&t.charCodeAt(C)===10&&C++,H++,q=C)}return F||(C++,X=1),N=t.substring(W,C),I=13}return N+=String.fromCharCode(n),C++,I=16;case 45:if(N+=String.fromCharCode(n),C++,C===S||!r$2(t.charCodeAt(C)))return I=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return N+=_(),I=11;default:for(;C<S&&b(n);)C++,n=t.charCodeAt(C);if(F!==C){switch(N=t.substring(F,C),N){case`true`:return I=8;case`false`:return I=9;case`null`:return I=7}return I=16}return N+=String.fromCharCode(n),C++,I=16}}function b(t){if(t$1(t)||n$3(t))return!1;switch(t){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function x(){let t;do t=y();while(t>=12&&t<=15);return t}return{setPosition:g,getPosition:()=>C,scan:n?x:y,getToken:()=>I,getTokenValue:()=>N,getTokenOffset:()=>F,getTokenLength:()=>C-F,getTokenStartLine:()=>W,getTokenStartCharacter:()=>F-Y,getTokenError:()=>X}}function t$1(t){return t===32||t===9}function n$3(t){return t===10||t===13}function r$2(t){return t>=48&&t<=57}function o(t,n=[],S
|
|
767
|
+
`),H++,q=C,I=14;switch(n){case 123:return C++,I=1;case 125:return C++,I=2;case 91:return C++,I=3;case 93:return C++,I=4;case 58:return C++,I=6;case 44:return C++,I=5;case 34:return C++,N=v(),I=10;case 47:let W=C-1;if(t.charCodeAt(C+1)===47){for(C+=2;C<S&&!n$3(t.charCodeAt(C));)C++;return N=t.substring(W,C),I=12}if(t.charCodeAt(C+1)===42){C+=2;let n=S-1,F=!1;for(;C<n;){let n=t.charCodeAt(C);if(n===42&&t.charCodeAt(C+1)===47){C+=2,F=!0;break}C++,n$3(n)&&(n===13&&t.charCodeAt(C)===10&&C++,H++,q=C)}return F||(C++,X=1),N=t.substring(W,C),I=13}return N+=String.fromCharCode(n),C++,I=16;case 45:if(N+=String.fromCharCode(n),C++,C===S||!r$2(t.charCodeAt(C)))return I=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return N+=_(),I=11;default:for(;C<S&&b(n);)C++,n=t.charCodeAt(C);if(F!==C){switch(N=t.substring(F,C),N){case`true`:return I=8;case`false`:return I=9;case`null`:return I=7}return I=16}return N+=String.fromCharCode(n),C++,I=16}}function b(t){if(t$1(t)||n$3(t))return!1;switch(t){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function x(){let t;do t=y();while(t>=12&&t<=15);return t}return{setPosition:g,getPosition:()=>C,scan:n?x:y,getToken:()=>I,getTokenValue:()=>N,getTokenOffset:()=>F,getTokenLength:()=>C-F,getTokenStartLine:()=>W,getTokenStartCharacter:()=>F-Y,getTokenError:()=>X}}function t$1(t){return t===32||t===9}function n$3(t){return t===10||t===13}function r$2(t){return t>=48&&t<=57}function o(t,n=[],S=eM.DEFAULT){let C=null,N=[],F=[];function s(t){Array.isArray(N)?N.push(t):C!==null&&(N[C]=t)}return d$1(t,{onObjectBegin:()=>{let t={};s(t),F.push(N),N=t,C=null},onObjectProperty:t=>{C=t},onObjectEnd:()=>{N=F.pop()},onArrayBegin:()=>{let t=[];s(t),F.push(N),N=t,C=null},onArrayEnd:()=>{N=F.pop()},onLiteralValue:s,onError:(t,S,C)=>{n.push({error:t,offset:S,length:C})}},S),N[0]}function d$1(t,n,S=eM.DEFAULT){let C=e$1(t,!1),N=[],F=0;function c(t){return t?()=>F===0&&t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter()):()=>!0}function l(t){return t?n=>F===0&&t(n,C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter()):()=>!0}function u(t){return t?n=>F===0&&t(n,C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter(),()=>N.slice()):()=>!0}function d(t){return t?()=>{F>0?F++:t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter(),()=>N.slice())===!1&&(F=1)}:()=>!0}function f(t){return t?()=>{F>0&&F--,F===0&&t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter())}:()=>!0}let I=d(n.onObjectBegin),H=u(n.onObjectProperty),W=f(n.onObjectEnd),q=d(n.onArrayBegin),Y=f(n.onArrayEnd),X=u(n.onLiteralValue),Z=l(n.onSeparator),te=c(n.onComment),ne=l(n.onError),re=S&&S.disallowComments,ie=S&&S.allowTrailingComma;function w(){for(;;){let t=C.scan();switch(C.getTokenError()){case 4:T(14);break;case 5:T(15);break;case 3:T(13);break;case 1:re||T(11);break;case 2:T(12);break;case 6:T(16);break}switch(t){case 12:case 13:re?T(10):te();break;case 16:T(1);break;case 15:case 14:break;default:return t}}}function T(t,n=[],S=[]){if(ne(t),n.length+S.length>0){let t=C.getToken();for(;t!==17;){if(n.indexOf(t)!==-1){w();break}else if(S.indexOf(t)!==-1)break;t=w()}}}function E(t){let n=C.getTokenValue();return t?X(n):(H(n),N.push(n)),w(),!0}function D(){switch(C.getToken()){case 11:let t=C.getTokenValue(),n=Number(t);isNaN(n)&&(T(2),n=0),X(n);break;case 7:X(null);break;case 8:X(!0);break;case 9:X(!1);break;default:return!1}return w(),!0}function O(){return C.getToken()===10?(E(!1),C.getToken()===6?(Z(`:`),w(),j()||T(4,[],[2,5])):T(5,[],[2,5]),N.pop(),!0):(T(3,[],[2,5]),!1)}function k(){I(),w();let t=!1;for(;C.getToken()!==2&&C.getToken()!==17;){if(C.getToken()===5){if(t||T(4,[],[]),Z(`,`),w(),C.getToken()===2&&ie)break}else t&&T(6,[],[]);O()||T(4,[],[2,5]),t=!0}return W(),C.getToken()===2?w():T(7,[2],[]),!0}function A(){q(),w();let t=!0,n=!1;for(;C.getToken()!==4&&C.getToken()!==17;){if(C.getToken()===5){if(n||T(4,[],[]),Z(`,`),w(),C.getToken()===4&&ie)break}else n&&T(6,[],[]);t?(N.push(0),t=!1):N[N.length-1]++,j()||T(4,[],[4,5]),n=!0}return Y(),t||N.pop(),C.getToken()===4?w():T(8,[4],[]),!0}function j(){switch(C.getToken()){case 3:return A();case 1:return k();case 10:return E(!0);default:return D()}}return w(),C.getToken()===17?S.allowEmptyContent?!0:(T(4,[],[]),!1):j()?(C.getToken()!==17&&T(9,[],[]),!0):(T(4,[],[]),!1)}var $j,eM,tM,nM,rM,iM,aM=__esmMin(()=>{__name$1(e$1,`e`),__name$1(t$1,`t`),__name$1(n$3,`n`),__name$1(r$2,`r`),(function(t){t[t.lineFeed=10]=`lineFeed`,t[t.carriageReturn=13]=`carriageReturn`,t[t.space=32]=`space`,t[t._0=48]=`_0`,t[t._1=49]=`_1`,t[t._2=50]=`_2`,t[t._3=51]=`_3`,t[t._4=52]=`_4`,t[t._5=53]=`_5`,t[t._6=54]=`_6`,t[t._7=55]=`_7`,t[t._8=56]=`_8`,t[t._9=57]=`_9`,t[t.a=97]=`a`,t[t.b=98]=`b`,t[t.c=99]=`c`,t[t.d=100]=`d`,t[t.e=101]=`e`,t[t.f=102]=`f`,t[t.g=103]=`g`,t[t.h=104]=`h`,t[t.i=105]=`i`,t[t.j=106]=`j`,t[t.k=107]=`k`,t[t.l=108]=`l`,t[t.m=109]=`m`,t[t.n=110]=`n`,t[t.o=111]=`o`,t[t.p=112]=`p`,t[t.q=113]=`q`,t[t.r=114]=`r`,t[t.s=115]=`s`,t[t.t=116]=`t`,t[t.u=117]=`u`,t[t.v=118]=`v`,t[t.w=119]=`w`,t[t.x=120]=`x`,t[t.y=121]=`y`,t[t.z=122]=`z`,t[t.A=65]=`A`,t[t.B=66]=`B`,t[t.C=67]=`C`,t[t.D=68]=`D`,t[t.E=69]=`E`,t[t.F=70]=`F`,t[t.G=71]=`G`,t[t.H=72]=`H`,t[t.I=73]=`I`,t[t.J=74]=`J`,t[t.K=75]=`K`,t[t.L=76]=`L`,t[t.M=77]=`M`,t[t.N=78]=`N`,t[t.O=79]=`O`,t[t.P=80]=`P`,t[t.Q=81]=`Q`,t[t.R=82]=`R`,t[t.S=83]=`S`,t[t.T=84]=`T`,t[t.U=85]=`U`,t[t.V=86]=`V`,t[t.W=87]=`W`,t[t.X=88]=`X`,t[t.Y=89]=`Y`,t[t.Z=90]=`Z`,t[t.asterisk=42]=`asterisk`,t[t.backslash=92]=`backslash`,t[t.closeBrace=125]=`closeBrace`,t[t.closeBracket=93]=`closeBracket`,t[t.colon=58]=`colon`,t[t.comma=44]=`comma`,t[t.dot=46]=`dot`,t[t.doubleQuote=34]=`doubleQuote`,t[t.minus=45]=`minus`,t[t.openBrace=123]=`openBrace`,t[t.openBracket=91]=`openBracket`,t[t.plus=43]=`plus`,t[t.slash=47]=`slash`,t[t.formFeed=12]=`formFeed`,t[t.tab=9]=`tab`})($j||={}),Array(20).fill(0).map((t,n)=>` `.repeat(n)),Array(200).fill(0).map((t,n)=>`
|
|
768
768
|
`+` `.repeat(n)),Array(200).fill(0).map((t,n)=>`\r`+` `.repeat(n)),Array(200).fill(0).map((t,n)=>`\r
|
|
769
769
|
`+` `.repeat(n)),Array(200).fill(0).map((t,n)=>`
|
|
770
770
|
`+` `.repeat(n)),Array(200).fill(0).map((t,n)=>`\r`+` `.repeat(n)),Array(200).fill(0).map((t,n)=>`\r
|
|
771
|
-
`+` `.repeat(n)),(function(t){t.DEFAULT={allowTrailingComma:!1}})(
|
|
772
|
-
`)){let t=/^(\w+):\s+(\d+)(\s+kB)?/.exec(S);t&&n.set(t[1],parseInt(t[2])*(t[3]?1024:1))}return n.size===0?null:{virtual:n.get(`VmSize`)??0,resident:n.get(`VmRSS`)??0,data:n.get(`VmData`)??0,peak:n.get(`VmPeak`)??0}}var lM=__esmMin(()=>{ut(),__name$1(readProcessMemory$2,`readProcessMemory`)});function readProcessMemory$1(){return null}var uM=__esmMin(()=>{__name$1(readProcessMemory$1,`readProcessMemory`)});function detectHeapPlatform(){return dM===null&&(dM=lt.get_current_dir().startsWith(`/`)?lt.file_test(`/proc/self/status`,lt.FileTest.EXISTS)?`linux`:lt.file_test(`/System/Library/CoreServices/SystemVersion.plist`,lt.FileTest.EXISTS)?`darwin`:`unknown`:`win32`),dM}function readProcessMemory(){switch(detectHeapPlatform()){case`linux`:return readProcessMemory$2();case`darwin`:return readProcessMemory$3();case`win32`:return readProcessMemory$1();default:return null}}function getHeapStatistics(){let t=readProcessMemory()??fM;return{total_heap_size:t.virtual,total_heap_size_executable:0,total_physical_size:t.resident,total_available_size:0,used_heap_size:t.resident,heap_size_limit:0,malloced_memory:t.data,peak_malloced_memory:t.peak,does_zap_garbage:0,number_of_native_contexts:0,number_of_detached_contexts:0,total_global_handles_size:0,used_global_handles_size:0,external_memory:0}}var dM,fM,pM=__esmMin(()=>{cM(),lM(),uM(),ut(),dM=null,fM={virtual:0,resident:0,data:0,peak:0}});function writeVarint(t,n){for(n>>>=0;n>=128;)t.push(n&127|128),n>>>=7;t.push(n)}function readVarint(t,n){let S=0,C=0,N;do{if(n>=t.length)throw Error(`Unexpected end of buffer reading varint`);N=t[n++],S|=(N&127)<<C,C+=7}while(N&128);return[S>>>0,n]}function zigZagEncode(t){return t>=0?t*2:-t*2-1}function zigZagDecode(t){return t&1?-(t>>>1)-1:t>>>1}function writeFloat64(t,n){let S=new DataView(new ArrayBuffer(8));S.setFloat64(0,n,!0);for(let n=0;n<8;n++)t.push(S.getUint8(n))}function readFloat64(t,n){if(n+8>t.length)throw Error(`ReadDouble() failed`);return[new DataView(t.buffer,t.byteOffset+n,8).getFloat64(0,!0),n+8]}function isOneByte(t){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>255)return!1;return!0}function typedArrayToIndex(t){let n=Object.prototype.toString.call(t);return n===`[object Int8Array]`?0:n===`[object Uint8Array]`?1:n===`[object Uint8ClampedArray]`?2:n===`[object Int16Array]`?3:n===`[object Uint16Array]`?4:n===`[object Int32Array]`?5:n===`[object Uint32Array]`?6:n===`[object Float32Array]`?7:n===`[object Float64Array]`?8:n===`[object DataView]`?9:n===`[object BigInt64Array]`?11:n===`[object BigUint64Array]`?12:-1}function indexToTypedArray(t){switch(t){case 0:return Int8Array;case 1:return Uint8Array;case 2:return Uint8ClampedArray;case 3:return Int16Array;case 4:return Uint16Array;case 5:return Int32Array;case 6:return Uint32Array;case 7:return Float32Array;case 8:return Float64Array;case 9:return DataView;case 10:return Xe;case 11:return BigInt64Array;case 12:return BigUint64Array}}function regExpFlagsToInt(t){let n=0;return t.global&&(n|=1),t.ignoreCase&&(n|=2),t.multiline&&(n|=4),t.sticky&&(n|=8),t.unicode&&(n|=16),t.dotAll&&(n|=32),t.hasIndices&&(n|=64),t.unicodeSets&&(n|=128),n}function intToRegExpFlags(t){let n=``;return t&1&&(n+=`g`),t&2&&(n+=`i`),t&4&&(n+=`m`),t&8&&(n+=`y`),t&16&&(n+=`u`),t&32&&(n+=`s`),t&64&&(n+=`d`),t&128&&(n+=`v`),n}var Serializer,Deserializer,DefaultSerializer,DefaultDeserializer,mM=__esmMin(()=>{ot(),Serializer=class{_bytes=[];_seen=[];_treatAbvAsHostObjects=!1;_getDataCloneError=Error;writeHeader(){this._bytes.push(255),writeVarint(this._bytes,15)}writeValue(t){if(typeof t==`object`&&t){let n=this._seen.indexOf(t);if(n!==-1){this._bytes.push(94),writeVarint(this._bytes,n);return}}if(t===void 0)this._bytes.push(95);else if(t===null)this._bytes.push(48);else if(t===!0)this._bytes.push(84);else if(t===!1)this._bytes.push(70);else if(typeof t==`number`)Number.isInteger(t)&&t>=-(2**31)&&t<=2**32-1?t>=0?(this._bytes.push(85),writeVarint(this._bytes,t)):(this._bytes.push(73),writeVarint(this._bytes,zigZagEncode(t))):(this._bytes.push(78),writeFloat64(this._bytes,t));else if(typeof t==`bigint`)this._writeBigInt(t);else if(typeof t==`string`)this._writeString(t);else if(typeof t==`object`){let n=t;if(t instanceof Date)this._seen.push(n),this._bytes.push(68),writeFloat64(this._bytes,t.getTime());else if(t instanceof RegExp)this._seen.push(n),this._bytes.push(82),this._writeString(t.source),writeVarint(this._bytes,regExpFlagsToInt(t));else if(t instanceof ArrayBuffer){this._seen.push(n);let S=new Uint8Array(t);this._bytes.push(66),writeVarint(this._bytes,S.length);for(let t=0;t<S.length;t++)this._bytes.push(S[t])}else if(this._treatAbvAsHostObjects&&(ArrayBuffer.isView(t)||Xe.isBuffer(t)))this._seen.push(n),this._bytes.push(92),this._writeHostObject(n);else if(Array.isArray(t)){this._seen.push(n);let S=t;this._bytes.push(65),writeVarint(this._bytes,S.length);for(let t=0;t<S.length;t++)this.writeValue(S[t]);this._bytes.push(36),writeVarint(this._bytes,0),writeVarint(this._bytes,S.length)}else{this._seen.push(n),this._bytes.push(111);let t=Object.keys(n);for(let S of t)this._writeString(S),this.writeValue(n[S]);this._bytes.push(123),writeVarint(this._bytes,t.length)}}else throw new this._getDataCloneError(`${String(t)} could not be cloned.`)}releaseBuffer(){let t=Xe.from(this._bytes);return this._bytes=[],this._seen=[],t}writeUint32(t){writeVarint(this._bytes,t>>>0)}writeUint64(t,n){writeVarint(this._bytes,t>>>0),writeVarint(this._bytes,n>>>0)}writeDouble(t){writeFloat64(this._bytes,t)}writeRawBytes(t){if(!ArrayBuffer.isView(t))throw TypeError(`source must be a TypedArray or a DataView`);let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);for(let t=0;t<n.length;t++)this._bytes.push(n[t])}_writeHostObject(t){throw new this._getDataCloneError(`Unserializable host object: ${Object.prototype.toString.call(t)}`)}_setTreatArrayBufferViewsAsHostObjects(t){this._treatAbvAsHostObjects=t}_writeString(t){if(isOneByte(t)){this._bytes.push(34),writeVarint(this._bytes,t.length);for(let n=0;n<t.length;n++)this._bytes.push(t.charCodeAt(n)&255)}else{let n=new TextEncoder().encode(t);this._bytes.push(99),writeVarint(this._bytes,n.length);for(let t=0;t<n.length;t++)this._bytes.push(n[t])}}_writeBigInt(t){this._bytes.push(90);let n=t<0n,S=n?-t:t,C=[],N=S;for(;N>0n;)C.push(Number(N&4294967295n)),C.push(Number(N>>32n&4294967295n)),N>>=64n;let F=C.length<<1|!!n;writeVarint(this._bytes,F);for(let t of C)this._bytes.push(t&255),this._bytes.push(t>>8&255),this._bytes.push(t>>16&255),this._bytes.push(t>>24&255);C.length}},Deserializer=class{_pos=0;_wireVersion=0;_seen=[];buffer;constructor(t){if(!ArrayBuffer.isView(t)&&!(t instanceof ArrayBuffer))throw TypeError(`buffer must be a TypedArray or a DataView`);t instanceof ArrayBuffer?this.buffer=Xe.from(t):this.buffer=Xe.from(t.buffer,t.byteOffset,t.byteLength)}readHeader(){if(this.buffer[this._pos]!==255)throw Error(`ReadHeader() failed`);this._pos++;let[t,n]=readVarint(this.buffer,this._pos);return this._wireVersion=t,this._pos=n,!0}getWireFormatVersion(){return this._wireVersion}readValue(){if(this._pos>=this.buffer.length)throw Error(`Unexpected end of buffer`);let t=this.buffer[this._pos++];switch(t){case 95:return;case 48:return null;case 84:return!0;case 70:return!1;case 73:{let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,zigZagDecode(t)}case 85:{let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,t>>>0}case 78:{let[t,n]=readFloat64(this.buffer,this._pos);return this._pos=n,t}case 90:return this._readBigInt();case 34:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=``;for(let n=0;n<t;n++)S+=String.fromCharCode(this.buffer[this._pos++]);return S}case 99:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=this.buffer.slice(this._pos,this._pos+t);return this._pos+=t,new TextDecoder().decode(S)}case 68:{let[t,n]=readFloat64(this.buffer,this._pos);this._pos=n;let S=new Date(t);return this._seen.push(S),S}case 82:{let t=this.readValue(),[n,S]=readVarint(this.buffer,this._pos);this._pos=S;let C=intToRegExpFlags(n),N=new RegExp(t,C);return this._seen.push(N),N}case 66:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=new ArrayBuffer(t),C=new Uint8Array(S);for(let n=0;n<t;n++)C[n]=this.buffer[this._pos++];return this._seen.push(S),S}case 94:{let[t,n]=readVarint(this.buffer,this._pos);if(this._pos=n,t>=this._seen.length)throw Error(`Invalid object reference`);return this._seen[t]}case 65:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=Array.from({length:t});this._seen.push(S);for(let n=0;n<t;n++)S[n]=this.readValue();if(this.buffer[this._pos]!==36)throw Error(`Expected kEndDenseArray`);this._pos++;let[,C]=readVarint(this.buffer,this._pos);this._pos=C;let[,N]=readVarint(this.buffer,this._pos);return this._pos=N,S}case 111:{let t={};for(this._seen.push(t);this.buffer[this._pos]!==123;){let n=this.readValue();t[n]=this.readValue()}this._pos++;let[,n]=readVarint(this.buffer,this._pos);return this._pos=n,t}case 92:{let t=this._readHostObject();return t!=null&&this._seen.push(t),t}default:throw Error(`Unknown tag 0x${t.toString(16).padStart(2,`0`)} at position ${this._pos-1}`)}}readUint32(){let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,t>>>0}readUint64(){let[t,n]=readVarint(this.buffer,this._pos),[S,C]=readVarint(this.buffer,n);return this._pos=C,[t>>>0,S>>>0]}readDouble(){let[t,n]=readFloat64(this.buffer,this._pos);return this._pos=n,t}_readRawBytes(t){let n=this._pos;if(this._pos+=t,this._pos>this.buffer.length)throw Error(`Unexpected end of buffer reading raw bytes`);return n}readRawBytes(t){let n=this._readRawBytes(t);return Xe.from(this.buffer.buffer,this.buffer.byteOffset+n,t)}_readHostObject(){throw Error(`No host object deserializer installed`)}_readBigInt(){let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=(t&1)==1,C=t>>1,N=0n;for(let t=0;t<C;t++){let n=this.buffer[this._pos]|this.buffer[this._pos+1]<<8|this.buffer[this._pos+2]<<16|this.buffer[this._pos+3]<<24;this._pos+=4,N|=BigInt(n>>>0)<<BigInt(t*32)}return S?-N:N}},DefaultSerializer=class extends Serializer{constructor(){super(),this._setTreatArrayBufferViewsAsHostObjects(!0)}_writeHostObject(t){let n;if(Xe.isBuffer(t))n=10;else if(n=typedArrayToIndex(t),n===-1)throw new this._getDataCloneError(`Unserializable host object: ${Object.prototype.toString.call(t)}`);this.writeUint32(n),this.writeUint32(t.byteLength),this.writeRawBytes(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}},DefaultDeserializer=class extends Deserializer{_readHostObject(){let t=this.readUint32(),n=this.readUint32(),S=this._readRawBytes(n);if(t===10){let t=Xe.allocUnsafe(n);return this.buffer.copy(t,0,this.buffer.byteOffset+S,this.buffer.byteOffset+S+n),t}let C=indexToTypedArray(t);if(!C)throw Error(`Unknown TypedArray type index ${t}`);let N=C.BYTES_PER_ELEMENT??1,F=n/N,I=this.buffer.byteOffset+S;if(I%N===0)return new C(this.buffer.buffer,I,F);let H=Xe.allocUnsafe(n);return this.buffer.copy(H,0,this.buffer.byteOffset+S,this.buffer.byteOffset+S+n),new C(H.buffer,H.byteOffset,F)}}});function serialize(t){let n=new DefaultSerializer;return n.writeHeader(),n.writeValue(t),n.releaseBuffer()}function deserialize(t){let n=new DefaultDeserializer(t);return n.readHeader(),n.readValue()}function getHeapSpaceStatistics(){return[]}function getHeapCodeStatistics(){return{code_and_metadata_size:0,bytecode_and_metadata_size:0,external_script_source_size:0,cpu_profiler_metadata_size:0}}function setFlagsFromString(t){}function getHeapSnapshot(t){return null}function writeHeapSnapshot(t){return``}function isStringOneByteRepresentation(t){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>255)return!1;return!0}function startCpuProfile(){return new SyncCPUProfileHandle}var GCProfiler,SyncCPUProfileHandle,hM,gM=__esmMin(()=>{pM(),mM(),GCProfiler=class{#e=!1;#t=0;start(){this.#e||(this.#e=!0,this.#t=Date.now())}stop(){if(this.#e){this.#e=!1;try{let t=globalThis.imports?.system;typeof t?.gc==`function`&&t.gc()}catch{}return{version:1,startTime:this.#t,endTime:Date.now(),stats:[]}}}[Symbol.dispose](){this.stop()}},SyncCPUProfileHandle=class{stop(){}[Symbol.dispose](){this.stop()}},hM={getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,getHeapSnapshot,writeHeapSnapshot,serialize,deserialize,isStringOneByteRepresentation,Serializer,Deserializer,DefaultSerializer,DefaultDeserializer,GCProfiler,startCpuProfile}});function formatList(t,n=`and`){return t.length<3?t.join(` ${n} `):`${t.slice(0,-1).join(`, `)}, ${n} ${t.at(-1)}`}function createError(t,n,S){return xM.set(t,n),makeNodeErrorWithCode(S,t)}function makeNodeErrorWithCode(t,n){return function NodeError(...S){let C=Error.stackTraceLimit;isErrorStackTraceLimitWritable()&&(Error.stackTraceLimit=0);let N=new t;isErrorStackTraceLimitWritable()&&(Error.stackTraceLimit=C);let F=getMessage(n,S,N);return Object.defineProperties(N,{message:{value:F,enumerable:!1,writable:!0,configurable:!0},toString:{value(){return`${this.name} [${n}]: ${this.message}`},enumerable:!1,writable:!0,configurable:!0}}),wM(N),N.code=n,N}}function isErrorStackTraceLimitWritable(){try{if(hM.startupSnapshot.isBuildingSnapshot())return!1}catch{}let t=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return t===void 0?Object.isExtensible(Error):vM.call(t,`writable`)&&t.writable!==void 0?t.writable:t.set!==void 0}function hideStackFrames(t){let n=SM+t.name;return Object.defineProperty(t,"name",{value:n}),t}function getMessage(t,n,S){let C=xM.get(t);if(qd.ok(C!==void 0,"expected `message` to be found"),typeof C==`function`)return qd.ok(C.length<=n.length,`Code: ${t}; The provided arguments length (${n.length}) does not match the required ones (${C.length}).`),Reflect.apply(C,S,n);let N=/%[dfijoOs]/g,F=0;for(;N.exec(C)!==null;)F++;return qd.ok(F===n.length,`Code: ${t}; The provided arguments length (${n.length}) does not match the required ones (${F}).`),n.length===0?C:(n.unshift(C),Reflect.apply(format,null,n))}function determineSpecificType(t){if(t==null)return String(t);if(typeof t==`function`&&t.name)return`function ${t.name}`;if(typeof t==`object`)return t.constructor&&t.constructor.name?`an instance of ${t.constructor.name}`:`${inspect(t,{depth:-1})}`;let n=inspect(t,{colors:!1});return n.length>28&&(n=`${n.slice(0,25)}...`),`type ${typeof t} (${n})`}function read(t,{base:n,specifier:S}){let C=FM.get(t);if(C)return C;let N;try{N=jd.readFileSync(An.toNamespacedPath(t),`utf8`)}catch(t){let n=t;if(n.code!==`ENOENT`)throw n}let F={exists:!1,pjsonPath:t,main:void 0,name:void 0,type:`none`,exports:void 0,imports:void 0};if(N!==void 0){let C;try{C=JSON.parse(N)}catch(C){let N=new EM(t,(n?`"${S}" from `:``)+fileURLToPath(n||S),C.message);throw N.cause=C,N}F.exists=!0,PM.call(C,`name`)&&typeof C.name==`string`&&(F.name=C.name),PM.call(C,`main`)&&typeof C.main==`string`&&(F.main=C.main),PM.call(C,`exports`)&&(F.exports=C.exports),PM.call(C,`imports`)&&(F.imports=C.imports),PM.call(C,`type`)&&(C.type===`commonjs`||C.type===`module`)&&(F.type=C.type)}return FM.set(t,F),F}function getPackageScopeConfig(t){let n=new URL(`package.json`,t);for(;!n.pathname.endsWith(`node_modules/package.json`);){let S=read(fileURLToPath(n),{specifier:t});if(S.exists)return S;let C=n;if(n=new URL(`../package.json`,n),n.pathname===C.pathname)break}return{pjsonPath:fileURLToPath(n),exists:!1,type:`none`}}function mimeToFormat(t){return t&&/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(t)?`module`:t===`application/json`?`json`:null}function getDataProtocolModuleFormat(t){let{1:n}=/^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(t.pathname)||[null,null,null];return mimeToFormat(n)}function extname(t){let n=t.pathname,S=n.length;for(;S--;){let t=n.codePointAt(S);if(t===47)return``;if(t===46)return n.codePointAt(S-1)===47?``:n.slice(S)}return``}function getFileProtocolModuleFormat(t,n,S){let C=extname(t);if(C===`.js`){let{type:n}=getPackageScopeConfig(t);return n===`none`?`commonjs`:n}if(C===``){let{type:n}=getPackageScopeConfig(t);return n===`none`||n===`commonjs`?`commonjs`:`module`}let N=LM[C];if(N)return N;if(!S)throw new NM(C,fileURLToPath(t))}function defaultGetFormatWithoutErrors(t,n){let S=t.protocol;return IM.call(RM,S)&&RM[S](t,n,!0)||null}function emitInvalidSegmentDeprecation(t,n,S,C,N,F,I){if(en.noDeprecation)return;let H=fileURLToPath(C),W=qM.exec(I?t:n)!==null;en.emitWarning(`Use of deprecated ${W?`double slash`:`leading or trailing slash matching`} resolving "${t}" for module request "${n}" ${n===S?``:`matched to "${S}" `}in the "${N?`imports`:`exports`}" field module resolution of the package at ${H}${F?` imported from ${fileURLToPath(F)}`:``}.`,`DeprecationWarning`,`DEP0166`)}function emitLegacyIndexDeprecation(t,n,S,C){if(en.noDeprecation||defaultGetFormatWithoutErrors(t,{parentURL:S.href})!==`module`)return;let N=fileURLToPath(t.href),F=fileURLToPath(new Bn(`.`,n)),I=fileURLToPath(S);C?An.resolve(F,C)!==N&&en.emitWarning(`Package ${F} has a "main" field set to "${C}", excluding the full filename and extension to the resolved file at "${N.slice(F.length)}", imported from ${I}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`):en.emitWarning(`No "main" or "exports" field defined in the package.json for ${F} resolving the main entry point "${N.slice(F.length)}", imported from ${I}.\nDefault "index" lookups for the main are deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`)}function tryStatSync(t){try{return statSync(t)}catch{}}function fileExists$1(t){let n=statSync(t,{throwIfNoEntry:!1});return(n?n.isFile():void 0)??!1}function legacyMainResolve(t,n,S){let C;if(n.main!==void 0){if(C=new Bn(n.main,t),fileExists$1(C))return C;let N=[`./${n.main}.js`,`./${n.main}.json`,`./${n.main}.node`,`./${n.main}/index.js`,`./${n.main}/index.json`,`./${n.main}/index.node`],F=-1;for(;++F<N.length&&(C=new Bn(N[F],t),!fileExists$1(C));)C=void 0;if(C)return emitLegacyIndexDeprecation(C,t,S,n.main),C}let N=[`./index.js`,`./index.json`,`./index.node`],F=-1;for(;++F<N.length&&(C=new Bn(N[F],t),!fileExists$1(C));)C=void 0;if(C)return emitLegacyIndexDeprecation(C,t,S,n.main),C;throw new OM(fileURLToPath(new Bn(`.`,t)),fileURLToPath(S))}function finalizeResolution(t,n,S){if(GM.exec(t.pathname)!==null)throw new TM(t.pathname,String.raw`must not include encoded "/" or "\" characters`,fileURLToPath(n));let C;try{C=fileURLToPath(t)}catch(S){throw Object.defineProperty(S,"input",{value:String(t)}),Object.defineProperty(S,"module",{value:String(n)}),S}let N=tryStatSync(C.endsWith(`/`)?C.slice(-1):C);if(N&&N.isDirectory()){let S=new jM(C,fileURLToPath(n));throw S.url=String(t),S}if(!N||!N.isFile()){let S=new OM(C||t.pathname,n&&fileURLToPath(n),!0);throw S.url=String(t),S}if(!S){let n=realpathSync(C),{search:S,hash:N}=t;t=pathToFileURL(n+(C.endsWith(An.sep)?`/`:``)),t.search=S,t.hash=N}return t}function importNotDefined(t,n,S){return new kM(t,n&&fileURLToPath(new Bn(`.`,n)),fileURLToPath(S))}function exportsNotFound(t,n,S){return new AM(fileURLToPath(new Bn(`.`,n)),t,S&&fileURLToPath(S))}function throwInvalidSubpath(t,n,S,C,N){throw new TM(t,`request is not a valid match in pattern "${n}" for the "${C?`imports`:`exports`}" resolution of ${fileURLToPath(S)}`,N&&fileURLToPath(N))}function invalidPackageTarget(t,n,S,C,N){return n=typeof n==`object`&&n?JSON.stringify(n,null,``):`${n}`,new DM(fileURLToPath(new Bn(`.`,S)),t,n,C,N&&fileURLToPath(N))}function resolvePackageTargetString(t,n,S,C,N,F,I,H,W){if(n!==``&&!F&&t.at(-1)!==`/`)throw invalidPackageTarget(S,t,C,I,N);if(!t.startsWith(`./`)){if(I&&!t.startsWith(`../`)&&!t.startsWith(`/`)){let S=!1;try{new Bn(t),S=!0}catch{}if(!S)return packageResolve(F?zM.call(WM,t,()=>n):t+n,C,W)}throw invalidPackageTarget(S,t,C,I,N)}if(VM.exec(t.slice(2))!==null)if(HM.exec(t.slice(2))===null){if(!H){let H=F?S.replace(`*`,()=>n):S+n;emitInvalidSegmentDeprecation(F?zM.call(WM,t,()=>n):t,H,S,C,I,N,!0)}}else throw invalidPackageTarget(S,t,C,I,N);let q=new Bn(t,C),Y=q.pathname,X=new Bn(`.`,C).pathname;if(!Y.startsWith(X))throw invalidPackageTarget(S,t,C,I,N);if(n===``)return q;if(VM.exec(n)!==null){let W=F?S.replace(`*`,()=>n):S+n;HM.exec(n)===null?H||emitInvalidSegmentDeprecation(F?zM.call(WM,t,()=>n):t,W,S,C,I,N,!1):throwInvalidSubpath(W,S,C,I,N)}return F?new Bn(zM.call(WM,q.href,()=>n)):new Bn(n,q)}function isArrayIndex(t){let n=Number(t);return`${n}`===t?n>=0&&n<4294967295:!1}function resolvePackageTarget(t,n,S,C,N,F,I,H,W){if(typeof n==`string`)return resolvePackageTargetString(n,S,C,t,N,F,I,H,W);if(Array.isArray(n)){let q=n;if(q.length===0)return null;let Y,X=-1;for(;++X<q.length;){let n=q[X],Z;try{Z=resolvePackageTarget(t,n,S,C,N,F,I,H,W)}catch(t){let n=t;if(Y=n,n.code===`ERR_INVALID_PACKAGE_TARGET`)continue;throw t}if(Z!==void 0){if(Z===null){Y=null;continue}return Z}}if(Y==null)return null;throw Y}if(typeof n==`object`&&n){let q=Object.getOwnPropertyNames(n),Y=-1;for(;++Y<q.length;){let n=q[Y];if(isArrayIndex(n))throw new EM(fileURLToPath(t),fileURLToPath(N),`"exports" cannot contain numeric property keys.`)}for(Y=-1;++Y<q.length;){let X=q[Y];if(X==="default"||W&&W.has(X)){let q=n[X],Y=resolvePackageTarget(t,q,S,C,N,F,I,H,W);if(Y===void 0)continue;return Y}}return null}if(n===null)return null;throw invalidPackageTarget(C,n,t,I,N)}function isConditionalExportsMainSugar(t,n,S){if(typeof t==`string`||Array.isArray(t))return!0;if(typeof t!=`object`||!t)return!1;let C=Object.getOwnPropertyNames(t),N=!1,F=0,I=-1;for(;++I<C.length;){let t=C[I],H=t===``||t[0]!==`.`;if(F++===0)N=H;else if(N!==H)throw new EM(fileURLToPath(n),fileURLToPath(S),`"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`)}return N}function emitTrailingSlashPatternDeprecation(t,n,S){if(en.noDeprecation)return;let C=fileURLToPath(n);KM.has(C+`|`+t)||(KM.add(C+`|`+t),en.emitWarning(`Use of deprecated trailing slash pattern mapping "${t}" in the "exports" field module resolution of the package at ${C}${S?` imported from ${fileURLToPath(S)}`:``}. Mapping specifiers ending in "/" is no longer supported.`,`DeprecationWarning`,`DEP0155`))}function packageExportsResolve(t,n,S,C,N){let F=S.exports;if(isConditionalExportsMainSugar(F,t,C)&&(F={".":F}),BM.call(F,n)&&!n.includes(`*`)&&!n.endsWith(`/`)){let S=F[n],I=resolvePackageTarget(t,S,``,n,C,!1,!1,!1,N);if(I==null)throw exportsNotFound(n,t,C);return I}let I=``,H=``,W=Object.getOwnPropertyNames(F),q=-1;for(;++q<W.length;){let S=W[q],N=S.indexOf(`*`);if(N!==-1&&n.startsWith(S.slice(0,N))){n.endsWith(`/`)&&emitTrailingSlashPatternDeprecation(n,t,C);let F=S.slice(N+1);n.length>=S.length&&n.endsWith(F)&&patternKeyCompare(I,S)===1&&S.lastIndexOf(`*`)===N&&(I=S,H=n.slice(N,n.length-F.length))}}if(I){let S=F[I],W=resolvePackageTarget(t,S,H,I,C,!0,!1,n.endsWith(`/`),N);if(W==null)throw exportsNotFound(n,t,C);return W}throw exportsNotFound(n,t,C)}function patternKeyCompare(t,n){let S=t.indexOf(`*`),C=n.indexOf(`*`),N=S===-1?t.length:S+1,F=C===-1?n.length:C+1;return N>F?-1:F>N||S===-1?1:C===-1||t.length>n.length?-1:+(n.length>t.length)}function packageImportsResolve(t,n,S){if(t===`#`||t.startsWith(`#/`)||t.endsWith(`/`))throw new TM(t,`is not a valid internal imports specifier name`,fileURLToPath(n));let C,N=getPackageScopeConfig(n);if(N.exists){C=pathToFileURL(N.pjsonPath);let F=N.imports;if(F)if(BM.call(F,t)&&!t.includes(`*`)){let N=resolvePackageTarget(C,F[t],``,t,n,!1,!0,!1,S);if(N!=null)return N}else{let N=``,I=``,H=Object.getOwnPropertyNames(F),W=-1;for(;++W<H.length;){let n=H[W],S=n.indexOf(`*`);if(S!==-1&&t.startsWith(n.slice(0,-1))){let C=n.slice(S+1);t.length>=n.length&&t.endsWith(C)&&patternKeyCompare(N,n)===1&&n.lastIndexOf(`*`)===S&&(N=n,I=t.slice(S,t.length-C.length))}}if(N){let t=F[N],H=resolvePackageTarget(C,t,I,N,n,!0,!0,!1,S);if(H!=null)return H}}}throw importNotDefined(t,C,n)}function parsePackageName(t,n){let S=t.indexOf(`/`),C=!0,N=!1;t[0]===`@`&&(N=!0,S===-1||t.length===0?C=!1:S=t.indexOf(`/`,S+1));let F=S===-1?t:t.slice(0,S);if(UM.exec(F)!==null&&(C=!1),!C)throw new TM(t,`is not a valid package name`,fileURLToPath(n));return{packageName:F,packageSubpath:`.`+(S===-1?``:t.slice(S)),isScoped:N}}function packageResolve(t,n,S){if(_M.includes(t))return new Bn(`node:`+t);let{packageName:C,packageSubpath:N,isScoped:F}=parsePackageName(t,n),I=getPackageScopeConfig(n);if(I.exists&&I.name===C&&I.exports!==void 0&&I.exports!==null)return packageExportsResolve(pathToFileURL(I.pjsonPath),N,I,n,S);let H=new Bn(`./node_modules/`+C+`/package.json`,n),W=fileURLToPath(H),q;do{let I=tryStatSync(W.slice(0,-13));if(!I||!I.isDirectory()){q=W,H=new Bn((F?`../../../../node_modules/`:`../../../node_modules/`)+C+`/package.json`,H),W=fileURLToPath(H);continue}let Y=read(W,{base:n,specifier:t});return Y.exports!==void 0&&Y.exports!==null?packageExportsResolve(H,N,Y,n,S):N===`.`?legacyMainResolve(H,Y,n):new Bn(N,H)}while(W.length!==q.length);throw new OM(C,fileURLToPath(n),!1)}function isRelativeSpecifier(t){return t[0]===`.`&&(t.length===1||t[1]===`/`||t[1]===`.`&&(t.length===2||t[2]===`/`))}function shouldBeTreatedAsRelativeOrAbsolutePath(t){return t===``?!1:t[0]===`/`?!0:isRelativeSpecifier(t)}function moduleResolve(t,n,S,C){let N=n.protocol,F=N===`data:`,I;if(shouldBeTreatedAsRelativeOrAbsolutePath(t))try{I=new Bn(t,n)}catch(S){let C=new MM(t,n);throw C.cause=S,C}else if(N===`file:`&&t[0]===`#`)I=packageImportsResolve(t,n,S);else try{I=new Bn(t)}catch(C){if(F&&!_M.includes(t)){let S=new MM(t,n);throw S.cause=C,S}I=packageResolve(t,n,S)}return qd.ok(I!==void 0,`expected to be defined`),I.protocol===`file:`?finalizeResolution(I,n,C):I}function resolveModuleURL(t,n){let S=_parseInput(t);if(`external`in S)return S.external;let C=S.specifier,N=S.url,F=S.absolutePath,I,H;if(n?.cache!==!1&&(I=_cacheKey(F||C,n),H=n?.cache&&typeof n?.cache==`object`?n.cache:XM),H){let t=H.get(I);if(typeof t==`string`)return t;if(t instanceof Error){if(n?.try)return;throw t}}if(F)try{let t=lstatSync(F);if(t.isSymbolicLink()&&(F=realpathSync(F),N=pathToFileURL(F)),t.isFile())return H&&H.set(I,N.href),N.href}catch(t){if(t?.code!==`ENOENT`)throw H&&H.set(I,t),t}let W=n?.conditions?new Set(n.conditions):JM,q=C||N.href,Y=_normalizeBases(n?.from),X=n?.suffixes||[``],Z=n?.extensions?[``,...n.extensions]:[``],te;for(let t of Y){for(let n of X){let S=_join(q,n);S===`.`&&(S+=`/.`);for(let n of Z)if(te=_tryModuleResolve(S+n,t,W),te)break;if(te)break}if(te)break}if(!te){let S=Error(`Cannot resolve module "${t}" (from: ${Y.map(t=>_fmtPath(t)).join(`, `)})`);if(S.code=`ERR_MODULE_NOT_FOUND`,H&&H.set(I,S),n?.try)return;throw S}return H&&H.set(I,te.href),te.href}function resolveModulePath(t,n){let S=resolveModuleURL(t,n);if(!S||!S.startsWith(`file://`)&&n?.try)return;let C=fileURLToPath(S);return YM?_normalizeWinPath(C):C}function _tryModuleResolve(t,n,S){try{return moduleResolve(t,n,S)}catch{}}function _normalizeBases(t){let n=(Array.isArray(t)?t:[t]).flatMap(t=>_normalizeBase(t));return n.length===0?[pathToFileURL(`./`)]:n}function _normalizeBase(t){if(!t)return[];if(_isURL(t))return[t];if(typeof t!=`string`)return[];if(/^(?:node|data|http|https|file):/.test(t))return new URL(t);try{return t.endsWith(`/`)||statSync(t).isDirectory()?pathToFileURL(t+`/`):pathToFileURL(t)}catch{return[pathToFileURL(t+`/`),pathToFileURL(t)]}}function _fmtPath(t){try{return fileURLToPath(t)}catch{return t}}function _cacheKey(t,n){return JSON.stringify([t,(n?.conditions||[`node`,`import`]).sort(),n?.extensions,n?.from,n?.suffixes])}function _join(t,n){return!t||!n||n===`/`?t:(t.endsWith(`/`)?t:t+`/`)+(n.startsWith(`/`)?n.slice(1):n)}function _normalizeWinPath(t){return t.replace(/\\/g,`/`).replace(/^[a-z]:\//,t=>t.toUpperCase())}function _isURL(t){return t instanceof URL||t?.constructor?.name===`URL`}function _parseInput(t){if(typeof t==`string`){if(t.startsWith(`file:`)){let n=new URL(t);return{url:n,absolutePath:fileURLToPath(n)}}return bn(t)?{url:pathToFileURL(t),absolutePath:t}:/^(?:node|data|http|https):/.test(t)?{external:t}:_M.includes(t)&&!t.includes(`:`)?{external:`node:${t}`}:{specifier:t}}if(_isURL(t))return t.protocol===`file:`?{url:t,absolutePath:fileURLToPath(t)}:{external:t.href};throw TypeError("id must be a `string` or `URL`")}var _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=__esmMin(()=>{Md(),Hn(),jn(),Jd(),rn(),gM(),yu(),_M=`_http_agent._http_client._http_common._http_incoming._http_outgoing._http_server._stream_duplex._stream_passthrough._stream_readable._stream_transform._stream_wrap._stream_writable._tls_common._tls_wrap.assert.assert/strict.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.dns/promises.domain.events.fs.fs/promises.http.http2.https.inspector.inspector/promises.module.net.os.path.path/posix.path/win32.perf_hooks.process.punycode.querystring.readline.readline/promises.repl.stream.stream/consumers.stream/promises.stream/web.string_decoder.sys.timers.timers/promises.tls.trace_events.tty.url.util.util/types.v8.vm.wasi.worker_threads.zlib`.split(`.`),vM={}.hasOwnProperty,yM=/^([A-Z][a-z\d]*)+$/,bM=new Set([`string`,`function`,`number`,`object`,`Function`,`Object`,`boolean`,`bigint`,`symbol`]),xM=new Map,SM=`__node_internal_`,wM=hideStackFrames(function(t){let n=isErrorStackTraceLimitWritable();return n&&(CM=Error.stackTraceLimit,Error.stackTraceLimit=1/0),Error.captureStackTrace(t),n&&(Error.stackTraceLimit=CM),t}),createError(`ERR_INVALID_ARG_TYPE`,(t,n,S)=>{qd.ok(typeof t==`string`,`'name' must be a string`),Array.isArray(n)||(n=[n]);let C=`The `;if(t.endsWith(` argument`))C+=`${t} `;else{let n=t.includes(`.`)?`property`:`argument`;C+=`"${t}" ${n} `}C+=`must be `;let N=[],F=[],I=[];for(let t of n)qd.ok(typeof t==`string`,`All expected entries have to be of type string`),bM.has(t)?N.push(t.toLowerCase()):yM.exec(t)===null?(qd.ok(t!==`object`,`The value "object" should be written as "Object"`),I.push(t)):F.push(t);if(F.length>0){let t=N.indexOf(`object`);t!==-1&&(N.slice(t,1),F.push(`Object`))}return N.length>0&&(C+=`${N.length>1?`one of type`:`of type`} ${formatList(N,`or`)}`,(F.length>0||I.length>0)&&(C+=` or `)),F.length>0&&(C+=`an instance of ${formatList(F,`or`)}`,I.length>0&&(C+=` or `)),I.length>0&&(I.length>1?C+=`one of ${formatList(I,`or`)}`:(I[0]?.toLowerCase()!==I[0]&&(C+=`an `),C+=`${I[0]}`)),C+=`. Received ${determineSpecificType(S)}`,C},TypeError),TM=createError(`ERR_INVALID_MODULE_SPECIFIER`,(t,n,S)=>`Invalid module "${t}" ${n}${S?` imported from ${S}`:``}`,TypeError),EM=createError(`ERR_INVALID_PACKAGE_CONFIG`,(t,n,S)=>`Invalid package config ${t}${n?` while importing ${n}`:``}${S?`. ${S}`:``}`,Error),DM=createError(`ERR_INVALID_PACKAGE_TARGET`,(t,n,S,C=!1,N)=>{let F=typeof S==`string`&&!C&&S.length>0&&!S.startsWith(`./`);return n===`.`?(qd.ok(C===!1),`Invalid "exports" main target ${JSON.stringify(S)} defined in the package config ${t}package.json${N?` imported from ${N}`:``}${F?`; targets must start with "./"`:``}`):`Invalid "${C?`imports`:`exports`}" target ${JSON.stringify(S)} defined for '${n}' in the package config ${t}package.json${N?` imported from ${N}`:``}${F?`; targets must start with "./"`:``}`},Error),OM=createError(`ERR_MODULE_NOT_FOUND`,(t,n,S=!1)=>`Cannot find ${S?`module`:`package`} '${t}' imported from ${n}`,Error),createError(`ERR_NETWORK_IMPORT_DISALLOWED`,`import of '%s' by %s is not supported: %s`,Error),kM=createError(`ERR_PACKAGE_IMPORT_NOT_DEFINED`,(t,n,S)=>`Package import specifier "${t}" is not defined${n?` in package ${n||``}package.json`:``} imported from ${S}`,TypeError),AM=createError(`ERR_PACKAGE_PATH_NOT_EXPORTED`,(t,n,S)=>n===`.`?`No "exports" main defined in ${t}package.json${S?` imported from ${S}`:``}`:`Package subpath '${n}' is not defined by "exports" in ${t}package.json${S?` imported from ${S}`:``}`,Error),jM=createError(`ERR_UNSUPPORTED_DIR_IMPORT`,`Directory import '%s' is not supported resolving ES modules imported from %s`,Error),MM=createError(`ERR_UNSUPPORTED_RESOLVE_REQUEST`,`Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.`,TypeError),NM=createError(`ERR_UNKNOWN_FILE_EXTENSION`,(t,n)=>`Unknown file extension "${t}" for ${n}`,TypeError),createError(`ERR_INVALID_ARG_VALUE`,(t,n,S=`is invalid`)=>{let C=inspect(n);return C.length>128&&(C=`${C.slice(0,128)}...`),`The ${t.includes(`.`)?`property`:`argument`} '${t}' ${S}. Received ${C}`},TypeError),PM={}.hasOwnProperty,FM=new Map,IM={}.hasOwnProperty,LM={__proto__:null,".json":`json`,".cjs":`commonjs`,".cts":`commonjs`,".js":`module`,".ts":`module`,".mts":`module`,".mjs":`module`},RM={__proto__:null,"data:":getDataProtocolModuleFormat,"file:":getFileProtocolModuleFormat,"node:":()=>`builtin`},zM=RegExp.prototype[Symbol.replace],BM={}.hasOwnProperty,VM=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i,HM=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i,UM=/^\.|%|\\/,WM=/\*/g,GM=/%2f|%5c/i,KM=new Set,qM=/[/\\]{2}/,__name$1(fileExists$1,`fileExists`),JM=new Set([`node`,`import`]),YM=process.platform===`win32`,XM=globalThis.__EXSOLVE_CACHE__||=new Map});async function findFile(t,n={}){let S=Array.isArray(t)?t:[t],C={...QM,...n},N=resolve(C.startingFrom),F=N[0]===`/`,I=N.split(`/`).filter(Boolean);if(S.includes(I.at(-1))&&await C.test(N))return N;F&&(I[0]=`/`+I[0]);let H=I.findIndex(t=>t.match(C.rootPattern));if(H===-1&&(H=0),C.reverse)for(let t=H+1;t<=I.length;t++)for(let n of S){let S=Gj(...I.slice(0,t),n);if(await C.test(S))return S}else for(let t=I.length;t>H;t--)for(let n of S){let S=Gj(...I.slice(0,t),n);if(await C.test(S))return S}throw Error(`Cannot find matching ${t} in ${C.startingFrom} or parent directories`)}function findNearestFile(t,n={}){return findFile(t,n)}function _resolvePath(t,n={}){return t instanceof URL||t.startsWith(`file://`)?normalize(fileURLToPath(t)):isAbsolute(t)?normalize(t):resolveModulePath(t,{...n,from:n.from||n.parent||n.url})}async function readPackageJSON(t,n={}){let S=await resolvePackageJSON(t,n),C=n.cache&&typeof n.cache!=`boolean`?n.cache:$M;if(n.cache&&C.has(S))return C.get(S);let N=await pd.readFile(S,`utf8`),F;try{F=n$2(N)}catch{F=r$1(N)}return C.set(S,F),F}async function resolvePackageJSON(t=process.cwd(),n={}){return findNearestFile(`package.json`,{...n,startingFrom:_resolvePath(t,n)})}var QM,$M,eN=__esmMin(()=>{Md(),qj(),sM(),ZM(),Hn(),hd(),QM={startingFrom:`.`,rootPattern:/^node_modules$/,reverse:!1,test:t=>{try{if(statSync(t).isFile())return!0}catch{}}},$M=new Map});function d(t,n){if(!n.includes(cN)&&t.hasOwnProperty(n))return[n];let S,C;for(let N of Object.keys(t))if(N.includes(cN)){let[t,F,I]=N.split(cN);if(I===void 0&&n.startsWith(t)&&n.endsWith(F)){let I=n.slice(t.length,-F.length||void 0);I&&(!S||m(S,N))&&(S=N,C=I)}}return[S,C]}var A,a,tN,nN,rN,iN,aN,oN,sN,f,cN,m,p,lN,v,uN=__esmMin(()=>{A=t=>typeof t==`object`&&!!t,a=(t,n)=>Object.assign(Error(`[${t}]: ${n}`),{code:t}),tN=`ERR_INVALID_PACKAGE_CONFIG`,nN=`ERR_INVALID_PACKAGE_TARGET`,rN=`ERR_PACKAGE_PATH_NOT_EXPORTED`,iN=/^\d+$/,aN=/^(\.{1,2}|node_modules)$/i,oN=/\/|\\/,sN=(t=>(t.Export=`exports`,t.Import=`imports`,t))(sN||{}),f=(t,n,S,C,N)=>{if(n==null)return[];if(typeof n==`string`){let[S,...C]=n.split(oN);if(S===`..`||C.some(t=>aN.test(t)))throw a(nN,`Invalid "${t}" target "${n}" defined in the package config`);return[N?n.replace(/\*/g,N):n]}if(Array.isArray(n))return n.flatMap(n=>f(t,n,S,C,N));if(A(n)){for(let F of Object.keys(n)){if(iN.test(F))throw a(tN,`Cannot contain numeric property keys`);if(F==="default"||C.includes(F))return f(t,n[F],S,C,N)}return[]}throw a(nN,`Invalid "${t}" target "${n}"`)},cN=`*`,m=(t,n)=>{let S=t.indexOf(cN),C=n.indexOf(cN);return S===C?n.length>t.length:C>S},p=t=>Object.keys(t).reduce((t,n)=>{let S=n===``||n[0]!==`.`;if(t===void 0||t===S)return S;throw a(tN,`"exports" cannot contain some keys starting with "." and some not`)},void 0),lN=/^\w+:/,v=(t,n,S)=>{if(!t)throw Error(`"exports" is required`);n=n===``?`.`:`./${n}`,(typeof t==`string`||Array.isArray(t)||A(t)&&p(t))&&(t={".":t});let[C,N]=d(t,n),F=f(sN.Export,t[C],n,S,N);if(F.length===0)throw a(rN,n===`.`?`No "exports" main defined`:`Package subpath '${n}' is not defined by "exports"`);for(let t of F)if(!t.startsWith(`./`)&&!lN.test(t))throw a(nN,`Invalid "exports" target "${t}" defined in the package config`);return F}});function h(t){return t.startsWith(`\\\\?\\`)?t:t.replace(/\\/g,`/`)}function Ne(t,n=!1){let S=t.length,C=0,N=``,F=0,I=16,H=0,W=0,q=0,Y=0,X=0;function _(n,S){let N=0,F=0;for(;N<n;){let n=t.charCodeAt(C);if(n>=48&&n<=57)F=F*16+n-48;else if(n>=65&&n<=70)F=F*16+n-65+10;else if(n>=97&&n<=102)F=F*16+n-97+10;else break;C++,N++}return N<n&&(F=-1),F}r(_,`scanHexDigits`);function v(t){C=t,N=``,F=0,I=16,X=0}r(v,`setPosition`);function p(){let n=C;if(t.charCodeAt(C)===48)C++;else for(C++;C<t.length&&R(t.charCodeAt(C));)C++;if(C<t.length&&t.charCodeAt(C)===46)if(C++,C<t.length&&R(t.charCodeAt(C)))for(C++;C<t.length&&R(t.charCodeAt(C));)C++;else return X=3,t.substring(n,C);let S=C;if(C<t.length&&(t.charCodeAt(C)===69||t.charCodeAt(C)===101))if(C++,(C<t.length&&t.charCodeAt(C)===43||t.charCodeAt(C)===45)&&C++,C<t.length&&R(t.charCodeAt(C))){for(C++;C<t.length&&R(t.charCodeAt(C));)C++;S=C}else X=3;return t.substring(n,S)}r(p,`scanNumber`);function L(){let n=``,N=C;for(;;){if(C>=S){n+=t.substring(N,C),X=2;break}let F=t.charCodeAt(C);if(F===34){n+=t.substring(N,C),C++;break}if(F===92){if(n+=t.substring(N,C),C++,C>=S){X=2;break}switch(t.charCodeAt(C++)){case 34:n+=`"`;break;case 92:n+=`\\`;break;case 47:n+=`/`;break;case 98:n+=`\b`;break;case 102:n+=`\f`;break;case 110:n+=`
|
|
771
|
+
`+` `.repeat(n)),(function(t){t.DEFAULT={allowTrailingComma:!1}})(eM||={}),__name$1(d$1,`d`),(function(t){t[t.None=0]=`None`,t[t.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=4]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=6]=`InvalidCharacter`})(tM||={}),(function(t){t[t.OpenBraceToken=1]=`OpenBraceToken`,t[t.CloseBraceToken=2]=`CloseBraceToken`,t[t.OpenBracketToken=3]=`OpenBracketToken`,t[t.CloseBracketToken=4]=`CloseBracketToken`,t[t.CommaToken=5]=`CommaToken`,t[t.ColonToken=6]=`ColonToken`,t[t.NullKeyword=7]=`NullKeyword`,t[t.TrueKeyword=8]=`TrueKeyword`,t[t.FalseKeyword=9]=`FalseKeyword`,t[t.StringLiteral=10]=`StringLiteral`,t[t.NumericLiteral=11]=`NumericLiteral`,t[t.LineCommentTrivia=12]=`LineCommentTrivia`,t[t.BlockCommentTrivia=13]=`BlockCommentTrivia`,t[t.LineBreakTrivia=14]=`LineBreakTrivia`,t[t.Trivia=15]=`Trivia`,t[t.Unknown=16]=`Unknown`,t[t.EOF=17]=`EOF`})(nM||={}),rM=o,(function(t){t[t.InvalidSymbol=1]=`InvalidSymbol`,t[t.InvalidNumberFormat=2]=`InvalidNumberFormat`,t[t.PropertyNameExpected=3]=`PropertyNameExpected`,t[t.ValueExpected=4]=`ValueExpected`,t[t.ColonExpected=5]=`ColonExpected`,t[t.CommaExpected=6]=`CommaExpected`,t[t.CloseBraceExpected=7]=`CloseBraceExpected`,t[t.CloseBracketExpected=8]=`CloseBracketExpected`,t[t.EndOfFileExpected=9]=`EndOfFileExpected`,t[t.InvalidCommentToken=10]=`InvalidCommentToken`,t[t.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=14]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=16]=`InvalidCharacter`})(iM||={})});function n$2(t,n){let S=JSON.parse(t,n?.reviver);return a$4(t,S,n),S}var oM=__esmMin(()=>{Qj(),__name$1(n$2,`n`)});function r$1(t,n){let S=rM(t,n?.errors,n);return a$4(t,S,n),S}var sM=__esmMin(()=>{Qj(),aM(),__name$1(r$1,`r`)}),cM=__esmMin(()=>{oM(),sM()});function readProcessMemory$3(){try{let[t,n]=lt.spawn_command_line_sync(`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!t||!n)return null;let S=new TextDecoder().decode(n).trim(),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}catch{return null}}var lM=__esmMin(()=>{ut(),__name$1(readProcessMemory$3,`readProcessMemory`)});function readProcessMemory$2(){let t;try{let[n,S]=lt.file_get_contents(`/proc/self/status`);if(!n||!S)return null;t=new TextDecoder().decode(S)}catch{return null}let n=new Map;for(let S of t.split(`
|
|
772
|
+
`)){let t=/^(\w+):\s+(\d+)(\s+kB)?/.exec(S);t&&n.set(t[1],parseInt(t[2])*(t[3]?1024:1))}return n.size===0?null:{virtual:n.get(`VmSize`)??0,resident:n.get(`VmRSS`)??0,data:n.get(`VmData`)??0,peak:n.get(`VmPeak`)??0}}var uM=__esmMin(()=>{ut(),__name$1(readProcessMemory$2,`readProcessMemory`)});function readProcessMemory$1(){return null}var dM=__esmMin(()=>{__name$1(readProcessMemory$1,`readProcessMemory`)});function detectHeapPlatform(){return fM===null&&(fM=lt.get_current_dir().startsWith(`/`)?lt.file_test(`/proc/self/status`,lt.FileTest.EXISTS)?`linux`:lt.file_test(`/System/Library/CoreServices/SystemVersion.plist`,lt.FileTest.EXISTS)?`darwin`:`unknown`:`win32`),fM}function readProcessMemory(){switch(detectHeapPlatform()){case`linux`:return readProcessMemory$2();case`darwin`:return readProcessMemory$3();case`win32`:return readProcessMemory$1();default:return null}}function getHeapStatistics(){let t=readProcessMemory()??pM;return{total_heap_size:t.virtual,total_heap_size_executable:0,total_physical_size:t.resident,total_available_size:0,used_heap_size:t.resident,heap_size_limit:0,malloced_memory:t.data,peak_malloced_memory:t.peak,does_zap_garbage:0,number_of_native_contexts:0,number_of_detached_contexts:0,total_global_handles_size:0,used_global_handles_size:0,external_memory:0}}var fM,pM,mM=__esmMin(()=>{lM(),uM(),dM(),ut(),fM=null,pM={virtual:0,resident:0,data:0,peak:0}});function writeVarint(t,n){for(n>>>=0;n>=128;)t.push(n&127|128),n>>>=7;t.push(n)}function readVarint(t,n){let S=0,C=0,N;do{if(n>=t.length)throw Error(`Unexpected end of buffer reading varint`);N=t[n++],S|=(N&127)<<C,C+=7}while(N&128);return[S>>>0,n]}function zigZagEncode(t){return t>=0?t*2:-t*2-1}function zigZagDecode(t){return t&1?-(t>>>1)-1:t>>>1}function writeFloat64(t,n){let S=new DataView(new ArrayBuffer(8));S.setFloat64(0,n,!0);for(let n=0;n<8;n++)t.push(S.getUint8(n))}function readFloat64(t,n){if(n+8>t.length)throw Error(`ReadDouble() failed`);return[new DataView(t.buffer,t.byteOffset+n,8).getFloat64(0,!0),n+8]}function isOneByte(t){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>255)return!1;return!0}function typedArrayToIndex(t){let n=Object.prototype.toString.call(t);return n===`[object Int8Array]`?0:n===`[object Uint8Array]`?1:n===`[object Uint8ClampedArray]`?2:n===`[object Int16Array]`?3:n===`[object Uint16Array]`?4:n===`[object Int32Array]`?5:n===`[object Uint32Array]`?6:n===`[object Float32Array]`?7:n===`[object Float64Array]`?8:n===`[object DataView]`?9:n===`[object BigInt64Array]`?11:n===`[object BigUint64Array]`?12:-1}function indexToTypedArray(t){switch(t){case 0:return Int8Array;case 1:return Uint8Array;case 2:return Uint8ClampedArray;case 3:return Int16Array;case 4:return Uint16Array;case 5:return Int32Array;case 6:return Uint32Array;case 7:return Float32Array;case 8:return Float64Array;case 9:return DataView;case 10:return Xe;case 11:return BigInt64Array;case 12:return BigUint64Array}}function regExpFlagsToInt(t){let n=0;return t.global&&(n|=1),t.ignoreCase&&(n|=2),t.multiline&&(n|=4),t.sticky&&(n|=8),t.unicode&&(n|=16),t.dotAll&&(n|=32),t.hasIndices&&(n|=64),t.unicodeSets&&(n|=128),n}function intToRegExpFlags(t){let n=``;return t&1&&(n+=`g`),t&2&&(n+=`i`),t&4&&(n+=`m`),t&8&&(n+=`y`),t&16&&(n+=`u`),t&32&&(n+=`s`),t&64&&(n+=`d`),t&128&&(n+=`v`),n}var Serializer,Deserializer,DefaultSerializer,DefaultDeserializer,hM=__esmMin(()=>{ot(),Serializer=class{_bytes=[];_seen=[];_treatAbvAsHostObjects=!1;_getDataCloneError=Error;writeHeader(){this._bytes.push(255),writeVarint(this._bytes,15)}writeValue(t){if(typeof t==`object`&&t){let n=this._seen.indexOf(t);if(n!==-1){this._bytes.push(94),writeVarint(this._bytes,n);return}}if(t===void 0)this._bytes.push(95);else if(t===null)this._bytes.push(48);else if(t===!0)this._bytes.push(84);else if(t===!1)this._bytes.push(70);else if(typeof t==`number`)Number.isInteger(t)&&t>=-(2**31)&&t<=2**32-1?t>=0?(this._bytes.push(85),writeVarint(this._bytes,t)):(this._bytes.push(73),writeVarint(this._bytes,zigZagEncode(t))):(this._bytes.push(78),writeFloat64(this._bytes,t));else if(typeof t==`bigint`)this._writeBigInt(t);else if(typeof t==`string`)this._writeString(t);else if(typeof t==`object`){let n=t;if(t instanceof Date)this._seen.push(n),this._bytes.push(68),writeFloat64(this._bytes,t.getTime());else if(t instanceof RegExp)this._seen.push(n),this._bytes.push(82),this._writeString(t.source),writeVarint(this._bytes,regExpFlagsToInt(t));else if(t instanceof ArrayBuffer){this._seen.push(n);let S=new Uint8Array(t);this._bytes.push(66),writeVarint(this._bytes,S.length);for(let t=0;t<S.length;t++)this._bytes.push(S[t])}else if(this._treatAbvAsHostObjects&&(ArrayBuffer.isView(t)||Xe.isBuffer(t)))this._seen.push(n),this._bytes.push(92),this._writeHostObject(n);else if(Array.isArray(t)){this._seen.push(n);let S=t;this._bytes.push(65),writeVarint(this._bytes,S.length);for(let t=0;t<S.length;t++)this.writeValue(S[t]);this._bytes.push(36),writeVarint(this._bytes,0),writeVarint(this._bytes,S.length)}else{this._seen.push(n),this._bytes.push(111);let t=Object.keys(n);for(let S of t)this._writeString(S),this.writeValue(n[S]);this._bytes.push(123),writeVarint(this._bytes,t.length)}}else throw new this._getDataCloneError(`${String(t)} could not be cloned.`)}releaseBuffer(){let t=Xe.from(this._bytes);return this._bytes=[],this._seen=[],t}writeUint32(t){writeVarint(this._bytes,t>>>0)}writeUint64(t,n){writeVarint(this._bytes,t>>>0),writeVarint(this._bytes,n>>>0)}writeDouble(t){writeFloat64(this._bytes,t)}writeRawBytes(t){if(!ArrayBuffer.isView(t))throw TypeError(`source must be a TypedArray or a DataView`);let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);for(let t=0;t<n.length;t++)this._bytes.push(n[t])}_writeHostObject(t){throw new this._getDataCloneError(`Unserializable host object: ${Object.prototype.toString.call(t)}`)}_setTreatArrayBufferViewsAsHostObjects(t){this._treatAbvAsHostObjects=t}_writeString(t){if(isOneByte(t)){this._bytes.push(34),writeVarint(this._bytes,t.length);for(let n=0;n<t.length;n++)this._bytes.push(t.charCodeAt(n)&255)}else{let n=new TextEncoder().encode(t);this._bytes.push(99),writeVarint(this._bytes,n.length);for(let t=0;t<n.length;t++)this._bytes.push(n[t])}}_writeBigInt(t){this._bytes.push(90);let n=t<0n,S=n?-t:t,C=[],N=S;for(;N>0n;)C.push(Number(N&4294967295n)),C.push(Number(N>>32n&4294967295n)),N>>=64n;let F=C.length<<1|!!n;writeVarint(this._bytes,F);for(let t of C)this._bytes.push(t&255),this._bytes.push(t>>8&255),this._bytes.push(t>>16&255),this._bytes.push(t>>24&255);C.length}},Deserializer=class{_pos=0;_wireVersion=0;_seen=[];buffer;constructor(t){if(!ArrayBuffer.isView(t)&&!(t instanceof ArrayBuffer))throw TypeError(`buffer must be a TypedArray or a DataView`);t instanceof ArrayBuffer?this.buffer=Xe.from(t):this.buffer=Xe.from(t.buffer,t.byteOffset,t.byteLength)}readHeader(){if(this.buffer[this._pos]!==255)throw Error(`ReadHeader() failed`);this._pos++;let[t,n]=readVarint(this.buffer,this._pos);return this._wireVersion=t,this._pos=n,!0}getWireFormatVersion(){return this._wireVersion}readValue(){if(this._pos>=this.buffer.length)throw Error(`Unexpected end of buffer`);let t=this.buffer[this._pos++];switch(t){case 95:return;case 48:return null;case 84:return!0;case 70:return!1;case 73:{let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,zigZagDecode(t)}case 85:{let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,t>>>0}case 78:{let[t,n]=readFloat64(this.buffer,this._pos);return this._pos=n,t}case 90:return this._readBigInt();case 34:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=``;for(let n=0;n<t;n++)S+=String.fromCharCode(this.buffer[this._pos++]);return S}case 99:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=this.buffer.slice(this._pos,this._pos+t);return this._pos+=t,new TextDecoder().decode(S)}case 68:{let[t,n]=readFloat64(this.buffer,this._pos);this._pos=n;let S=new Date(t);return this._seen.push(S),S}case 82:{let t=this.readValue(),[n,S]=readVarint(this.buffer,this._pos);this._pos=S;let C=intToRegExpFlags(n),N=new RegExp(t,C);return this._seen.push(N),N}case 66:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=new ArrayBuffer(t),C=new Uint8Array(S);for(let n=0;n<t;n++)C[n]=this.buffer[this._pos++];return this._seen.push(S),S}case 94:{let[t,n]=readVarint(this.buffer,this._pos);if(this._pos=n,t>=this._seen.length)throw Error(`Invalid object reference`);return this._seen[t]}case 65:{let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=Array.from({length:t});this._seen.push(S);for(let n=0;n<t;n++)S[n]=this.readValue();if(this.buffer[this._pos]!==36)throw Error(`Expected kEndDenseArray`);this._pos++;let[,C]=readVarint(this.buffer,this._pos);this._pos=C;let[,N]=readVarint(this.buffer,this._pos);return this._pos=N,S}case 111:{let t={};for(this._seen.push(t);this.buffer[this._pos]!==123;){let n=this.readValue();t[n]=this.readValue()}this._pos++;let[,n]=readVarint(this.buffer,this._pos);return this._pos=n,t}case 92:{let t=this._readHostObject();return t!=null&&this._seen.push(t),t}default:throw Error(`Unknown tag 0x${t.toString(16).padStart(2,`0`)} at position ${this._pos-1}`)}}readUint32(){let[t,n]=readVarint(this.buffer,this._pos);return this._pos=n,t>>>0}readUint64(){let[t,n]=readVarint(this.buffer,this._pos),[S,C]=readVarint(this.buffer,n);return this._pos=C,[t>>>0,S>>>0]}readDouble(){let[t,n]=readFloat64(this.buffer,this._pos);return this._pos=n,t}_readRawBytes(t){let n=this._pos;if(this._pos+=t,this._pos>this.buffer.length)throw Error(`Unexpected end of buffer reading raw bytes`);return n}readRawBytes(t){let n=this._readRawBytes(t);return Xe.from(this.buffer.buffer,this.buffer.byteOffset+n,t)}_readHostObject(){throw Error(`No host object deserializer installed`)}_readBigInt(){let[t,n]=readVarint(this.buffer,this._pos);this._pos=n;let S=(t&1)==1,C=t>>1,N=0n;for(let t=0;t<C;t++){let n=this.buffer[this._pos]|this.buffer[this._pos+1]<<8|this.buffer[this._pos+2]<<16|this.buffer[this._pos+3]<<24;this._pos+=4,N|=BigInt(n>>>0)<<BigInt(t*32)}return S?-N:N}},DefaultSerializer=class extends Serializer{constructor(){super(),this._setTreatArrayBufferViewsAsHostObjects(!0)}_writeHostObject(t){let n;if(Xe.isBuffer(t))n=10;else if(n=typedArrayToIndex(t),n===-1)throw new this._getDataCloneError(`Unserializable host object: ${Object.prototype.toString.call(t)}`);this.writeUint32(n),this.writeUint32(t.byteLength),this.writeRawBytes(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}},DefaultDeserializer=class extends Deserializer{_readHostObject(){let t=this.readUint32(),n=this.readUint32(),S=this._readRawBytes(n);if(t===10){let t=Xe.allocUnsafe(n);return this.buffer.copy(t,0,this.buffer.byteOffset+S,this.buffer.byteOffset+S+n),t}let C=indexToTypedArray(t);if(!C)throw Error(`Unknown TypedArray type index ${t}`);let N=C.BYTES_PER_ELEMENT??1,F=n/N,I=this.buffer.byteOffset+S;if(I%N===0)return new C(this.buffer.buffer,I,F);let H=Xe.allocUnsafe(n);return this.buffer.copy(H,0,this.buffer.byteOffset+S,this.buffer.byteOffset+S+n),new C(H.buffer,H.byteOffset,F)}}});function serialize(t){let n=new DefaultSerializer;return n.writeHeader(),n.writeValue(t),n.releaseBuffer()}function deserialize(t){let n=new DefaultDeserializer(t);return n.readHeader(),n.readValue()}function getHeapSpaceStatistics(){return[]}function getHeapCodeStatistics(){return{code_and_metadata_size:0,bytecode_and_metadata_size:0,external_script_source_size:0,cpu_profiler_metadata_size:0}}function setFlagsFromString(t){}function getHeapSnapshot(t){return null}function writeHeapSnapshot(t){return``}function isStringOneByteRepresentation(t){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>255)return!1;return!0}function startCpuProfile(){return new SyncCPUProfileHandle}var GCProfiler,SyncCPUProfileHandle,gM,_M=__esmMin(()=>{mM(),hM(),GCProfiler=class{#e=!1;#t=0;start(){this.#e||(this.#e=!0,this.#t=Date.now())}stop(){if(this.#e){this.#e=!1;try{let t=globalThis.imports?.system;typeof t?.gc==`function`&&t.gc()}catch{}return{version:1,startTime:this.#t,endTime:Date.now(),stats:[]}}}[Symbol.dispose](){this.stop()}},SyncCPUProfileHandle=class{stop(){}[Symbol.dispose](){this.stop()}},gM={getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,getHeapSnapshot,writeHeapSnapshot,serialize,deserialize,isStringOneByteRepresentation,Serializer,Deserializer,DefaultSerializer,DefaultDeserializer,GCProfiler,startCpuProfile}});function formatList(t,n=`and`){return t.length<3?t.join(` ${n} `):`${t.slice(0,-1).join(`, `)}, ${n} ${t.at(-1)}`}function createError(t,n,S){return SM.set(t,n),makeNodeErrorWithCode(S,t)}function makeNodeErrorWithCode(t,n){return function NodeError(...S){let C=Error.stackTraceLimit;isErrorStackTraceLimitWritable()&&(Error.stackTraceLimit=0);let N=new t;isErrorStackTraceLimitWritable()&&(Error.stackTraceLimit=C);let F=getMessage(n,S,N);return Object.defineProperties(N,{message:{value:F,enumerable:!1,writable:!0,configurable:!0},toString:{value(){return`${this.name} [${n}]: ${this.message}`},enumerable:!1,writable:!0,configurable:!0}}),TM(N),N.code=n,N}}function isErrorStackTraceLimitWritable(){try{if(gM.startupSnapshot.isBuildingSnapshot())return!1}catch{}let t=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return t===void 0?Object.isExtensible(Error):yM.call(t,`writable`)&&t.writable!==void 0?t.writable:t.set!==void 0}function hideStackFrames(t){let n=CM+t.name;return Object.defineProperty(t,"name",{value:n}),t}function getMessage(t,n,S){let C=SM.get(t);if(qd.ok(C!==void 0,"expected `message` to be found"),typeof C==`function`)return qd.ok(C.length<=n.length,`Code: ${t}; The provided arguments length (${n.length}) does not match the required ones (${C.length}).`),Reflect.apply(C,S,n);let N=/%[dfijoOs]/g,F=0;for(;N.exec(C)!==null;)F++;return qd.ok(F===n.length,`Code: ${t}; The provided arguments length (${n.length}) does not match the required ones (${F}).`),n.length===0?C:(n.unshift(C),Reflect.apply(format,null,n))}function determineSpecificType(t){if(t==null)return String(t);if(typeof t==`function`&&t.name)return`function ${t.name}`;if(typeof t==`object`)return t.constructor&&t.constructor.name?`an instance of ${t.constructor.name}`:`${inspect(t,{depth:-1})}`;let n=inspect(t,{colors:!1});return n.length>28&&(n=`${n.slice(0,25)}...`),`type ${typeof t} (${n})`}function read(t,{base:n,specifier:S}){let C=IM.get(t);if(C)return C;let N;try{N=jd.readFileSync(An.toNamespacedPath(t),`utf8`)}catch(t){let n=t;if(n.code!==`ENOENT`)throw n}let F={exists:!1,pjsonPath:t,main:void 0,name:void 0,type:`none`,exports:void 0,imports:void 0};if(N!==void 0){let C;try{C=JSON.parse(N)}catch(C){let N=new DM(t,(n?`"${S}" from `:``)+fileURLToPath(n||S),C.message);throw N.cause=C,N}F.exists=!0,FM.call(C,`name`)&&typeof C.name==`string`&&(F.name=C.name),FM.call(C,`main`)&&typeof C.main==`string`&&(F.main=C.main),FM.call(C,`exports`)&&(F.exports=C.exports),FM.call(C,`imports`)&&(F.imports=C.imports),FM.call(C,`type`)&&(C.type===`commonjs`||C.type===`module`)&&(F.type=C.type)}return IM.set(t,F),F}function getPackageScopeConfig(t){let n=new URL(`package.json`,t);for(;!n.pathname.endsWith(`node_modules/package.json`);){let S=read(fileURLToPath(n),{specifier:t});if(S.exists)return S;let C=n;if(n=new URL(`../package.json`,n),n.pathname===C.pathname)break}return{pjsonPath:fileURLToPath(n),exists:!1,type:`none`}}function mimeToFormat(t){return t&&/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(t)?`module`:t===`application/json`?`json`:null}function getDataProtocolModuleFormat(t){let{1:n}=/^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(t.pathname)||[null,null,null];return mimeToFormat(n)}function extname(t){let n=t.pathname,S=n.length;for(;S--;){let t=n.codePointAt(S);if(t===47)return``;if(t===46)return n.codePointAt(S-1)===47?``:n.slice(S)}return``}function getFileProtocolModuleFormat(t,n,S){let C=extname(t);if(C===`.js`){let{type:n}=getPackageScopeConfig(t);return n===`none`?`commonjs`:n}if(C===``){let{type:n}=getPackageScopeConfig(t);return n===`none`||n===`commonjs`?`commonjs`:`module`}let N=RM[C];if(N)return N;if(!S)throw new PM(C,fileURLToPath(t))}function defaultGetFormatWithoutErrors(t,n){let S=t.protocol;return LM.call(zM,S)&&zM[S](t,n,!0)||null}function emitInvalidSegmentDeprecation(t,n,S,C,N,F,I){if(en.noDeprecation)return;let H=fileURLToPath(C),W=JM.exec(I?t:n)!==null;en.emitWarning(`Use of deprecated ${W?`double slash`:`leading or trailing slash matching`} resolving "${t}" for module request "${n}" ${n===S?``:`matched to "${S}" `}in the "${N?`imports`:`exports`}" field module resolution of the package at ${H}${F?` imported from ${fileURLToPath(F)}`:``}.`,`DeprecationWarning`,`DEP0166`)}function emitLegacyIndexDeprecation(t,n,S,C){if(en.noDeprecation||defaultGetFormatWithoutErrors(t,{parentURL:S.href})!==`module`)return;let N=fileURLToPath(t.href),F=fileURLToPath(new Bn(`.`,n)),I=fileURLToPath(S);C?An.resolve(F,C)!==N&&en.emitWarning(`Package ${F} has a "main" field set to "${C}", excluding the full filename and extension to the resolved file at "${N.slice(F.length)}", imported from ${I}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`):en.emitWarning(`No "main" or "exports" field defined in the package.json for ${F} resolving the main entry point "${N.slice(F.length)}", imported from ${I}.\nDefault "index" lookups for the main are deprecated for ES modules.`,`DeprecationWarning`,`DEP0151`)}function tryStatSync(t){try{return statSync(t)}catch{}}function fileExists$1(t){let n=statSync(t,{throwIfNoEntry:!1});return(n?n.isFile():void 0)??!1}function legacyMainResolve(t,n,S){let C;if(n.main!==void 0){if(C=new Bn(n.main,t),fileExists$1(C))return C;let N=[`./${n.main}.js`,`./${n.main}.json`,`./${n.main}.node`,`./${n.main}/index.js`,`./${n.main}/index.json`,`./${n.main}/index.node`],F=-1;for(;++F<N.length&&(C=new Bn(N[F],t),!fileExists$1(C));)C=void 0;if(C)return emitLegacyIndexDeprecation(C,t,S,n.main),C}let N=[`./index.js`,`./index.json`,`./index.node`],F=-1;for(;++F<N.length&&(C=new Bn(N[F],t),!fileExists$1(C));)C=void 0;if(C)return emitLegacyIndexDeprecation(C,t,S,n.main),C;throw new kM(fileURLToPath(new Bn(`.`,t)),fileURLToPath(S))}function finalizeResolution(t,n,S){if(KM.exec(t.pathname)!==null)throw new EM(t.pathname,String.raw`must not include encoded "/" or "\" characters`,fileURLToPath(n));let C;try{C=fileURLToPath(t)}catch(S){throw Object.defineProperty(S,"input",{value:String(t)}),Object.defineProperty(S,"module",{value:String(n)}),S}let N=tryStatSync(C.endsWith(`/`)?C.slice(-1):C);if(N&&N.isDirectory()){let S=new MM(C,fileURLToPath(n));throw S.url=String(t),S}if(!N||!N.isFile()){let S=new kM(C||t.pathname,n&&fileURLToPath(n),!0);throw S.url=String(t),S}if(!S){let n=realpathSync(C),{search:S,hash:N}=t;t=pathToFileURL(n+(C.endsWith(An.sep)?`/`:``)),t.search=S,t.hash=N}return t}function importNotDefined(t,n,S){return new AM(t,n&&fileURLToPath(new Bn(`.`,n)),fileURLToPath(S))}function exportsNotFound(t,n,S){return new jM(fileURLToPath(new Bn(`.`,n)),t,S&&fileURLToPath(S))}function throwInvalidSubpath(t,n,S,C,N){throw new EM(t,`request is not a valid match in pattern "${n}" for the "${C?`imports`:`exports`}" resolution of ${fileURLToPath(S)}`,N&&fileURLToPath(N))}function invalidPackageTarget(t,n,S,C,N){return n=typeof n==`object`&&n?JSON.stringify(n,null,``):`${n}`,new OM(fileURLToPath(new Bn(`.`,S)),t,n,C,N&&fileURLToPath(N))}function resolvePackageTargetString(t,n,S,C,N,F,I,H,W){if(n!==``&&!F&&t.at(-1)!==`/`)throw invalidPackageTarget(S,t,C,I,N);if(!t.startsWith(`./`)){if(I&&!t.startsWith(`../`)&&!t.startsWith(`/`)){let S=!1;try{new Bn(t),S=!0}catch{}if(!S)return packageResolve(F?BM.call(GM,t,()=>n):t+n,C,W)}throw invalidPackageTarget(S,t,C,I,N)}if(HM.exec(t.slice(2))!==null)if(UM.exec(t.slice(2))===null){if(!H){let H=F?S.replace(`*`,()=>n):S+n;emitInvalidSegmentDeprecation(F?BM.call(GM,t,()=>n):t,H,S,C,I,N,!0)}}else throw invalidPackageTarget(S,t,C,I,N);let q=new Bn(t,C),Y=q.pathname,X=new Bn(`.`,C).pathname;if(!Y.startsWith(X))throw invalidPackageTarget(S,t,C,I,N);if(n===``)return q;if(HM.exec(n)!==null){let W=F?S.replace(`*`,()=>n):S+n;UM.exec(n)===null?H||emitInvalidSegmentDeprecation(F?BM.call(GM,t,()=>n):t,W,S,C,I,N,!1):throwInvalidSubpath(W,S,C,I,N)}return F?new Bn(BM.call(GM,q.href,()=>n)):new Bn(n,q)}function isArrayIndex(t){let n=Number(t);return`${n}`===t?n>=0&&n<4294967295:!1}function resolvePackageTarget(t,n,S,C,N,F,I,H,W){if(typeof n==`string`)return resolvePackageTargetString(n,S,C,t,N,F,I,H,W);if(Array.isArray(n)){let q=n;if(q.length===0)return null;let Y,X=-1;for(;++X<q.length;){let n=q[X],Z;try{Z=resolvePackageTarget(t,n,S,C,N,F,I,H,W)}catch(t){let n=t;if(Y=n,n.code===`ERR_INVALID_PACKAGE_TARGET`)continue;throw t}if(Z!==void 0){if(Z===null){Y=null;continue}return Z}}if(Y==null)return null;throw Y}if(typeof n==`object`&&n){let q=Object.getOwnPropertyNames(n),Y=-1;for(;++Y<q.length;){let n=q[Y];if(isArrayIndex(n))throw new DM(fileURLToPath(t),fileURLToPath(N),`"exports" cannot contain numeric property keys.`)}for(Y=-1;++Y<q.length;){let X=q[Y];if(X==="default"||W&&W.has(X)){let q=n[X],Y=resolvePackageTarget(t,q,S,C,N,F,I,H,W);if(Y===void 0)continue;return Y}}return null}if(n===null)return null;throw invalidPackageTarget(C,n,t,I,N)}function isConditionalExportsMainSugar(t,n,S){if(typeof t==`string`||Array.isArray(t))return!0;if(typeof t!=`object`||!t)return!1;let C=Object.getOwnPropertyNames(t),N=!1,F=0,I=-1;for(;++I<C.length;){let t=C[I],H=t===``||t[0]!==`.`;if(F++===0)N=H;else if(N!==H)throw new DM(fileURLToPath(n),fileURLToPath(S),`"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`)}return N}function emitTrailingSlashPatternDeprecation(t,n,S){if(en.noDeprecation)return;let C=fileURLToPath(n);qM.has(C+`|`+t)||(qM.add(C+`|`+t),en.emitWarning(`Use of deprecated trailing slash pattern mapping "${t}" in the "exports" field module resolution of the package at ${C}${S?` imported from ${fileURLToPath(S)}`:``}. Mapping specifiers ending in "/" is no longer supported.`,`DeprecationWarning`,`DEP0155`))}function packageExportsResolve(t,n,S,C,N){let F=S.exports;if(isConditionalExportsMainSugar(F,t,C)&&(F={".":F}),VM.call(F,n)&&!n.includes(`*`)&&!n.endsWith(`/`)){let S=F[n],I=resolvePackageTarget(t,S,``,n,C,!1,!1,!1,N);if(I==null)throw exportsNotFound(n,t,C);return I}let I=``,H=``,W=Object.getOwnPropertyNames(F),q=-1;for(;++q<W.length;){let S=W[q],N=S.indexOf(`*`);if(N!==-1&&n.startsWith(S.slice(0,N))){n.endsWith(`/`)&&emitTrailingSlashPatternDeprecation(n,t,C);let F=S.slice(N+1);n.length>=S.length&&n.endsWith(F)&&patternKeyCompare(I,S)===1&&S.lastIndexOf(`*`)===N&&(I=S,H=n.slice(N,n.length-F.length))}}if(I){let S=F[I],W=resolvePackageTarget(t,S,H,I,C,!0,!1,n.endsWith(`/`),N);if(W==null)throw exportsNotFound(n,t,C);return W}throw exportsNotFound(n,t,C)}function patternKeyCompare(t,n){let S=t.indexOf(`*`),C=n.indexOf(`*`),N=S===-1?t.length:S+1,F=C===-1?n.length:C+1;return N>F?-1:F>N||S===-1?1:C===-1||t.length>n.length?-1:+(n.length>t.length)}function packageImportsResolve(t,n,S){if(t===`#`||t.startsWith(`#/`)||t.endsWith(`/`))throw new EM(t,`is not a valid internal imports specifier name`,fileURLToPath(n));let C,N=getPackageScopeConfig(n);if(N.exists){C=pathToFileURL(N.pjsonPath);let F=N.imports;if(F)if(VM.call(F,t)&&!t.includes(`*`)){let N=resolvePackageTarget(C,F[t],``,t,n,!1,!0,!1,S);if(N!=null)return N}else{let N=``,I=``,H=Object.getOwnPropertyNames(F),W=-1;for(;++W<H.length;){let n=H[W],S=n.indexOf(`*`);if(S!==-1&&t.startsWith(n.slice(0,-1))){let C=n.slice(S+1);t.length>=n.length&&t.endsWith(C)&&patternKeyCompare(N,n)===1&&n.lastIndexOf(`*`)===S&&(N=n,I=t.slice(S,t.length-C.length))}}if(N){let t=F[N],H=resolvePackageTarget(C,t,I,N,n,!0,!0,!1,S);if(H!=null)return H}}}throw importNotDefined(t,C,n)}function parsePackageName(t,n){let S=t.indexOf(`/`),C=!0,N=!1;t[0]===`@`&&(N=!0,S===-1||t.length===0?C=!1:S=t.indexOf(`/`,S+1));let F=S===-1?t:t.slice(0,S);if(WM.exec(F)!==null&&(C=!1),!C)throw new EM(t,`is not a valid package name`,fileURLToPath(n));return{packageName:F,packageSubpath:`.`+(S===-1?``:t.slice(S)),isScoped:N}}function packageResolve(t,n,S){if(vM.includes(t))return new Bn(`node:`+t);let{packageName:C,packageSubpath:N,isScoped:F}=parsePackageName(t,n),I=getPackageScopeConfig(n);if(I.exists&&I.name===C&&I.exports!==void 0&&I.exports!==null)return packageExportsResolve(pathToFileURL(I.pjsonPath),N,I,n,S);let H=new Bn(`./node_modules/`+C+`/package.json`,n),W=fileURLToPath(H),q;do{let I=tryStatSync(W.slice(0,-13));if(!I||!I.isDirectory()){q=W,H=new Bn((F?`../../../../node_modules/`:`../../../node_modules/`)+C+`/package.json`,H),W=fileURLToPath(H);continue}let Y=read(W,{base:n,specifier:t});return Y.exports!==void 0&&Y.exports!==null?packageExportsResolve(H,N,Y,n,S):N===`.`?legacyMainResolve(H,Y,n):new Bn(N,H)}while(W.length!==q.length);throw new kM(C,fileURLToPath(n),!1)}function isRelativeSpecifier(t){return t[0]===`.`&&(t.length===1||t[1]===`/`||t[1]===`.`&&(t.length===2||t[2]===`/`))}function shouldBeTreatedAsRelativeOrAbsolutePath(t){return t===``?!1:t[0]===`/`?!0:isRelativeSpecifier(t)}function moduleResolve(t,n,S,C){let N=n.protocol,F=N===`data:`,I;if(shouldBeTreatedAsRelativeOrAbsolutePath(t))try{I=new Bn(t,n)}catch(S){let C=new NM(t,n);throw C.cause=S,C}else if(N===`file:`&&t[0]===`#`)I=packageImportsResolve(t,n,S);else try{I=new Bn(t)}catch(C){if(F&&!vM.includes(t)){let S=new NM(t,n);throw S.cause=C,S}I=packageResolve(t,n,S)}return qd.ok(I!==void 0,`expected to be defined`),I.protocol===`file:`?finalizeResolution(I,n,C):I}function resolveModuleURL(t,n){let S=_parseInput(t);if(`external`in S)return S.external;let C=S.specifier,N=S.url,F=S.absolutePath,I,H;if(n?.cache!==!1&&(I=_cacheKey(F||C,n),H=n?.cache&&typeof n?.cache==`object`?n.cache:ZM),H){let t=H.get(I);if(typeof t==`string`)return t;if(t instanceof Error){if(n?.try)return;throw t}}if(F)try{let t=lstatSync(F);if(t.isSymbolicLink()&&(F=realpathSync(F),N=pathToFileURL(F)),t.isFile())return H&&H.set(I,N.href),N.href}catch(t){if(t?.code!==`ENOENT`)throw H&&H.set(I,t),t}let W=n?.conditions?new Set(n.conditions):YM,q=C||N.href,Y=_normalizeBases(n?.from),X=n?.suffixes||[``],Z=n?.extensions?[``,...n.extensions]:[``],te;for(let t of Y){for(let n of X){let S=_join(q,n);S===`.`&&(S+=`/.`);for(let n of Z)if(te=_tryModuleResolve(S+n,t,W),te)break;if(te)break}if(te)break}if(!te){let S=Error(`Cannot resolve module "${t}" (from: ${Y.map(t=>_fmtPath(t)).join(`, `)})`);if(S.code=`ERR_MODULE_NOT_FOUND`,H&&H.set(I,S),n?.try)return;throw S}return H&&H.set(I,te.href),te.href}function resolveModulePath(t,n){let S=resolveModuleURL(t,n);if(!S||!S.startsWith(`file://`)&&n?.try)return;let C=fileURLToPath(S);return XM?_normalizeWinPath(C):C}function _tryModuleResolve(t,n,S){try{return moduleResolve(t,n,S)}catch{}}function _normalizeBases(t){let n=(Array.isArray(t)?t:[t]).flatMap(t=>_normalizeBase(t));return n.length===0?[pathToFileURL(`./`)]:n}function _normalizeBase(t){if(!t)return[];if(_isURL(t))return[t];if(typeof t!=`string`)return[];if(/^(?:node|data|http|https|file):/.test(t))return new URL(t);try{return t.endsWith(`/`)||statSync(t).isDirectory()?pathToFileURL(t+`/`):pathToFileURL(t)}catch{return[pathToFileURL(t+`/`),pathToFileURL(t)]}}function _fmtPath(t){try{return fileURLToPath(t)}catch{return t}}function _cacheKey(t,n){return JSON.stringify([t,(n?.conditions||[`node`,`import`]).sort(),n?.extensions,n?.from,n?.suffixes])}function _join(t,n){return!t||!n||n===`/`?t:(t.endsWith(`/`)?t:t+`/`)+(n.startsWith(`/`)?n.slice(1):n)}function _normalizeWinPath(t){return t.replace(/\\/g,`/`).replace(/^[a-z]:\//,t=>t.toUpperCase())}function _isURL(t){return t instanceof URL||t?.constructor?.name===`URL`}function _parseInput(t){if(typeof t==`string`){if(t.startsWith(`file:`)){let n=new URL(t);return{url:n,absolutePath:fileURLToPath(n)}}return bn(t)?{url:pathToFileURL(t),absolutePath:t}:/^(?:node|data|http|https):/.test(t)?{external:t}:vM.includes(t)&&!t.includes(`:`)?{external:`node:${t}`}:{specifier:t}}if(_isURL(t))return t.protocol===`file:`?{url:t,absolutePath:fileURLToPath(t)}:{external:t.href};throw TypeError("id must be a `string` or `URL`")}var 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=__esmMin(()=>{Md(),Hn(),jn(),Jd(),rn(),_M(),yu(),vM=`_http_agent._http_client._http_common._http_incoming._http_outgoing._http_server._stream_duplex._stream_passthrough._stream_readable._stream_transform._stream_wrap._stream_writable._tls_common._tls_wrap.assert.assert/strict.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.dns/promises.domain.events.fs.fs/promises.http.http2.https.inspector.inspector/promises.module.net.os.path.path/posix.path/win32.perf_hooks.process.punycode.querystring.readline.readline/promises.repl.stream.stream/consumers.stream/promises.stream/web.string_decoder.sys.timers.timers/promises.tls.trace_events.tty.url.util.util/types.v8.vm.wasi.worker_threads.zlib`.split(`.`),yM={}.hasOwnProperty,bM=/^([A-Z][a-z\d]*)+$/,xM=new Set([`string`,`function`,`number`,`object`,`Function`,`Object`,`boolean`,`bigint`,`symbol`]),SM=new Map,CM=`__node_internal_`,TM=hideStackFrames(function(t){let n=isErrorStackTraceLimitWritable();return n&&(wM=Error.stackTraceLimit,Error.stackTraceLimit=1/0),Error.captureStackTrace(t),n&&(Error.stackTraceLimit=wM),t}),createError(`ERR_INVALID_ARG_TYPE`,(t,n,S)=>{qd.ok(typeof t==`string`,`'name' must be a string`),Array.isArray(n)||(n=[n]);let C=`The `;if(t.endsWith(` argument`))C+=`${t} `;else{let n=t.includes(`.`)?`property`:`argument`;C+=`"${t}" ${n} `}C+=`must be `;let N=[],F=[],I=[];for(let t of n)qd.ok(typeof t==`string`,`All expected entries have to be of type string`),xM.has(t)?N.push(t.toLowerCase()):bM.exec(t)===null?(qd.ok(t!==`object`,`The value "object" should be written as "Object"`),I.push(t)):F.push(t);if(F.length>0){let t=N.indexOf(`object`);t!==-1&&(N.slice(t,1),F.push(`Object`))}return N.length>0&&(C+=`${N.length>1?`one of type`:`of type`} ${formatList(N,`or`)}`,(F.length>0||I.length>0)&&(C+=` or `)),F.length>0&&(C+=`an instance of ${formatList(F,`or`)}`,I.length>0&&(C+=` or `)),I.length>0&&(I.length>1?C+=`one of ${formatList(I,`or`)}`:(I[0]?.toLowerCase()!==I[0]&&(C+=`an `),C+=`${I[0]}`)),C+=`. Received ${determineSpecificType(S)}`,C},TypeError),EM=createError(`ERR_INVALID_MODULE_SPECIFIER`,(t,n,S)=>`Invalid module "${t}" ${n}${S?` imported from ${S}`:``}`,TypeError),DM=createError(`ERR_INVALID_PACKAGE_CONFIG`,(t,n,S)=>`Invalid package config ${t}${n?` while importing ${n}`:``}${S?`. ${S}`:``}`,Error),OM=createError(`ERR_INVALID_PACKAGE_TARGET`,(t,n,S,C=!1,N)=>{let F=typeof S==`string`&&!C&&S.length>0&&!S.startsWith(`./`);return n===`.`?(qd.ok(C===!1),`Invalid "exports" main target ${JSON.stringify(S)} defined in the package config ${t}package.json${N?` imported from ${N}`:``}${F?`; targets must start with "./"`:``}`):`Invalid "${C?`imports`:`exports`}" target ${JSON.stringify(S)} defined for '${n}' in the package config ${t}package.json${N?` imported from ${N}`:``}${F?`; targets must start with "./"`:``}`},Error),kM=createError(`ERR_MODULE_NOT_FOUND`,(t,n,S=!1)=>`Cannot find ${S?`module`:`package`} '${t}' imported from ${n}`,Error),createError(`ERR_NETWORK_IMPORT_DISALLOWED`,`import of '%s' by %s is not supported: %s`,Error),AM=createError(`ERR_PACKAGE_IMPORT_NOT_DEFINED`,(t,n,S)=>`Package import specifier "${t}" is not defined${n?` in package ${n||``}package.json`:``} imported from ${S}`,TypeError),jM=createError(`ERR_PACKAGE_PATH_NOT_EXPORTED`,(t,n,S)=>n===`.`?`No "exports" main defined in ${t}package.json${S?` imported from ${S}`:``}`:`Package subpath '${n}' is not defined by "exports" in ${t}package.json${S?` imported from ${S}`:``}`,Error),MM=createError(`ERR_UNSUPPORTED_DIR_IMPORT`,`Directory import '%s' is not supported resolving ES modules imported from %s`,Error),NM=createError(`ERR_UNSUPPORTED_RESOLVE_REQUEST`,`Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.`,TypeError),PM=createError(`ERR_UNKNOWN_FILE_EXTENSION`,(t,n)=>`Unknown file extension "${t}" for ${n}`,TypeError),createError(`ERR_INVALID_ARG_VALUE`,(t,n,S=`is invalid`)=>{let C=inspect(n);return C.length>128&&(C=`${C.slice(0,128)}...`),`The ${t.includes(`.`)?`property`:`argument`} '${t}' ${S}. Received ${C}`},TypeError),FM={}.hasOwnProperty,IM=new Map,LM={}.hasOwnProperty,RM={__proto__:null,".json":`json`,".cjs":`commonjs`,".cts":`commonjs`,".js":`module`,".ts":`module`,".mts":`module`,".mjs":`module`},zM={__proto__:null,"data:":getDataProtocolModuleFormat,"file:":getFileProtocolModuleFormat,"node:":()=>`builtin`},BM=RegExp.prototype[Symbol.replace],VM={}.hasOwnProperty,HM=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i,UM=/(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i,WM=/^\.|%|\\/,GM=/\*/g,KM=/%2f|%5c/i,qM=new Set,JM=/[/\\]{2}/,__name$1(fileExists$1,`fileExists`),YM=new Set([`node`,`import`]),XM=process.platform===`win32`,ZM=globalThis.__EXSOLVE_CACHE__||=new Map});async function findFile(t,n={}){let S=Array.isArray(t)?t:[t],C={...$M,...n},N=resolve(C.startingFrom),F=N[0]===`/`,I=N.split(`/`).filter(Boolean);if(S.includes(I.at(-1))&&await C.test(N))return N;F&&(I[0]=`/`+I[0]);let H=I.findIndex(t=>t.match(C.rootPattern));if(H===-1&&(H=0),C.reverse)for(let t=H+1;t<=I.length;t++)for(let n of S){let S=Kj(...I.slice(0,t),n);if(await C.test(S))return S}else for(let t=I.length;t>H;t--)for(let n of S){let S=Kj(...I.slice(0,t),n);if(await C.test(S))return S}throw Error(`Cannot find matching ${t} in ${C.startingFrom} or parent directories`)}function findNearestFile(t,n={}){return findFile(t,n)}function _resolvePath(t,n={}){return t instanceof URL||t.startsWith(`file://`)?normalize(fileURLToPath(t)):isAbsolute(t)?normalize(t):resolveModulePath(t,{...n,from:n.from||n.parent||n.url})}async function readPackageJSON(t,n={}){let S=await resolvePackageJSON(t,n),C=n.cache&&typeof n.cache!=`boolean`?n.cache:eN;if(n.cache&&C.has(S))return C.get(S);let N=await pd.readFile(S,`utf8`),F;try{F=n$2(N)}catch{F=r$1(N)}return C.set(S,F),F}async function resolvePackageJSON(t=process.cwd(),n={}){return findNearestFile(`package.json`,{...n,startingFrom:_resolvePath(t,n)})}var $M,eN,tN=__esmMin(()=>{Md(),Jj(),cM(),QM(),Hn(),hd(),$M={startingFrom:`.`,rootPattern:/^node_modules$/,reverse:!1,test:t=>{try{if(statSync(t).isFile())return!0}catch{}}},eN=new Map});function d(t,n){if(!n.includes(lN)&&t.hasOwnProperty(n))return[n];let S,C;for(let N of Object.keys(t))if(N.includes(lN)){let[t,F,I]=N.split(lN);if(I===void 0&&n.startsWith(t)&&n.endsWith(F)){let I=n.slice(t.length,-F.length||void 0);I&&(!S||m(S,N))&&(S=N,C=I)}}return[S,C]}var A,a,nN,rN,iN,aN,oN,sN,cN,f,lN,m,p,uN,v,dN=__esmMin(()=>{A=t=>typeof t==`object`&&!!t,a=(t,n)=>Object.assign(Error(`[${t}]: ${n}`),{code:t}),nN=`ERR_INVALID_PACKAGE_CONFIG`,rN=`ERR_INVALID_PACKAGE_TARGET`,iN=`ERR_PACKAGE_PATH_NOT_EXPORTED`,aN=/^\d+$/,oN=/^(\.{1,2}|node_modules)$/i,sN=/\/|\\/,cN=(t=>(t.Export=`exports`,t.Import=`imports`,t))(cN||{}),f=(t,n,S,C,N)=>{if(n==null)return[];if(typeof n==`string`){let[S,...C]=n.split(sN);if(S===`..`||C.some(t=>oN.test(t)))throw a(rN,`Invalid "${t}" target "${n}" defined in the package config`);return[N?n.replace(/\*/g,N):n]}if(Array.isArray(n))return n.flatMap(n=>f(t,n,S,C,N));if(A(n)){for(let F of Object.keys(n)){if(aN.test(F))throw a(nN,`Cannot contain numeric property keys`);if(F==="default"||C.includes(F))return f(t,n[F],S,C,N)}return[]}throw a(rN,`Invalid "${t}" target "${n}"`)},lN=`*`,m=(t,n)=>{let S=t.indexOf(lN),C=n.indexOf(lN);return S===C?n.length>t.length:C>S},p=t=>Object.keys(t).reduce((t,n)=>{let S=n===``||n[0]!==`.`;if(t===void 0||t===S)return S;throw a(nN,`"exports" cannot contain some keys starting with "." and some not`)},void 0),uN=/^\w+:/,v=(t,n,S)=>{if(!t)throw Error(`"exports" is required`);n=n===``?`.`:`./${n}`,(typeof t==`string`||Array.isArray(t)||A(t)&&p(t))&&(t={".":t});let[C,N]=d(t,n),F=f(cN.Export,t[C],n,S,N);if(F.length===0)throw a(iN,n===`.`?`No "exports" main defined`:`Package subpath '${n}' is not defined by "exports"`);for(let t of F)if(!t.startsWith(`./`)&&!uN.test(t))throw a(rN,`Invalid "exports" target "${t}" defined in the package config`);return F}});function h(t){return t.startsWith(`\\\\?\\`)?t:t.replace(/\\/g,`/`)}function Ne(t,n=!1){let S=t.length,C=0,N=``,F=0,I=16,H=0,W=0,q=0,Y=0,X=0;function _(n,S){let N=0,F=0;for(;N<n;){let n=t.charCodeAt(C);if(n>=48&&n<=57)F=F*16+n-48;else if(n>=65&&n<=70)F=F*16+n-65+10;else if(n>=97&&n<=102)F=F*16+n-97+10;else break;C++,N++}return N<n&&(F=-1),F}r(_,`scanHexDigits`);function v(t){C=t,N=``,F=0,I=16,X=0}r(v,`setPosition`);function p(){let n=C;if(t.charCodeAt(C)===48)C++;else for(C++;C<t.length&&R(t.charCodeAt(C));)C++;if(C<t.length&&t.charCodeAt(C)===46)if(C++,C<t.length&&R(t.charCodeAt(C)))for(C++;C<t.length&&R(t.charCodeAt(C));)C++;else return X=3,t.substring(n,C);let S=C;if(C<t.length&&(t.charCodeAt(C)===69||t.charCodeAt(C)===101))if(C++,(C<t.length&&t.charCodeAt(C)===43||t.charCodeAt(C)===45)&&C++,C<t.length&&R(t.charCodeAt(C))){for(C++;C<t.length&&R(t.charCodeAt(C));)C++;S=C}else X=3;return t.substring(n,S)}r(p,`scanNumber`);function L(){let n=``,N=C;for(;;){if(C>=S){n+=t.substring(N,C),X=2;break}let F=t.charCodeAt(C);if(F===34){n+=t.substring(N,C),C++;break}if(F===92){if(n+=t.substring(N,C),C++,C>=S){X=2;break}switch(t.charCodeAt(C++)){case 34:n+=`"`;break;case 92:n+=`\\`;break;case 47:n+=`/`;break;case 98:n+=`\b`;break;case 102:n+=`\f`;break;case 110:n+=`
|
|
773
773
|
`;break;case 114:n+=`\r`;break;case 116:n+=` `;break;case 117:let t=_(4);t>=0?n+=String.fromCharCode(t):X=4;break;default:X=5}N=C;continue}if(F>=0&&F<=31)if(J(F)){n+=t.substring(N,C),X=2;break}else X=6;C++}return n}r(L,`scanString`);function A(){if(N=``,X=0,F=C,W=H,Y=q,C>=S)return F=S,I=17;let n=t.charCodeAt(C);if(ee(n)){do C++,N+=String.fromCharCode(n),n=t.charCodeAt(C);while(ee(n));return I=15}if(J(n))return C++,N+=String.fromCharCode(n),n===13&&t.charCodeAt(C)===10&&(C++,N+=`
|
|
774
|
-
`),H++,q=C,I=14;switch(n){case 123:return C++,I=1;case 125:return C++,I=2;case 91:return C++,I=3;case 93:return C++,I=4;case 58:return C++,I=6;case 44:return C++,I=5;case 34:return C++,N=L(),I=10;case 47:let W=C-1;if(t.charCodeAt(C+1)===47){for(C+=2;C<S&&!J(t.charCodeAt(C));)C++;return N=t.substring(W,C),I=12}if(t.charCodeAt(C+1)===42){C+=2;let n=S-1,F=!1;for(;C<n;){let n=t.charCodeAt(C);if(n===42&&t.charCodeAt(C+1)===47){C+=2,F=!0;break}C++,J(n)&&(n===13&&t.charCodeAt(C)===10&&C++,H++,q=C)}return F||(C++,X=1),N=t.substring(W,C),I=13}return N+=String.fromCharCode(n),C++,I=16;case 45:if(N+=String.fromCharCode(n),C++,C===S||!R(t.charCodeAt(C)))return I=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return N+=p(),I=11;default:for(;C<S&&D(n);)C++,n=t.charCodeAt(C);if(F!==C){switch(N=t.substring(F,C),N){case`true`:return I=8;case`false`:return I=9;case`null`:return I=7}return I=16}return N+=String.fromCharCode(n),C++,I=16}}r(A,`scanNext`);function D(t){if(ee(t)||J(t))return!1;switch(t){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}r(D,`isUnknownContentCharacter`);function B(){let t;do t=A();while(t>=12&&t<=15);return t}return r(B,`scanNextNonTrivia`),{setPosition:v,getPosition:r(()=>C,`getPosition`),scan:n?B:A,getToken:r(()=>I,`getToken`),getTokenValue:r(()=>N,`getTokenValue`),getTokenOffset:r(()=>F,`getTokenOffset`),getTokenLength:r(()=>C-F,`getTokenLength`),getTokenStartLine:r(()=>W,`getTokenStartLine`),getTokenStartCharacter:r(()=>F-Y,`getTokenStartCharacter`),getTokenError:r(()=>X,`getTokenError`)}}function ee(t){return t===32||t===9}function J(t){return t===10||t===13}function R(t){return t>=48&&t<=57}function Pe(t,n=[],S=
|
|
775
|
-
`+` `.repeat(n)),Array(
|
|
776
|
-
`+` `.repeat(n)),Array(
|
|
777
|
-
`+` `.repeat(n)),Array(
|
|
778
|
-
`+` `.repeat(n)),(function(t){t.DEFAULT={allowTrailingComma:!1}})(xN||={}),r(Pe,`parse$1`),r(We,`visit`),(function(t){t[t.None=0]=`None`,t[t.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=4]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=6]=`InvalidCharacter`})(SN||={}),(function(t){t[t.OpenBraceToken=1]=`OpenBraceToken`,t[t.CloseBraceToken=2]=`CloseBraceToken`,t[t.OpenBracketToken=3]=`OpenBracketToken`,t[t.CloseBracketToken=4]=`CloseBracketToken`,t[t.CommaToken=5]=`CommaToken`,t[t.ColonToken=6]=`ColonToken`,t[t.NullKeyword=7]=`NullKeyword`,t[t.TrueKeyword=8]=`TrueKeyword`,t[t.FalseKeyword=9]=`FalseKeyword`,t[t.StringLiteral=10]=`StringLiteral`,t[t.NumericLiteral=11]=`NumericLiteral`,t[t.LineCommentTrivia=12]=`LineCommentTrivia`,t[t.BlockCommentTrivia=13]=`BlockCommentTrivia`,t[t.LineBreakTrivia=14]=`LineBreakTrivia`,t[t.Trivia=15]=`Trivia`,t[t.Unknown=16]=`Unknown`,t[t.EOF=17]=`EOF`})(CN||={}),wN=Pe,(function(t){t[t.InvalidSymbol=1]=`InvalidSymbol`,t[t.InvalidNumberFormat=2]=`InvalidNumberFormat`,t[t.PropertyNameExpected=3]=`PropertyNameExpected`,t[t.ValueExpected=4]=`ValueExpected`,t[t.ColonExpected=5]=`ColonExpected`,t[t.CommaExpected=6]=`CommaExpected`,t[t.CloseBraceExpected=7]=`CloseBraceExpected`,t[t.CloseBracketExpected=8]=`CloseBracketExpected`,t[t.EndOfFileExpected=9]=`EndOfFileExpected`,t[t.InvalidCommentToken=10]=`InvalidCommentToken`,t[t.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=14]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=16]=`InvalidCharacter`})(TN||={}),EN=r((t,n)=>wN(mN(n,t,`utf8`)),`readJsonc`),DN=Symbol(`implicitBaseUrl`),ON="${configDir}",kN=r(()=>{let{findPnpApi:t}=kl;return t&&t(process.cwd())},`getPnpApi`),AN=r((t,n,S,C)=>{let N=`resolveFromPackageJsonPath:${t}:${n}:${S}`;if(C!=null&&C.has(N))return C.get(N);let F=EN(t,C);if(!F)return;let I=n||`tsconfig.json`;if(!S&&F.exports)try{let[t]=v(F.exports,n,[`require`,`types`]);I=t}catch{return!1}else!n&&F.tsconfig&&(I=F.tsconfig);return I=An.join(t,`..`,I),C?.set(N,I),I},`resolveFromPackageJsonPath`),jN=`package.json`,MN=`tsconfig.json`,NN=r((t,n,S)=>{let C=t;if(t===`..`&&(C=An.join(C,MN)),t[0]===`.`&&(C=An.resolve(n,C)),An.isAbsolute(C)){if(pN(S,C)){if(hN(S,C).isFile())return C}else if(!C.endsWith(`.json`)){let t=`${C}.json`;if(pN(S,t))return t}return}let[N,...F]=t.split(`/`),I=N[0]===`@`?`${N}/${F.shift()}`:N,H=F.join(`/`),W=kN();if(W){let{resolveRequest:C}=W;try{if(I===t){let t=C(An.join(I,jN),n);if(t){let n=AN(t,H,!1,S);if(n&&pN(S,n))return n}}else{let S;try{S=C(t,n,{extensions:[`.json`]})}catch{S=C(An.join(t,MN),n)}if(S)return S}}catch{}}let q=gN(An.resolve(n),An.join(`node_modules`,I),S);if(!q||!hN(S,q).isDirectory())return;let Y=An.join(q,jN);if(pN(S,Y)){let t=AN(Y,H,!1,S);if(t===!1)return;if(t&&pN(S,t)&&hN(S,t).isFile())return t}let X=An.join(q,H),Z=X.endsWith(`.json`);if(!Z){let t=`${X}.json`;if(pN(S,t))return t}if(pN(S,X)){if(hN(S,X).isDirectory()){let t=An.join(X,jN);if(pN(S,t)){let n=AN(t,``,!0,S);if(n&&pN(S,n))return n}let n=An.join(X,MN);if(pN(S,n))return n}else if(Z)return X}},`resolveExtendsPath`),PN=r((t,n)=>vN(An.relative(t,n)),`pathRelative`),FN=[`files`,`include`,`exclude`],IN=r((t,n,S)=>{let C=An.join(n,S);return h(An.relative(t,C))||`./`},`resolveAndRelativize`),LN=r((t,n,S)=>{let C=An.relative(t,n);return C?h(`${C}/${S.startsWith(`./`)?S.slice(2):S}`):S},`prefixPattern`),RN=r((t,n,S,C)=>{let N=NN(t,n,C);if(!N)throw Error(`File '${t}' not found.`);if(S.has(N))throw Error(`Circularity detected while resolving configuration: ${N}`);S.add(N);let F=An.dirname(N),I=BN(N,C,S);delete I.references;let{compilerOptions:H}=I;if(H){let{baseUrl:t}=H;t&&!t.startsWith(ON)&&(H.baseUrl=IN(n,F,t));let{outDir:S}=H;S&&!S.startsWith(ON)&&(H.outDir=IN(n,F,S));let{declarationDir:C}=H;C&&!C.startsWith(ON)&&(H.declarationDir=IN(n,F,C));let{rootDir:N}=H;N&&!N.startsWith(ON)&&(H.rootDir=IN(n,F,N));let{rootDirs:I}=H;I&&(H.rootDirs=I.map(t=>t.startsWith(ON)?t:IN(n,F,t)));let{typeRoots:W}=H;W&&(H.typeRoots=W.map(t=>t.startsWith(ON)?t:IN(n,F,t)))}for(let t of FN){let S=I[t];S&&(I[t]=S.map(t=>t.startsWith(ON)?t:LN(n,F,t)))}return I},`resolveExtends`),zN=[`outDir`,`declarationDir`],BN=r((t,n,S=new Set)=>{let C;try{C=EN(t,n)||{}}catch{throw Error(`Cannot resolve tsconfig at path: ${t}`)}if(typeof C!=`object`)throw SyntaxError(`Failed to parse tsconfig at: ${t}`);let N=An.dirname(t);if(C.compilerOptions){let{compilerOptions:t}=C;t.paths&&!t.baseUrl&&(t[DN]=N)}if(C.extends){let t=Array.isArray(C.extends)?C.extends:[C.extends];delete C.extends;for(let F of t.reverse()){let t=RN(F,N,new Set(S),n),I={...t,...C,compilerOptions:{...t.compilerOptions,...C.compilerOptions}};t.watchOptions&&(I.watchOptions={...t.watchOptions,...C.watchOptions}),C=I}}if(C.compilerOptions){let{compilerOptions:t}=C;for(let n of[`baseUrl`,`rootDir`]){let S=t[n];if(S&&!S.startsWith(ON)){let C=An.resolve(N,S);t[n]=PN(N,C)}}for(let n of zN){let S=t[n];S&&(Array.isArray(C.exclude)||(C.exclude=zN.map(n=>t[n]).filter(Boolean)),S.startsWith(ON)||(S=vN(S)),t[n]=S)}}else C.compilerOptions={};if(C.include&&=C.include.map(h),C.files&&=C.files.map(t=>t.startsWith(ON)?t:vN(t)),C.watchOptions){let{watchOptions:t}=C;t.excludeDirectories&&=t.excludeDirectories.map(t=>h(An.resolve(N,t))),t.excludeFiles&&=t.excludeFiles.map(t=>h(An.resolve(N,t))),t.watchFile&&=t.watchFile.toLowerCase(),t.watchDirectory&&=t.watchDirectory.toLowerCase(),t.fallbackPolling&&=t.fallbackPolling.toLowerCase()}return C},`_parseTsconfig`),VN=r((t,n)=>{if(t.startsWith(ON))return h(An.join(n,t.slice(12)))},`interpolateConfigDir`),HN=[`outDir`,`declarationDir`,`outFile`,`rootDir`,`baseUrl`,`tsBuildInfoFile`],UN=r(t=>{if(t.strict)for(let n of[`noImplicitAny`,`noImplicitThis`,`strictNullChecks`,`strictFunctionTypes`,`strictBindCallApply`,`strictPropertyInitialization`,`strictBuiltinIteratorReturn`,`alwaysStrict`,`useUnknownInCatchVariables`])t[n]===void 0&&(t[n]=!0);if(t.composite&&(t.declaration??=!0,t.incremental??=!0),t.target){let n=t.target.toLowerCase();n===`es2015`&&(n=`es6`),t.target=n,n===`esnext`&&(t.module??=`es6`,t.useDefineForClassFields??=!0),(n===`es6`||n===`es2016`||n===`es2017`||n===`es2018`||n===`es2019`||n===`es2020`||n===`es2021`||n===`es2022`||n===`es2023`||n===`es2024`)&&(t.module??=`es6`),(n===`es2022`||n===`es2023`||n===`es2024`)&&(t.useDefineForClassFields??=!0)}if(t.module){let n=t.module.toLowerCase();if(n===`es2015`&&(n=`es6`),t.module=n,(n===`es6`||n===`es2020`||n===`es2022`||n===`esnext`||n===`none`||n===`system`||n===`umd`||n===`amd`)&&(t.moduleResolution??=`classic`),n===`system`&&(t.allowSyntheticDefaultImports??=!0),(n===`node16`||n===`node18`||n===`node20`||n===`nodenext`||n===`preserve`)&&(t.esModuleInterop??=!0,t.allowSyntheticDefaultImports??=!0),(n===`node16`||n===`node18`||n===`node20`||n===`nodenext`)&&(t.moduleDetection??=`force`),n===`node16`&&(t.target??=`es2022`,t.moduleResolution??=`node16`),n===`node18`&&(t.target??=`es2022`,t.moduleResolution??=`node16`),n===`node20`&&(t.target??=`es2023`,t.moduleResolution??=`node16`,t.resolveJsonModule??=!0),n===`nodenext`&&(t.target??=`esnext`,t.moduleResolution??=`nodenext`,t.resolveJsonModule??=!0),n===`node16`||n===`node18`||n===`node20`||n===`nodenext`){let n=t.target;(n===`es3`||n===`es2022`||n===`es2023`||n===`es2024`||n===`esnext`)&&(t.useDefineForClassFields??=!0)}n===`preserve`&&(t.moduleResolution??=`bundler`)}if(t.moduleResolution){let n=t.moduleResolution.toLowerCase();n===`node`&&(n=`node10`),t.moduleResolution=n,(n===`node16`||n===`nodenext`||n===`bundler`)&&(t.resolvePackageJsonExports??=!0,t.resolvePackageJsonImports??=!0),n===`bundler`&&(t.allowSyntheticDefaultImports??=!0,t.resolveJsonModule??=!0)}t.jsx&&=t.jsx.toLowerCase(),t.moduleDetection&&=t.moduleDetection.toLowerCase(),t.importsNotUsedAsValues&&=t.importsNotUsedAsValues.toLowerCase(),t.newLine&&=t.newLine.toLowerCase(),t.esModuleInterop&&(t.allowSyntheticDefaultImports??=!0),t.verbatimModuleSyntax&&(t.isolatedModules??=!0,t.preserveConstEnums??=!0),t.isolatedModules&&(t.preserveConstEnums??=!0),t.rewriteRelativeImportExtensions&&(t.allowImportingTsExtensions??=!0),t.lib&&=t.lib.map(t=>t.toLowerCase()),t.checkJs&&(t.allowJs??=!0)},`normalizeCompilerOptions`),WN=r((t,n=new Map)=>{let S=An.resolve(t),C=BN(S,n),N=An.dirname(S),{compilerOptions:F}=C;if(F){for(let t of HN){let n=F[t];if(n){let S=VN(n,N);F[t]=S?PN(N,S):n}}for(let t of[`rootDirs`,`typeRoots`]){let n=F[t];n&&(F[t]=n.map(t=>{let n=VN(t,N);return n?PN(N,n):vN(t)}))}let{paths:t}=F;if(t)for(let n of Object.keys(t))t[n]=t[n].map(t=>VN(t,N)??t);UN(F)}for(let t of FN){let n=C[t];n&&(C[t]=n.map(t=>VN(t,N)??t))}return C},`parseTsconfig`),GN=Object.defineProperty,KN=r((t,n)=>GN(t,`name`,{value:n,configurable:!0}),`s`),qN=KN(t=>{let n=``;for(let S=0;S<t.length;S+=1){let C=t[S],N=C.toUpperCase();n+=C===N?C.toLowerCase():N}return n},`invertCase`),JN=new Map,YN=KN((t,n)=>{let S=An.join(t,`.is-fs-case-sensitive-test-${process.pid}`);try{return n.writeFileSync(S,``),!n.existsSync(qN(S))}finally{try{n.unlinkSync(S)}catch{}}},`checkDirectoryCaseWithWrite`),XN=KN((t,n,S)=>{try{return YN(t,S)}catch(t){if(n===void 0)return YN(Eg.tmpdir(),S);throw t}},`checkDirectoryCaseWithFallback`),ZN=KN((t,n=jd,S=!0)=>{let C=t??process.cwd();if(S&&JN.has(C))return JN.get(C);let N,F=qN(C);return N=F!==C&&n.existsSync(C)?!n.existsSync(F):XN(C,t,n),S&&JN.set(C,N),N},`isFsCaseSensitive`),{join:QN}=An.posix,$N={ts:[`.ts`,`.tsx`,`.d.ts`],cts:[`.cts`,`.d.cts`],mts:[`.mts`,`.d.mts`]},eP=r(t=>{let n=[...$N.ts],S=[...$N.cts],C=[...$N.mts];return t!=null&&t.allowJs&&(n.push(`.js`,`.jsx`),S.push(`.cjs`),C.push(`.mjs`)),[...n,...S,...C]},`getSupportedExtensions`),tP=r(t=>{let n=[];if(!t)return n;let{outDir:S,declarationDir:C}=t;return S&&n.push(S),C&&n.push(C),n},`getDefaultExcludeSpec`),nP=r(t=>t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),`escapeForRegexp`),rP=`(?!(${[`node_modules`,`bower_components`,`jspm_packages`].join(`|`)})(/|$))`,iP=/(?:^|\/)[^.*?]+$/,aP=`**/*`,oP=`[^/]`,sP=`[^./]`,cP=process.platform===`win32`,lP=r(({config:t,path:n},S=ZN())=>{if(`extends`in t)throw Error(`tsconfig#extends must be resolved. Use getTsconfig or parseTsconfig to resolve it.`);if(!An.isAbsolute(n))throw Error(`The tsconfig path must be absolute`);cP&&(n=h(n));let C=An.dirname(n),{files:N,include:F,exclude:I,compilerOptions:H}=t,W=r(t=>An.isAbsolute(t)?t:QN(C,t),`resolvePattern`),q=N?.map(W),Y=eP(H),X=S?``:`i`,Z=(I||tP(H)).map(t=>{let n=W(t),S=nP(n).replaceAll(String.raw`\*\*/`,`(.+/)?`).replaceAll(String.raw`\*`,`${oP}*`).replaceAll(String.raw`\?`,oP);return RegExp(`^${S}($|/)`,X)}),te=N||F?F:[aP],ne=te?te.map(t=>{let n=W(t);iP.test(n)&&(n=QN(n,aP));let S=nP(n).replaceAll(String.raw`/\*\*`,`(/${rP}${sP}${oP}*)*?`).replaceAll(/(\/)?\\\*/g,(t,n)=>{let S=`(${sP}|(\\.(?!min\\.js$))?)*`;return n?`/${rP}${sP}${S}`:S}).replaceAll(/(\/)?\\\?/g,(t,n)=>{let S=oP;return n?`/${rP}${S}`:S});return RegExp(`^${S}$`,X)}):void 0;return n=>{if(!An.isAbsolute(n))throw Error(`filePath must be absolute`);if(cP&&(n=h(n)),q!=null&&q.includes(n)||!(!Y.some(t=>n.endsWith(t))||Z.some(t=>t.test(n)))&&ne&&ne.some(t=>t.test(n)))return t}},`createFilesMatcher`),uP=r((t,n,S)=>{let C=An.resolve(t),N=h(t);for(;;){let t=gN(N,n,S);if(!t)return;let F=An.resolve(t),I=WN(F,S),H={path:h(F),config:I};if(lP(H)(C))return H;let W=An.dirname(t),q=An.dirname(W);if(q===W)return;N=q}},`findConfigApplicable`),dP=r((t=process.cwd(),n=`tsconfig.json`,S=new Map,C=!1)=>C?uP(t,n,S)?.path:gN(h(t),n,S),`findTsconfig`),fP=r((t=process.cwd(),n=`tsconfig.json`,S=new Map,C=!1)=>{if(!C){let C=dP(t,n,S);return C?{path:C,config:WN(C,S)}:null}return uP(t,n,S)??null},`getTsconfig`),pP=/\*/g,mP=r((t,n)=>{let S=t.match(pP);if(S&&S.length>1)throw Error(n)},`assertStarCount`),hP=r(t=>{if(t.includes(`*`)){let[n,S]=t.split(`*`);return{prefix:n,suffix:S}}return t},`parsePattern`),gP=r(({prefix:t,suffix:n},S)=>S.startsWith(t)&&S.endsWith(n),`isPatternMatch`),_P=r((t,n,S)=>Object.entries(t).map(([t,C])=>(mP(t,`Pattern '${t}' can have at most one '*' character.`),{pattern:hP(t),substitutions:C.map(C=>{if(mP(C,`Substitution '${C}' in pattern '${t}' can have at most one '*' character.`),!n&&!_N.test(C)&&!An.isAbsolute(C))throw Error(`Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?`);return An.resolve(S,C)})})),`parsePaths`),r(t=>{let{compilerOptions:n}=t.config;if(!n)return null;let{baseUrl:S,paths:C}=n;if(!S&&!C)return null;let N=DN in n&&n[DN],F=An.resolve(An.dirname(t.path),S||N||`.`),I=C?_P(C,S,F):[];return t=>{if(_N.test(t))return[];let n=[];for(let S of I){if(S.pattern===t)return S.substitutions.map(h);typeof S.pattern!=`string`&&n.push(S)}let C,N=-1;for(let S of n)gP(S.pattern,t)&&S.pattern.prefix.length>N&&(N=S.pattern.prefix.length,C=S);if(!C)return S?[h(An.join(F,t))]:[];let H=t.slice(C.pattern.prefix.length,t.length-C.pattern.suffix.length);return C.substitutions.map(t=>h(t.replace(`*`,H)))}},`createPathsMatcher`)});function workspacesForChangedFiles(t,n){let S=new Set,C=[],N={children:new Map};for(let n of t){if(n.relativeLocation===`.`||n.relativeLocation===``)continue;let t=n.relativeLocation.split(`/`).filter(Boolean),S=N;for(let n of t){let t=S.children.get(n);t||(t={children:new Map},S.children.set(n,t)),S=t}S.ws=n.name}for(let t of n){if(!t)continue;let n=t.replace(/\\/g,`/`).split(`/`).filter(Boolean),F=N,I;for(let t of n){if(F=F.children.get(t),!F)break;F.ws&&(I=F.ws)}I?S.add(I):C.push(t)}return{matched:S,unmatched:C}}var yP=__esmMin(()=>{});function expandPattern(t,n){let S=n.split(`/`).filter(Boolean),C=[vn(t)];for(let t of S){let n=[];for(let S of C)if(t===`*`){let t=[];try{t=readdirSync(S)}catch{continue}for(let C of t){if(C.startsWith(`.`))continue;let t=xn(S,C);try{statSync(t).isDirectory()&&n.push(t)}catch{}}}else if(t.includes(`*`)){let C=globToRegex$1(t),N=[];try{N=readdirSync(S)}catch{continue}for(let t of N){if(t.startsWith(`.`)||!C.test(t))continue;let N=xn(S,t);try{statSync(N).isDirectory()&&n.push(N)}catch{}}}else{let C=xn(S,t);if(existsSync(C))try{statSync(C).isDirectory()&&n.push(C)}catch{}}C=n}return C}function globToRegex$1(t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`);return RegExp(`^${n}$`)}var bP=__esmMin(()=>{Md(),jn(),__name$1(globToRegex$1,`globToRegex`)});function discoverWorkspaces(t,n={}){let S=xn(t,`package.json`),C=existsSync(S);if(!C&&!n.patterns)throw Error(`@gjsify/workspace: no package.json at ${t}`);let N=C?JSON.parse(readFileSync(S,`utf-8`)):{},F=n.patterns??extractWorkspacePatterns(N),I=F.filter(t=>!t.startsWith(`!`)),H=F.filter(t=>t.startsWith(`!`)).map(t=>globToRegex$1(t.slice(1))),W=[],q=new Set;n.includeRoot&&N.name&&(W.push({location:t,relativeLocation:`.`,name:N.name,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}),q.add(t));for(let n of I)for(let S of expandPattern(t,n)){if(q.has(S))continue;let n=Sn(t,S).split(On).join(`/`);if(H.some(t=>t.test(n)))continue;let C=xn(S,`package.json`);if(!existsSync(C))continue;let N;try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{continue}N.name&&(q.add(S),W.push({location:S,relativeLocation:n,name:N.name,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}))}return W.sort((t,n)=>t.relativeLocation.localeCompare(n.relativeLocation)),W}function filterWorkspaces(t,n){let S=n.include?.map(globToRegex$1),C=n.exclude?.map(globToRegex$1);return t.filter(t=>!(n.noPrivate&&t.private||S&&S.length>0&&!S.some(n=>n.test(t.name))||C&&C.some(n=>n.test(t.name))))}function extractWorkspacePatterns(t){let n=t.workspaces;return n?Array.isArray(n)?n:n.packages??[]:[]}function indexByName(t){let n=new Map;for(let S of t)n.set(S.name,S);return n}var xP=__esmMin(()=>{bP(),Md(),jn()});function parse(t){try{return new SemVer(t)}catch{return null}}function compare(t,n){let S=t instanceof SemVer?t:new SemVer(t),C=n instanceof SemVer?n:new SemVer(n);return S.compare(C)}function satisfies(t,n){let S=n instanceof wP?n:new wP(n),C=t instanceof SemVer?t:parse(String(t));return C?S.test(C):!1}function maxSatisfying(t,n){let S=n instanceof wP?n:new wP(n),C=null;for(let n of t){let t=parse(n);!t||!S.test(t)||(C===null||t.compare(C)>0)&&(C=t)}return C?C.version:null}function validRange(t){try{return new wP(t).format()}catch{return null}}function testComparator(t,n){if(t.semver===null)return!0;let S=n.compare(t.semver);switch(t.operator){case``:case`=`:return S===0;case`<`:return S<0;case`<=`:return S<=0;case`>`:return S>0;case`>=`:return S>=0}}function formatComparator(t){return t.semver===null?`*`:`${t.operator}${t.semver.version}`}function parseRangePart(t){let n=t.trim();if(n===``||n===`*`||n.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=n.match(/^\s*(\S+)\s+-\s+(\S+)\s*$/);if(S)return hyphenRange(S[1],S[2]);let C=n.replace(/(<=|>=|<|>|=)\s+(?=\S)/g,`$1`).split(/\s+/),N=[];for(let t of C)N.push(...parseSimple(t));return N}function parseSimple(t){if(t===`*`||t===``||t.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];if(t.startsWith(`^`))return caretRange(t.slice(1));if(t.startsWith(`~`))return tildeRange(t.slice(1).replace(/^>/,``));let n=t.match(/^(<=|>=|<|>|=)\s*(.+)$/);if(n){let t=n[1];return primitiveRange(t,n[2])}return partialRange(t)}function parsePartial(t){let n=t.trim().replace(/^v/,``);if(n===``||n===`*`)return{major:null,minor:null,patch:null,pre:``,build:``};let S=``,C=``,N=n,F=N.indexOf(`+`);F>=0&&(C=N.slice(F+1),N=N.slice(0,F));let I=N.indexOf(`-`);I>=0&&(S=N.slice(I+1),N=N.slice(0,I));let H=N.split(`.`),xr=n=>{if(n===void 0||n===``||n===`x`||n===`X`||n===`*`)return null;if(!/^\d+$/.test(n))throw TypeError(`Invalid partial version: ${t}`);return Number(n)};return{major:xr(H[0]),minor:xr(H[1]),patch:xr(H[2]),pre:S,build:C}}function partialToVersion(t){return`${t.major??0}.${t.minor??0}.${t.patch??0}${t.pre?`-${t.pre}`:``}${t.build?`+${t.build}`:``}`}function partialRange(t){let n=parsePartial(t);return n.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:n.minor===null?[{operator:`>=`,semver:new SemVer(`${n.major}.0.0`)},{operator:`<`,semver:new SemVer(`${n.major+1}.0.0`)}]:n.patch===null?[{operator:`>=`,semver:new SemVer(`${n.major}.${n.minor}.0`)},{operator:`<`,semver:new SemVer(`${n.major}.${n.minor+1}.0`)}]:[{operator:`=`,semver:new SemVer(partialToVersion(n))}]}function caretRange(t){let n=parsePartial(t);if(n.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=`${n.major}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}`,C;return C=n.major>0||n.minor===null?`${n.major+1}.0.0`:n.minor>0||n.patch===null?`0.${n.minor+1}.0`:`0.0.${n.patch+1}`,[{operator:`>=`,semver:new SemVer(S)},{operator:`<`,semver:new SemVer(C)}]}function tildeRange(t){let n=parsePartial(t);if(n.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=`${n.major}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}`,C=n.minor===null?`${n.major+1}.0.0`:`${n.major}.${n.minor+1}.0`;return[{operator:`>=`,semver:new SemVer(S)},{operator:`<`,semver:new SemVer(C)}]}function primitiveRange(t,n){let S=parsePartial(n);return S.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:t===`=`||t===``?partialRange(n):t===`>`?S.minor===null?[{operator:`>=`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`>`,semver:new SemVer(partialToVersion(S))}]:t===`<`?S.minor===null?[{operator:`<`,semver:new SemVer(`${S.major}.0.0`)}]:S.patch===null?[{operator:`<`,semver:new SemVer(`${S.major}.${S.minor}.0`)}]:[{operator:`<`,semver:new SemVer(partialToVersion(S))}]:t===`>=`?[{operator:`>=`,semver:new SemVer(partialToVersion(S))}]:S.minor===null?[{operator:`<`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`<`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`<=`,semver:new SemVer(partialToVersion(S))}]}function hyphenRange(t,n){let S=parsePartial(t),C=parsePartial(n),N=S.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`)},F;return F=C.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:C.minor===null?{operator:`<`,semver:new SemVer(`${C.major+1}.0.0`)}:C.patch===null?{operator:`<`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}:{operator:`<=`,semver:new SemVer(`${C.major}.${C.minor}.${C.patch}${C.pre?`-${C.pre}`:``}`)},[N,F]}var SP,CP,SemVer,wP,TP=__esmMin(()=>{SP=/^(0|[1-9]\d*)$/,CP=/^(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,SemVer=class{major;minor;patch;prerelease;build;version;constructor(t){let n=String(t).trim().replace(/^v/,``),S=CP.exec(n);if(!S)throw TypeError(`Invalid Version: ${t}`);this.major=Number(S[1]),this.minor=Number(S[2]),this.patch=Number(S[3]),this.prerelease=S[4]?S[4].split(`.`).map(t=>SP.test(t)?Number(t):t):[],this.build=S[5]?S[5].split(`.`):[],this.version=`${this.major}.${this.minor}.${this.patch}`+(this.prerelease.length?`-${this.prerelease.join(`.`)}`:``)+(this.build.length?`+${this.build.join(`.`)}`:``)}compare(t){return this.major===t.major?this.minor===t.minor?this.patch===t.patch?this.comparePre(t):this.patch<t.patch?-1:1:this.minor<t.minor?-1:1:this.major<t.major?-1:1}comparePre(t){let n=this.prerelease,S=t.prerelease;if(n.length===0&&S.length===0)return 0;if(n.length===0)return 1;if(S.length===0)return-1;for(let t=0;;t++){let C=n[t],N=S[t];if(C===void 0&&N===void 0)return 0;if(N===void 0)return 1;if(C===void 0)return-1;if(C===N)continue;let F=typeof C==`number`,I=typeof N==`number`;return F&&!I?-1:!F&&I?1:C<N?-1:1}}toString(){return this.version}},wP=class Range{raw;set;constructor(t){if(t instanceof Range){this.raw=t.raw,this.set=t.set;return}this.raw=String(t).trim();let n=this.raw.split(/\s*\|\|\s*/),S=[];for(let t of n){let n=parseRangePart(t);if(n.length===0)throw TypeError(`Invalid range: ${this.raw}`);S.push(n)}if(S.length===0)throw TypeError(`Invalid range: ${this.raw}`);this.set=S}test(t){let n=t instanceof SemVer?t:parse(String(t));if(!n)return!1;for(let t of this.set)if(t.every(t=>testComparator(t,n))){if(n.prerelease.length>0&&!t.some(t=>t.semver!==null&&t.semver.prerelease.length>0&&t.semver.major===n.major&&t.semver.minor===n.minor&&t.semver.patch===n.patch))continue;return!0}return!1}format(){return this.set.map(t=>t.map(formatComparator).join(` `)).join(` || `)}toString(){return this.format()}}});function registryRangeOf(t){let n=t.trim();return/[:/\\]/.test(n)||n.toLowerCase()===`latest`||validRange(n)===null?null:n}function releaseVersionOf(t){let n=parse(t);return n===null?t:`${n.major}.${n.minor}.${n.patch}`}function buildDependencyGraph(t,n={}){let S=n.includeDev??!1,C=n.includePeer??!1,N=n.includeOptional??!0,F=indexByName(t),I=new Map,H=[];for(let n of t){let t=new Set,W=[],q=n.manifest;for(let I of[q.dependencies,S?q.devDependencies:void 0,C?q.peerDependencies:void 0,N?q.optionalDependencies:void 0])if(I)for(let[S,C]of Object.entries(I)){if(typeof C!=`string`)continue;let N=F.get(S);if(!N)continue;if(C.startsWith(`workspace:`)){t.add(S);continue}let I=registryRangeOf(C);I!==null&&(satisfies(releaseVersionOf(N.version),I)?t.add(S):W.push({from:n.name,to:S,spec:C,version:N.version}))}for(let n of W)t.has(n.to)||H.push(n);I.set(n.name,t)}return{edges:I,byName:F,unlinked:H}}function topologicalSort(t){let n=new Map,S=new Map;for(let C of t.edges.keys())n.set(C,new Set),S.set(C,0);for(let[C,N]of t.edges)for(let t of N)n.has(t)&&(n.get(t).add(C),S.set(C,(S.get(C)??0)+1));let C=[];for(let[t,n]of S)n===0&&C.push(t);C.sort();let N=[];for(;C.length>0;){let F=C.shift(),I=t.byName.get(F);I&&N.push(I);let H=n.get(F);if(H){let t=[];for(let n of H){let C=(S.get(n)??1)-1;S.set(n,C),C===0&&t.push(n)}t.sort(),C.push(...t)}}if(N.length!==S.size){let t=[...S.entries()].filter(([,t])=>t>0).map(([t])=>t);throw Error(`@gjsify/workspace: dependency cycle detected involving ${t.join(`, `)}`)}return N}function buildReverseDependencyGraph(t,n={}){let S=buildDependencyGraph(t,n),C=new Map;for(let t of S.edges.keys())C.set(t,new Set);for(let[t,n]of S.edges)for(let S of n){let n=C.get(S);n&&n.add(t)}return{edges:C,byName:S.byName,unlinked:S.unlinked}}function affectedClosure(t,n){let S=new Set,C=[];for(let N of n)t.byName.has(N)&&(S.has(N)||(S.add(N),C.push(N)));for(;C.length>0;){let n=C.shift(),N=t.edges.get(n);if(N)for(let t of N)S.has(t)||(S.add(t),C.push(t))}return S}var EP=__esmMin(()=>{xP(),TP()}),DP=__esmMin(()=>{yP(),xP(),EP(),jn()});function stripBom(t){return t.charCodeAt(0)===65279?t.slice(1):t}function readPackageJson$2(t){try{return JSON.parse(stripBom(readFileSync(t,`utf-8`)))}catch{return null}}var OP=__esmMin(()=>{Md(),__name$1(readPackageJson$2,`readPackageJson`)});function findWorkspaceRoot(t){let n=t;for(let S=0;S<12;S++){let S=xn(n,`package.json`);if(existsSync(S)&&readPackageJson$2(S)?.workspaces!==void 0)try{let S=discoverWorkspaces(n);if(n===t||S.some(n=>n.location===t))return n}catch{}let C=vn(n,`..`);if(C===n)break;n=C}return null}var kP=__esmMin(()=>{Md(),jn(),DP(),OP()});function resolveNpmPackage(t,n={}){let S=n.cwd??process.cwd(),C=process.env.GJSIFY_NODE_PATH;if(C)for(let n of C.split(kn).filter(Boolean)){let S=tryResolveFromDir(t,vn(n));if(S)return S}let N=tryResolveFromDir(t,S);if(N)return N;let F=findWorkspaceRoot(S);if(F&&F!==S){let n=tryResolveFromDir(t,F);if(n)return n}if(n.bundleUrl)try{return createRequire(n.bundleUrl).resolve(t)}catch{}let I=vn(S,`..`);for(let n=0;n<8;n++){let n=tryResolveFromDir(t,I);if(n)return n;let S=vn(I,`..`);if(S===I)break;I=S}return null}function tryResolveFromDir(t,n){try{let S=pathToFileURL(xn(n,`__gjsify_resolve__.js`)).href;return createRequire(S).resolve(t)}catch{return null}}function resolveInstalledPackage(t,n={}){let S=n.resolve??((t,S)=>S===`project`?resolveNpmPackage(t,{cwd:n.cwd,bundleUrl:n.bundleUrl}):tryResolveFromFile(t,AP)),C=S(t,`project`);if(C===null)return null;let N=S(t,`nowhere`);return N!==null&&N===C?null:C}function tryResolveFromFile(t,n){try{return createRequire(pathToFileURL(n).href).resolve(t)}catch{return null}}var AP,jP=__esmMin(()=>{Al(),Hn(),Dg(),jn(),kP(),AP=xn(tmpdir(),`.gjsify-nonexistent-control-anchor`,`__gjsify_resolve__.js`)});function giLibraryDirsForTypelibDir(t){let n=NP(t);return MP(t)===`girepository-1.0`?[n]:[t,n]}function splitSearchPath(t,n=`:`){return(t??``).split(n).filter(Boolean)}function isDirectory$1(t){try{return statSync(t).isDirectory()}catch{return!1}}function pkgConfigSearchDirs(t){if(LP)return LP;let n=splitSearchPath(t.PKG_CONFIG_PATH),S=spawnSync(`pkg-config`,[`--variable=pc_path`,`pkg-config`],{encoding:`utf8`,timeout:1e4});return!S.error&&S.status===0&&n.push(...splitSearchPath(String(S.stdout).trim())),LP=n,n}function systemGiLibraryDirs({platform:t=process.platform,env:n=process.env,existsDir:S=isDirectory$1,searchDirs:C=pkgConfigSearchDirs}={}){let N=FP[t];if(!N)return[];let F=[],add=t=>{t&&t!==`/`&&!F.includes(t)&&F.push(t)};for(let t of splitSearchPath(n.GI_TYPELIB_PATH))for(let n of giLibraryDirsForTypelibDir(t))S(n)&&add(n);let I=[];for(let t of C(n))MP(t)===`pkgconfig`&&I.push(NP(t));I.push(...N);for(let t of I)S(PP(t,`girepository-1.0`))&&add(t);return F}function dyldDefaultFallbackDirs(t=process.env){let n=t.HOME;return[...n?[`${n}/lib`]:[],`/usr/local/lib`,`/lib`,`/usr/lib`]}function composeDyldFallback(t,n=process.env){return[...new Set([...t,...splitSearchPath(n.DYLD_FALLBACK_LIBRARY_PATH),...dyldDefaultFallbackDirs(n)])].join(`:`)}var MP,NP,PP,FP,IP,LP,RP=__esmMin(()=>{w_(),Md(),jn(),{basename:MP,dirname:NP,join:PP}=un,FP={darwin:[`/opt/homebrew/lib`,`/usr/local/lib`,`/opt/local/lib`]},IP=`girepository-1.0`,LP=null,__name$1(isDirectory$1,`isDirectory`)});function isDirectory(t){try{return statSync(t).isDirectory()}catch{return!1}}function subdirectories(t){try{return readdirSync(t,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function systemGiTypelibDirs({platform:t=process.platform,env:n=process.env,existsDir:S=isDirectory,listDirs:C=subdirectories,searchDirs:N=pkgConfigSearchDirs}={}){let{join:F,dirname:I,basename:H}=t===`win32`?fn:un,W=t===`win32`?`;`:`:`,q=[],add=t=>{t&&!q.includes(t)&&q.push(t)};for(let t of splitSearchPath(n.GI_TYPELIB_PATH,W))S(t)&&add(t);let Y=[];for(let t of N(n))H(t)===`pkgconfig`&&Y.push(I(t));if(t===`linux`){Y.push(...zP);for(let t of BP)for(let n of C(t))Y.push(F(t,n))}else if(t===`darwin`)Y.push(...systemGiLibraryDirs({platform:t,env:n,existsDir:S,searchDirs:N}));else if(t===`win32`)for(let t of splitSearchPath(n.PATH,W))H(t).toLowerCase()===`bin`&&Y.push(F(I(t),`lib`));for(let t of Y){let n=F(t,IP);S(n)&&add(n)}return q}function findSystemTypelib(t,n,{existsFile:S=existsSync,...C}={}){let{join:N}=C.platform===`win32`?fn:un,F=`${t}-${n}.typelib`;for(let t of systemGiTypelibDirs(C)){let n=N(t,F);if(S(n))return n}return null}var zP,BP,VP=__esmMin(()=>{Md(),jn(),RP(),zP=[`/usr/lib`,`/usr/lib64`,`/usr/local/lib`],BP=[`/usr/lib`]});function tryExecFile(t,n){let S=toSpawnable(t,n),C=spawnSync(S.cmd,S.args,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],windowsVerbatimArguments:S.windowsVerbatimArguments});return C.error||C.status!==0?null:C.stdout.trim()}function isOnPath(t,n=hostPathContext()){return findOnPath(t,n)!==void 0}function hostPathContext(){return{platform:process.platform,env:process.env,exists:existsSync,join:xn}}function checkBinary(t,n,S,C,N,F,I){let H=tryExecFile(S,C);return H===null?{id:t,name:n,found:!1,severity:N,requiredBy:I}:{id:t,name:n,found:!0,version:F?F(H):H.split(`
|
|
774
|
+
`),H++,q=C,I=14;switch(n){case 123:return C++,I=1;case 125:return C++,I=2;case 91:return C++,I=3;case 93:return C++,I=4;case 58:return C++,I=6;case 44:return C++,I=5;case 34:return C++,N=L(),I=10;case 47:let W=C-1;if(t.charCodeAt(C+1)===47){for(C+=2;C<S&&!J(t.charCodeAt(C));)C++;return N=t.substring(W,C),I=12}if(t.charCodeAt(C+1)===42){C+=2;let n=S-1,F=!1;for(;C<n;){let n=t.charCodeAt(C);if(n===42&&t.charCodeAt(C+1)===47){C+=2,F=!0;break}C++,J(n)&&(n===13&&t.charCodeAt(C)===10&&C++,H++,q=C)}return F||(C++,X=1),N=t.substring(W,C),I=13}return N+=String.fromCharCode(n),C++,I=16;case 45:if(N+=String.fromCharCode(n),C++,C===S||!R(t.charCodeAt(C)))return I=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return N+=p(),I=11;default:for(;C<S&&D(n);)C++,n=t.charCodeAt(C);if(F!==C){switch(N=t.substring(F,C),N){case`true`:return I=8;case`false`:return I=9;case`null`:return I=7}return I=16}return N+=String.fromCharCode(n),C++,I=16}}r(A,`scanNext`);function D(t){if(ee(t)||J(t))return!1;switch(t){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}r(D,`isUnknownContentCharacter`);function B(){let t;do t=A();while(t>=12&&t<=15);return t}return r(B,`scanNextNonTrivia`),{setPosition:v,getPosition:r(()=>C,`getPosition`),scan:n?B:A,getToken:r(()=>I,`getToken`),getTokenValue:r(()=>N,`getTokenValue`),getTokenOffset:r(()=>F,`getTokenOffset`),getTokenLength:r(()=>C-F,`getTokenLength`),getTokenStartLine:r(()=>W,`getTokenStartLine`),getTokenStartCharacter:r(()=>F-Y,`getTokenStartCharacter`),getTokenError:r(()=>X,`getTokenError`)}}function ee(t){return t===32||t===9}function J(t){return t===10||t===13}function R(t){return t>=48&&t<=57}function Pe(t,n=[],S=SN.DEFAULT){let C=null,N=[],F=[];function i(t){Array.isArray(N)?N.push(t):C!==null&&(N[C]=t)}return r(i,`onValue`),We(t,{onObjectBegin:r(()=>{let t={};i(t),F.push(N),N=t,C=null},`onObjectBegin`),onObjectProperty:r(t=>{C=t},`onObjectProperty`),onObjectEnd:r(()=>{N=F.pop()},`onObjectEnd`),onArrayBegin:r(()=>{let t=[];i(t),F.push(N),N=t,C=null},`onArrayBegin`),onArrayEnd:r(()=>{N=F.pop()},`onArrayEnd`),onLiteralValue:i,onError:r((t,S,C)=>{n.push({error:t,offset:S,length:C})},`onError`)},S),N[0]}function We(t,n,S=SN.DEFAULT){let C=Ne(t,!1),N=[],F=0;function i(t){return t?()=>F===0&&t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter()):()=>!0}r(i,`toNoArgVisit`);function f(t){return t?n=>F===0&&t(n,C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter()):()=>!0}r(f,`toOneArgVisit`);function u(t){return t?n=>F===0&&t(n,C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter(),()=>N.slice()):()=>!0}r(u,`toOneArgVisitWithPath`);function g(t){return t?()=>{F>0?F++:t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter(),()=>N.slice())===!1&&(F=1)}:()=>!0}r(g,`toBeginVisit`);function w(t){return t?()=>{F>0&&F--,F===0&&t(C.getTokenOffset(),C.getTokenLength(),C.getTokenStartLine(),C.getTokenStartCharacter())}:()=>!0}r(w,`toEndVisit`);let I=g(n.onObjectBegin),H=u(n.onObjectProperty),W=w(n.onObjectEnd),q=g(n.onArrayBegin),Y=w(n.onArrayEnd),X=u(n.onLiteralValue),Z=f(n.onSeparator),te=i(n.onComment),ne=f(n.onError),re=S&&S.disallowComments,ie=S&&S.allowTrailingComma;function T(){for(;;){let t=C.scan();switch(C.getTokenError()){case 4:k(14);break;case 5:k(15);break;case 3:k(13);break;case 1:re||k(11);break;case 2:k(12);break;case 6:k(16);break}switch(t){case 12:case 13:re?k(10):te();break;case 16:k(1);break;case 15:case 14:break;default:return t}}}r(T,`scanNext`);function k(t,n=[],S=[]){if(ne(t),n.length+S.length>0){let t=C.getToken();for(;t!==17;){if(n.indexOf(t)!==-1){T();break}else if(S.indexOf(t)!==-1)break;t=T()}}}r(k,`handleError`);function P(t){let n=C.getTokenValue();return t?X(n):(H(n),N.push(n)),T(),!0}r(P,`parseString`);function M(){switch(C.getToken()){case 11:let t=C.getTokenValue(),n=Number(t);isNaN(n)&&(k(2),n=0),X(n);break;case 7:X(null);break;case 8:X(!0);break;case 9:X(!1);break;default:return!1}return T(),!0}r(M,`parseLiteral`);function V(){return C.getToken()===10?(P(!1),C.getToken()===6?(Z(`:`),T(),U()||k(4,[],[2,5])):k(5,[],[2,5]),N.pop(),!0):(k(3,[],[2,5]),!1)}r(V,`parseProperty`);function z(){I(),T();let t=!1;for(;C.getToken()!==2&&C.getToken()!==17;){if(C.getToken()===5){if(t||k(4,[],[]),Z(`,`),T(),C.getToken()===2&&ie)break}else t&&k(6,[],[]);V()||k(4,[],[2,5]),t=!0}return W(),C.getToken()===2?T():k(7,[2],[]),!0}r(z,`parseObject`);function G(){q(),T();let t=!0,n=!1;for(;C.getToken()!==4&&C.getToken()!==17;){if(C.getToken()===5){if(n||k(4,[],[]),Z(`,`),T(),C.getToken()===4&&ie)break}else n&&k(6,[],[]);t?(N.push(0),t=!1):N[N.length-1]++,U()||k(4,[],[4,5]),n=!0}return Y(),t||N.pop(),C.getToken()===4?T():k(8,[4],[]),!0}r(G,`parseArray`);function U(){switch(C.getToken()){case 3:return G();case 1:return z();case 10:return P(!0);default:return M()}}return r(U,`parseValue`),T(),C.getToken()===17?S.allowEmptyContent?!0:(k(4,[],[]),!1):U()?(C.getToken()!==17&&k(9,[],[]),!0):(k(4,[],[]),!1)}var fN,r,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN,wN,TN,EN,DN,ON,kN,AN,jN,MN,NN,PN,FN,IN,LN,RN,zN,BN,VN,HN,UN,WN,GN,KN,qN,JN,YN,XN,ZN,QN,$N,eP,tP,nP,rP,iP,aP,oP,sP,cP,lP,uP,dP,fP,pP,mP,hP,gP,_P,vP,yP=__esmMin(()=>{jn(),Md(),Al(),dN(),Dg(),fN=Object.defineProperty,r=(t,n)=>fN(t,`name`,{value:n,configurable:!0}),r(h,`slash`),pN=r(t=>{let n=jd[t];return(S,...C)=>{let N=`${t}:${C.join(`:`)}`,F=S?.get(N);return F===void 0&&(F=Reflect.apply(n,jd,C),S?.set(N,F)),F}},`cacheFs`),mN=pN(`existsSync`),hN=pN(`readFileSync`),gN=pN(`statSync`),_N=r((t,n,S)=>{for(;;){let C=An.posix.join(t,n);if(mN(S,C))return C;let N=An.dirname(t);if(N===t)return;t=N}},`findUp`),vN=/^\.{1,2}(\/.*)?$/,yN=r(t=>{let n=h(t);return vN.test(n)?n:`./${n}`},`normalizeRelativePath`),r(Ne,`createScanner`),r(ee,`isWhiteSpace`),r(J,`isLineBreak`),r(R,`isDigit`),(function(t){t[t.lineFeed=10]=`lineFeed`,t[t.carriageReturn=13]=`carriageReturn`,t[t.space=32]=`space`,t[t._0=48]=`_0`,t[t._1=49]=`_1`,t[t._2=50]=`_2`,t[t._3=51]=`_3`,t[t._4=52]=`_4`,t[t._5=53]=`_5`,t[t._6=54]=`_6`,t[t._7=55]=`_7`,t[t._8=56]=`_8`,t[t._9=57]=`_9`,t[t.a=97]=`a`,t[t.b=98]=`b`,t[t.c=99]=`c`,t[t.d=100]=`d`,t[t.e=101]=`e`,t[t.f=102]=`f`,t[t.g=103]=`g`,t[t.h=104]=`h`,t[t.i=105]=`i`,t[t.j=106]=`j`,t[t.k=107]=`k`,t[t.l=108]=`l`,t[t.m=109]=`m`,t[t.n=110]=`n`,t[t.o=111]=`o`,t[t.p=112]=`p`,t[t.q=113]=`q`,t[t.r=114]=`r`,t[t.s=115]=`s`,t[t.t=116]=`t`,t[t.u=117]=`u`,t[t.v=118]=`v`,t[t.w=119]=`w`,t[t.x=120]=`x`,t[t.y=121]=`y`,t[t.z=122]=`z`,t[t.A=65]=`A`,t[t.B=66]=`B`,t[t.C=67]=`C`,t[t.D=68]=`D`,t[t.E=69]=`E`,t[t.F=70]=`F`,t[t.G=71]=`G`,t[t.H=72]=`H`,t[t.I=73]=`I`,t[t.J=74]=`J`,t[t.K=75]=`K`,t[t.L=76]=`L`,t[t.M=77]=`M`,t[t.N=78]=`N`,t[t.O=79]=`O`,t[t.P=80]=`P`,t[t.Q=81]=`Q`,t[t.R=82]=`R`,t[t.S=83]=`S`,t[t.T=84]=`T`,t[t.U=85]=`U`,t[t.V=86]=`V`,t[t.W=87]=`W`,t[t.X=88]=`X`,t[t.Y=89]=`Y`,t[t.Z=90]=`Z`,t[t.asterisk=42]=`asterisk`,t[t.backslash=92]=`backslash`,t[t.closeBrace=125]=`closeBrace`,t[t.closeBracket=93]=`closeBracket`,t[t.colon=58]=`colon`,t[t.comma=44]=`comma`,t[t.dot=46]=`dot`,t[t.doubleQuote=34]=`doubleQuote`,t[t.minus=45]=`minus`,t[t.openBrace=123]=`openBrace`,t[t.openBracket=91]=`openBracket`,t[t.plus=43]=`plus`,t[t.slash=47]=`slash`,t[t.formFeed=12]=`formFeed`,t[t.tab=9]=`tab`})(bN||={}),Array(20).fill(0).map((t,n)=>` `.repeat(n)),xN=200,Array(xN).fill(0).map((t,n)=>`
|
|
775
|
+
`+` `.repeat(n)),Array(xN).fill(0).map((t,n)=>`\r`+` `.repeat(n)),Array(xN).fill(0).map((t,n)=>`\r
|
|
776
|
+
`+` `.repeat(n)),Array(xN).fill(0).map((t,n)=>`
|
|
777
|
+
`+` `.repeat(n)),Array(xN).fill(0).map((t,n)=>`\r`+` `.repeat(n)),Array(xN).fill(0).map((t,n)=>`\r
|
|
778
|
+
`+` `.repeat(n)),(function(t){t.DEFAULT={allowTrailingComma:!1}})(SN||={}),r(Pe,`parse$1`),r(We,`visit`),(function(t){t[t.None=0]=`None`,t[t.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=4]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=6]=`InvalidCharacter`})(CN||={}),(function(t){t[t.OpenBraceToken=1]=`OpenBraceToken`,t[t.CloseBraceToken=2]=`CloseBraceToken`,t[t.OpenBracketToken=3]=`OpenBracketToken`,t[t.CloseBracketToken=4]=`CloseBracketToken`,t[t.CommaToken=5]=`CommaToken`,t[t.ColonToken=6]=`ColonToken`,t[t.NullKeyword=7]=`NullKeyword`,t[t.TrueKeyword=8]=`TrueKeyword`,t[t.FalseKeyword=9]=`FalseKeyword`,t[t.StringLiteral=10]=`StringLiteral`,t[t.NumericLiteral=11]=`NumericLiteral`,t[t.LineCommentTrivia=12]=`LineCommentTrivia`,t[t.BlockCommentTrivia=13]=`BlockCommentTrivia`,t[t.LineBreakTrivia=14]=`LineBreakTrivia`,t[t.Trivia=15]=`Trivia`,t[t.Unknown=16]=`Unknown`,t[t.EOF=17]=`EOF`})(wN||={}),TN=Pe,(function(t){t[t.InvalidSymbol=1]=`InvalidSymbol`,t[t.InvalidNumberFormat=2]=`InvalidNumberFormat`,t[t.PropertyNameExpected=3]=`PropertyNameExpected`,t[t.ValueExpected=4]=`ValueExpected`,t[t.ColonExpected=5]=`ColonExpected`,t[t.CommaExpected=6]=`CommaExpected`,t[t.CloseBraceExpected=7]=`CloseBraceExpected`,t[t.CloseBracketExpected=8]=`CloseBracketExpected`,t[t.EndOfFileExpected=9]=`EndOfFileExpected`,t[t.InvalidCommentToken=10]=`InvalidCommentToken`,t[t.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,t[t.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,t[t.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,t[t.InvalidUnicode=14]=`InvalidUnicode`,t[t.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,t[t.InvalidCharacter=16]=`InvalidCharacter`})(EN||={}),DN=r((t,n)=>TN(hN(n,t,`utf8`)),`readJsonc`),ON=Symbol(`implicitBaseUrl`),kN="${configDir}",AN=r(()=>{let{findPnpApi:t}=kl;return t&&t(process.cwd())},`getPnpApi`),jN=r((t,n,S,C)=>{let N=`resolveFromPackageJsonPath:${t}:${n}:${S}`;if(C!=null&&C.has(N))return C.get(N);let F=DN(t,C);if(!F)return;let I=n||`tsconfig.json`;if(!S&&F.exports)try{let[t]=v(F.exports,n,[`require`,`types`]);I=t}catch{return!1}else!n&&F.tsconfig&&(I=F.tsconfig);return I=An.join(t,`..`,I),C?.set(N,I),I},`resolveFromPackageJsonPath`),MN=`package.json`,NN=`tsconfig.json`,PN=r((t,n,S)=>{let C=t;if(t===`..`&&(C=An.join(C,NN)),t[0]===`.`&&(C=An.resolve(n,C)),An.isAbsolute(C)){if(mN(S,C)){if(gN(S,C).isFile())return C}else if(!C.endsWith(`.json`)){let t=`${C}.json`;if(mN(S,t))return t}return}let[N,...F]=t.split(`/`),I=N[0]===`@`?`${N}/${F.shift()}`:N,H=F.join(`/`),W=AN();if(W){let{resolveRequest:C}=W;try{if(I===t){let t=C(An.join(I,MN),n);if(t){let n=jN(t,H,!1,S);if(n&&mN(S,n))return n}}else{let S;try{S=C(t,n,{extensions:[`.json`]})}catch{S=C(An.join(t,NN),n)}if(S)return S}}catch{}}let q=_N(An.resolve(n),An.join(`node_modules`,I),S);if(!q||!gN(S,q).isDirectory())return;let Y=An.join(q,MN);if(mN(S,Y)){let t=jN(Y,H,!1,S);if(t===!1)return;if(t&&mN(S,t)&&gN(S,t).isFile())return t}let X=An.join(q,H),Z=X.endsWith(`.json`);if(!Z){let t=`${X}.json`;if(mN(S,t))return t}if(mN(S,X)){if(gN(S,X).isDirectory()){let t=An.join(X,MN);if(mN(S,t)){let n=jN(t,``,!0,S);if(n&&mN(S,n))return n}let n=An.join(X,NN);if(mN(S,n))return n}else if(Z)return X}},`resolveExtendsPath`),FN=r((t,n)=>yN(An.relative(t,n)),`pathRelative`),IN=[`files`,`include`,`exclude`],LN=r((t,n,S)=>{let C=An.join(n,S);return h(An.relative(t,C))||`./`},`resolveAndRelativize`),RN=r((t,n,S)=>{let C=An.relative(t,n);return C?h(`${C}/${S.startsWith(`./`)?S.slice(2):S}`):S},`prefixPattern`),zN=r((t,n,S,C)=>{let N=PN(t,n,C);if(!N)throw Error(`File '${t}' not found.`);if(S.has(N))throw Error(`Circularity detected while resolving configuration: ${N}`);S.add(N);let F=An.dirname(N),I=VN(N,C,S);delete I.references;let{compilerOptions:H}=I;if(H){let{baseUrl:t}=H;t&&!t.startsWith(kN)&&(H.baseUrl=LN(n,F,t));let{outDir:S}=H;S&&!S.startsWith(kN)&&(H.outDir=LN(n,F,S));let{declarationDir:C}=H;C&&!C.startsWith(kN)&&(H.declarationDir=LN(n,F,C));let{rootDir:N}=H;N&&!N.startsWith(kN)&&(H.rootDir=LN(n,F,N));let{rootDirs:I}=H;I&&(H.rootDirs=I.map(t=>t.startsWith(kN)?t:LN(n,F,t)));let{typeRoots:W}=H;W&&(H.typeRoots=W.map(t=>t.startsWith(kN)?t:LN(n,F,t)))}for(let t of IN){let S=I[t];S&&(I[t]=S.map(t=>t.startsWith(kN)?t:RN(n,F,t)))}return I},`resolveExtends`),BN=[`outDir`,`declarationDir`],VN=r((t,n,S=new Set)=>{let C;try{C=DN(t,n)||{}}catch{throw Error(`Cannot resolve tsconfig at path: ${t}`)}if(typeof C!=`object`)throw SyntaxError(`Failed to parse tsconfig at: ${t}`);let N=An.dirname(t);if(C.compilerOptions){let{compilerOptions:t}=C;t.paths&&!t.baseUrl&&(t[ON]=N)}if(C.extends){let t=Array.isArray(C.extends)?C.extends:[C.extends];delete C.extends;for(let F of t.reverse()){let t=zN(F,N,new Set(S),n),I={...t,...C,compilerOptions:{...t.compilerOptions,...C.compilerOptions}};t.watchOptions&&(I.watchOptions={...t.watchOptions,...C.watchOptions}),C=I}}if(C.compilerOptions){let{compilerOptions:t}=C;for(let n of[`baseUrl`,`rootDir`]){let S=t[n];if(S&&!S.startsWith(kN)){let C=An.resolve(N,S);t[n]=FN(N,C)}}for(let n of BN){let S=t[n];S&&(Array.isArray(C.exclude)||(C.exclude=BN.map(n=>t[n]).filter(Boolean)),S.startsWith(kN)||(S=yN(S)),t[n]=S)}}else C.compilerOptions={};if(C.include&&=C.include.map(h),C.files&&=C.files.map(t=>t.startsWith(kN)?t:yN(t)),C.watchOptions){let{watchOptions:t}=C;t.excludeDirectories&&=t.excludeDirectories.map(t=>h(An.resolve(N,t))),t.excludeFiles&&=t.excludeFiles.map(t=>h(An.resolve(N,t))),t.watchFile&&=t.watchFile.toLowerCase(),t.watchDirectory&&=t.watchDirectory.toLowerCase(),t.fallbackPolling&&=t.fallbackPolling.toLowerCase()}return C},`_parseTsconfig`),HN=r((t,n)=>{if(t.startsWith(kN))return h(An.join(n,t.slice(12)))},`interpolateConfigDir`),UN=[`outDir`,`declarationDir`,`outFile`,`rootDir`,`baseUrl`,`tsBuildInfoFile`],WN=r(t=>{if(t.strict)for(let n of[`noImplicitAny`,`noImplicitThis`,`strictNullChecks`,`strictFunctionTypes`,`strictBindCallApply`,`strictPropertyInitialization`,`strictBuiltinIteratorReturn`,`alwaysStrict`,`useUnknownInCatchVariables`])t[n]===void 0&&(t[n]=!0);if(t.composite&&(t.declaration??=!0,t.incremental??=!0),t.target){let n=t.target.toLowerCase();n===`es2015`&&(n=`es6`),t.target=n,n===`esnext`&&(t.module??=`es6`,t.useDefineForClassFields??=!0),(n===`es6`||n===`es2016`||n===`es2017`||n===`es2018`||n===`es2019`||n===`es2020`||n===`es2021`||n===`es2022`||n===`es2023`||n===`es2024`)&&(t.module??=`es6`),(n===`es2022`||n===`es2023`||n===`es2024`)&&(t.useDefineForClassFields??=!0)}if(t.module){let n=t.module.toLowerCase();if(n===`es2015`&&(n=`es6`),t.module=n,(n===`es6`||n===`es2020`||n===`es2022`||n===`esnext`||n===`none`||n===`system`||n===`umd`||n===`amd`)&&(t.moduleResolution??=`classic`),n===`system`&&(t.allowSyntheticDefaultImports??=!0),(n===`node16`||n===`node18`||n===`node20`||n===`nodenext`||n===`preserve`)&&(t.esModuleInterop??=!0,t.allowSyntheticDefaultImports??=!0),(n===`node16`||n===`node18`||n===`node20`||n===`nodenext`)&&(t.moduleDetection??=`force`),n===`node16`&&(t.target??=`es2022`,t.moduleResolution??=`node16`),n===`node18`&&(t.target??=`es2022`,t.moduleResolution??=`node16`),n===`node20`&&(t.target??=`es2023`,t.moduleResolution??=`node16`,t.resolveJsonModule??=!0),n===`nodenext`&&(t.target??=`esnext`,t.moduleResolution??=`nodenext`,t.resolveJsonModule??=!0),n===`node16`||n===`node18`||n===`node20`||n===`nodenext`){let n=t.target;(n===`es3`||n===`es2022`||n===`es2023`||n===`es2024`||n===`esnext`)&&(t.useDefineForClassFields??=!0)}n===`preserve`&&(t.moduleResolution??=`bundler`)}if(t.moduleResolution){let n=t.moduleResolution.toLowerCase();n===`node`&&(n=`node10`),t.moduleResolution=n,(n===`node16`||n===`nodenext`||n===`bundler`)&&(t.resolvePackageJsonExports??=!0,t.resolvePackageJsonImports??=!0),n===`bundler`&&(t.allowSyntheticDefaultImports??=!0,t.resolveJsonModule??=!0)}t.jsx&&=t.jsx.toLowerCase(),t.moduleDetection&&=t.moduleDetection.toLowerCase(),t.importsNotUsedAsValues&&=t.importsNotUsedAsValues.toLowerCase(),t.newLine&&=t.newLine.toLowerCase(),t.esModuleInterop&&(t.allowSyntheticDefaultImports??=!0),t.verbatimModuleSyntax&&(t.isolatedModules??=!0,t.preserveConstEnums??=!0),t.isolatedModules&&(t.preserveConstEnums??=!0),t.rewriteRelativeImportExtensions&&(t.allowImportingTsExtensions??=!0),t.lib&&=t.lib.map(t=>t.toLowerCase()),t.checkJs&&(t.allowJs??=!0)},`normalizeCompilerOptions`),GN=r((t,n=new Map)=>{let S=An.resolve(t),C=VN(S,n),N=An.dirname(S),{compilerOptions:F}=C;if(F){for(let t of UN){let n=F[t];if(n){let S=HN(n,N);F[t]=S?FN(N,S):n}}for(let t of[`rootDirs`,`typeRoots`]){let n=F[t];n&&(F[t]=n.map(t=>{let n=HN(t,N);return n?FN(N,n):yN(t)}))}let{paths:t}=F;if(t)for(let n of Object.keys(t))t[n]=t[n].map(t=>HN(t,N)??t);WN(F)}for(let t of IN){let n=C[t];n&&(C[t]=n.map(t=>HN(t,N)??t))}return C},`parseTsconfig`),KN=Object.defineProperty,qN=r((t,n)=>KN(t,`name`,{value:n,configurable:!0}),`s`),JN=qN(t=>{let n=``;for(let S=0;S<t.length;S+=1){let C=t[S],N=C.toUpperCase();n+=C===N?C.toLowerCase():N}return n},`invertCase`),YN=new Map,XN=qN((t,n)=>{let S=An.join(t,`.is-fs-case-sensitive-test-${process.pid}`);try{return n.writeFileSync(S,``),!n.existsSync(JN(S))}finally{try{n.unlinkSync(S)}catch{}}},`checkDirectoryCaseWithWrite`),ZN=qN((t,n,S)=>{try{return XN(t,S)}catch(t){if(n===void 0)return XN(Eg.tmpdir(),S);throw t}},`checkDirectoryCaseWithFallback`),QN=qN((t,n=jd,S=!0)=>{let C=t??process.cwd();if(S&&YN.has(C))return YN.get(C);let N,F=JN(C);return N=F!==C&&n.existsSync(C)?!n.existsSync(F):ZN(C,t,n),S&&YN.set(C,N),N},`isFsCaseSensitive`),{join:$N}=An.posix,eP={ts:[`.ts`,`.tsx`,`.d.ts`],cts:[`.cts`,`.d.cts`],mts:[`.mts`,`.d.mts`]},tP=r(t=>{let n=[...eP.ts],S=[...eP.cts],C=[...eP.mts];return t!=null&&t.allowJs&&(n.push(`.js`,`.jsx`),S.push(`.cjs`),C.push(`.mjs`)),[...n,...S,...C]},`getSupportedExtensions`),nP=r(t=>{let n=[];if(!t)return n;let{outDir:S,declarationDir:C}=t;return S&&n.push(S),C&&n.push(C),n},`getDefaultExcludeSpec`),rP=r(t=>t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),`escapeForRegexp`),iP=`(?!(${[`node_modules`,`bower_components`,`jspm_packages`].join(`|`)})(/|$))`,aP=/(?:^|\/)[^.*?]+$/,oP=`**/*`,sP=`[^/]`,cP=`[^./]`,lP=process.platform===`win32`,uP=r(({config:t,path:n},S=QN())=>{if(`extends`in t)throw Error(`tsconfig#extends must be resolved. Use getTsconfig or parseTsconfig to resolve it.`);if(!An.isAbsolute(n))throw Error(`The tsconfig path must be absolute`);lP&&(n=h(n));let C=An.dirname(n),{files:N,include:F,exclude:I,compilerOptions:H}=t,W=r(t=>An.isAbsolute(t)?t:$N(C,t),`resolvePattern`),q=N?.map(W),Y=tP(H),X=S?``:`i`,Z=(I||nP(H)).map(t=>{let n=W(t),S=rP(n).replaceAll(String.raw`\*\*/`,`(.+/)?`).replaceAll(String.raw`\*`,`${sP}*`).replaceAll(String.raw`\?`,sP);return RegExp(`^${S}($|/)`,X)}),te=N||F?F:[oP],ne=te?te.map(t=>{let n=W(t);aP.test(n)&&(n=$N(n,oP));let S=rP(n).replaceAll(String.raw`/\*\*`,`(/${iP}${cP}${sP}*)*?`).replaceAll(/(\/)?\\\*/g,(t,n)=>{let S=`(${cP}|(\\.(?!min\\.js$))?)*`;return n?`/${iP}${cP}${S}`:S}).replaceAll(/(\/)?\\\?/g,(t,n)=>{let S=sP;return n?`/${iP}${S}`:S});return RegExp(`^${S}$`,X)}):void 0;return n=>{if(!An.isAbsolute(n))throw Error(`filePath must be absolute`);if(lP&&(n=h(n)),q!=null&&q.includes(n)||!(!Y.some(t=>n.endsWith(t))||Z.some(t=>t.test(n)))&&ne&&ne.some(t=>t.test(n)))return t}},`createFilesMatcher`),dP=r((t,n,S)=>{let C=An.resolve(t),N=h(t);for(;;){let t=_N(N,n,S);if(!t)return;let F=An.resolve(t),I=GN(F,S),H={path:h(F),config:I};if(uP(H)(C))return H;let W=An.dirname(t),q=An.dirname(W);if(q===W)return;N=q}},`findConfigApplicable`),fP=r((t=process.cwd(),n=`tsconfig.json`,S=new Map,C=!1)=>C?dP(t,n,S)?.path:_N(h(t),n,S),`findTsconfig`),pP=r((t=process.cwd(),n=`tsconfig.json`,S=new Map,C=!1)=>{if(!C){let C=fP(t,n,S);return C?{path:C,config:GN(C,S)}:null}return dP(t,n,S)??null},`getTsconfig`),mP=/\*/g,hP=r((t,n)=>{let S=t.match(mP);if(S&&S.length>1)throw Error(n)},`assertStarCount`),gP=r(t=>{if(t.includes(`*`)){let[n,S]=t.split(`*`);return{prefix:n,suffix:S}}return t},`parsePattern`),_P=r(({prefix:t,suffix:n},S)=>S.startsWith(t)&&S.endsWith(n),`isPatternMatch`),vP=r((t,n,S)=>Object.entries(t).map(([t,C])=>(hP(t,`Pattern '${t}' can have at most one '*' character.`),{pattern:gP(t),substitutions:C.map(C=>{if(hP(C,`Substitution '${C}' in pattern '${t}' can have at most one '*' character.`),!n&&!vN.test(C)&&!An.isAbsolute(C))throw Error(`Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?`);return An.resolve(S,C)})})),`parsePaths`),r(t=>{let{compilerOptions:n}=t.config;if(!n)return null;let{baseUrl:S,paths:C}=n;if(!S&&!C)return null;let N=ON in n&&n[ON],F=An.resolve(An.dirname(t.path),S||N||`.`),I=C?vP(C,S,F):[];return t=>{if(vN.test(t))return[];let n=[];for(let S of I){if(S.pattern===t)return S.substitutions.map(h);typeof S.pattern!=`string`&&n.push(S)}let C,N=-1;for(let S of n)_P(S.pattern,t)&&S.pattern.prefix.length>N&&(N=S.pattern.prefix.length,C=S);if(!C)return S?[h(An.join(F,t))]:[];let H=t.slice(C.pattern.prefix.length,t.length-C.pattern.suffix.length);return C.substitutions.map(t=>h(t.replace(`*`,H)))}},`createPathsMatcher`)});function workspacesForChangedFiles(t,n){let S=new Set,C=[],N={children:new Map};for(let n of t){if(n.relativeLocation===`.`||n.relativeLocation===``)continue;let t=n.relativeLocation.split(`/`).filter(Boolean),S=N;for(let n of t){let t=S.children.get(n);t||(t={children:new Map},S.children.set(n,t)),S=t}S.ws=n.name}for(let t of n){if(!t)continue;let n=t.replace(/\\/g,`/`).split(`/`).filter(Boolean),F=N,I;for(let t of n){if(F=F.children.get(t),!F)break;F.ws&&(I=F.ws)}I?S.add(I):C.push(t)}return{matched:S,unmatched:C}}var bP=__esmMin(()=>{});function expandPattern(t,n){let S=n.split(`/`).filter(Boolean),C=[vn(t)];for(let t of S){let n=[];for(let S of C)if(t===`*`){let t=[];try{t=readdirSync(S)}catch{continue}for(let C of t){if(C.startsWith(`.`))continue;let t=xn(S,C);try{statSync(t).isDirectory()&&n.push(t)}catch{}}}else if(t.includes(`*`)){let C=globToRegex$1(t),N=[];try{N=readdirSync(S)}catch{continue}for(let t of N){if(t.startsWith(`.`)||!C.test(t))continue;let N=xn(S,t);try{statSync(N).isDirectory()&&n.push(N)}catch{}}}else{let C=xn(S,t);if(existsSync(C))try{statSync(C).isDirectory()&&n.push(C)}catch{}}C=n}return C}function globToRegex$1(t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`);return RegExp(`^${n}$`)}var xP=__esmMin(()=>{Md(),jn(),__name$1(globToRegex$1,`globToRegex`)});function discoverWorkspaces(t,n={}){let S=xn(t,`package.json`),C=existsSync(S);if(!C&&!n.patterns)throw Error(`@gjsify/workspace: no package.json at ${t}`);let N=C?JSON.parse(readFileSync(S,`utf-8`)):{},F=n.patterns??extractWorkspacePatterns(N),I=F.filter(t=>!t.startsWith(`!`)),H=F.filter(t=>t.startsWith(`!`)).map(t=>globToRegex$1(t.slice(1))),W=[],q=new Set;n.includeRoot&&N.name&&(W.push({location:t,relativeLocation:`.`,name:N.name,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}),q.add(t));for(let n of I)for(let S of expandPattern(t,n)){if(q.has(S))continue;let n=Sn(t,S).split(On).join(`/`);if(H.some(t=>t.test(n)))continue;let C=xn(S,`package.json`);if(!existsSync(C))continue;let N;try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{continue}N.name&&(q.add(S),W.push({location:S,relativeLocation:n,name:N.name,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}))}return W.sort((t,n)=>t.relativeLocation.localeCompare(n.relativeLocation)),W}function filterWorkspaces(t,n){let S=n.include?.map(globToRegex$1),C=n.exclude?.map(globToRegex$1);return t.filter(t=>!(n.noPrivate&&t.private||S&&S.length>0&&!S.some(n=>n.test(t.name))||C&&C.some(n=>n.test(t.name))))}function extractWorkspacePatterns(t){let n=t.workspaces;return n?Array.isArray(n)?n:n.packages??[]:[]}function indexByName(t){let n=new Map;for(let S of t)n.set(S.name,S);return n}var SP=__esmMin(()=>{xP(),Md(),jn()});function parse(t){try{return new SemVer(t)}catch{return null}}function compare(t,n){let S=t instanceof SemVer?t:new SemVer(t),C=n instanceof SemVer?n:new SemVer(n);return S.compare(C)}function satisfies(t,n){let S=n instanceof TP?n:new TP(n),C=t instanceof SemVer?t:parse(String(t));return C?S.test(C):!1}function maxSatisfying(t,n){let S=n instanceof TP?n:new TP(n),C=null;for(let n of t){let t=parse(n);!t||!S.test(t)||(C===null||t.compare(C)>0)&&(C=t)}return C?C.version:null}function validRange(t){try{return new TP(t).format()}catch{return null}}function testComparator(t,n){if(t.semver===null)return!0;let S=n.compare(t.semver);switch(t.operator){case``:case`=`:return S===0;case`<`:return S<0;case`<=`:return S<=0;case`>`:return S>0;case`>=`:return S>=0}}function formatComparator(t){return t.semver===null?`*`:`${t.operator}${t.semver.version}`}function parseRangePart(t){let n=t.trim();if(n===``||n===`*`||n.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=n.match(/^\s*(\S+)\s+-\s+(\S+)\s*$/);if(S)return hyphenRange(S[1],S[2]);let C=n.replace(/(<=|>=|<|>|=)\s+(?=\S)/g,`$1`).split(/\s+/),N=[];for(let t of C)N.push(...parseSimple(t));return N}function parseSimple(t){if(t===`*`||t===``||t.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];if(t.startsWith(`^`))return caretRange(t.slice(1));if(t.startsWith(`~`))return tildeRange(t.slice(1).replace(/^>/,``));let n=t.match(/^(<=|>=|<|>|=)\s*(.+)$/);if(n){let t=n[1];return primitiveRange(t,n[2])}return partialRange(t)}function parsePartial(t){let n=t.trim().replace(/^v/,``);if(n===``||n===`*`)return{major:null,minor:null,patch:null,pre:``,build:``};let S=``,C=``,N=n,F=N.indexOf(`+`);F>=0&&(C=N.slice(F+1),N=N.slice(0,F));let I=N.indexOf(`-`);I>=0&&(S=N.slice(I+1),N=N.slice(0,I));let H=N.split(`.`),xr=n=>{if(n===void 0||n===``||n===`x`||n===`X`||n===`*`)return null;if(!/^\d+$/.test(n))throw TypeError(`Invalid partial version: ${t}`);return Number(n)};return{major:xr(H[0]),minor:xr(H[1]),patch:xr(H[2]),pre:S,build:C}}function partialToVersion(t){return`${t.major??0}.${t.minor??0}.${t.patch??0}${t.pre?`-${t.pre}`:``}${t.build?`+${t.build}`:``}`}function partialRange(t){let n=parsePartial(t);return n.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:n.minor===null?[{operator:`>=`,semver:new SemVer(`${n.major}.0.0`)},{operator:`<`,semver:new SemVer(`${n.major+1}.0.0`)}]:n.patch===null?[{operator:`>=`,semver:new SemVer(`${n.major}.${n.minor}.0`)},{operator:`<`,semver:new SemVer(`${n.major}.${n.minor+1}.0`)}]:[{operator:`=`,semver:new SemVer(partialToVersion(n))}]}function caretRange(t){let n=parsePartial(t);if(n.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=`${n.major}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}`,C;return C=n.major>0||n.minor===null?`${n.major+1}.0.0`:n.minor>0||n.patch===null?`0.${n.minor+1}.0`:`0.0.${n.patch+1}`,[{operator:`>=`,semver:new SemVer(S)},{operator:`<`,semver:new SemVer(C)}]}function tildeRange(t){let n=parsePartial(t);if(n.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let S=`${n.major}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}`,C=n.minor===null?`${n.major+1}.0.0`:`${n.major}.${n.minor+1}.0`;return[{operator:`>=`,semver:new SemVer(S)},{operator:`<`,semver:new SemVer(C)}]}function primitiveRange(t,n){let S=parsePartial(n);return S.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:t===`=`||t===``?partialRange(n):t===`>`?S.minor===null?[{operator:`>=`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`>`,semver:new SemVer(partialToVersion(S))}]:t===`<`?S.minor===null?[{operator:`<`,semver:new SemVer(`${S.major}.0.0`)}]:S.patch===null?[{operator:`<`,semver:new SemVer(`${S.major}.${S.minor}.0`)}]:[{operator:`<`,semver:new SemVer(partialToVersion(S))}]:t===`>=`?[{operator:`>=`,semver:new SemVer(partialToVersion(S))}]:S.minor===null?[{operator:`<`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`<`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`<=`,semver:new SemVer(partialToVersion(S))}]}function hyphenRange(t,n){let S=parsePartial(t),C=parsePartial(n),N=S.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`)},F;return F=C.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:C.minor===null?{operator:`<`,semver:new SemVer(`${C.major+1}.0.0`)}:C.patch===null?{operator:`<`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}:{operator:`<=`,semver:new SemVer(`${C.major}.${C.minor}.${C.patch}${C.pre?`-${C.pre}`:``}`)},[N,F]}var CP,wP,SemVer,TP,EP=__esmMin(()=>{CP=/^(0|[1-9]\d*)$/,wP=/^(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,SemVer=class{major;minor;patch;prerelease;build;version;constructor(t){let n=String(t).trim().replace(/^v/,``),S=wP.exec(n);if(!S)throw TypeError(`Invalid Version: ${t}`);this.major=Number(S[1]),this.minor=Number(S[2]),this.patch=Number(S[3]),this.prerelease=S[4]?S[4].split(`.`).map(t=>CP.test(t)?Number(t):t):[],this.build=S[5]?S[5].split(`.`):[],this.version=`${this.major}.${this.minor}.${this.patch}`+(this.prerelease.length?`-${this.prerelease.join(`.`)}`:``)+(this.build.length?`+${this.build.join(`.`)}`:``)}compare(t){return this.major===t.major?this.minor===t.minor?this.patch===t.patch?this.comparePre(t):this.patch<t.patch?-1:1:this.minor<t.minor?-1:1:this.major<t.major?-1:1}comparePre(t){let n=this.prerelease,S=t.prerelease;if(n.length===0&&S.length===0)return 0;if(n.length===0)return 1;if(S.length===0)return-1;for(let t=0;;t++){let C=n[t],N=S[t];if(C===void 0&&N===void 0)return 0;if(N===void 0)return 1;if(C===void 0)return-1;if(C===N)continue;let F=typeof C==`number`,I=typeof N==`number`;return F&&!I?-1:!F&&I?1:C<N?-1:1}}toString(){return this.version}},TP=class Range{raw;set;constructor(t){if(t instanceof Range){this.raw=t.raw,this.set=t.set;return}this.raw=String(t).trim();let n=this.raw.split(/\s*\|\|\s*/),S=[];for(let t of n){let n=parseRangePart(t);if(n.length===0)throw TypeError(`Invalid range: ${this.raw}`);S.push(n)}if(S.length===0)throw TypeError(`Invalid range: ${this.raw}`);this.set=S}test(t){let n=t instanceof SemVer?t:parse(String(t));if(!n)return!1;for(let t of this.set)if(t.every(t=>testComparator(t,n))){if(n.prerelease.length>0&&!t.some(t=>t.semver!==null&&t.semver.prerelease.length>0&&t.semver.major===n.major&&t.semver.minor===n.minor&&t.semver.patch===n.patch))continue;return!0}return!1}format(){return this.set.map(t=>t.map(formatComparator).join(` `)).join(` || `)}toString(){return this.format()}}});function registryRangeOf(t){let n=t.trim();return/[:/\\]/.test(n)||n.toLowerCase()===`latest`||validRange(n)===null?null:n}function releaseVersionOf(t){let n=parse(t);return n===null?t:`${n.major}.${n.minor}.${n.patch}`}function buildDependencyGraph(t,n={}){let S=n.includeDev??!1,C=n.includePeer??!1,N=n.includeOptional??!0,F=indexByName(t),I=new Map,H=[];for(let n of t){let t=new Set,W=[],q=n.manifest;for(let I of[q.dependencies,S?q.devDependencies:void 0,C?q.peerDependencies:void 0,N?q.optionalDependencies:void 0])if(I)for(let[S,C]of Object.entries(I)){if(typeof C!=`string`)continue;let N=F.get(S);if(!N)continue;if(C.startsWith(`workspace:`)){t.add(S);continue}let I=registryRangeOf(C);I!==null&&(satisfies(releaseVersionOf(N.version),I)?t.add(S):W.push({from:n.name,to:S,spec:C,version:N.version}))}for(let n of W)t.has(n.to)||H.push(n);I.set(n.name,t)}return{edges:I,byName:F,unlinked:H}}function topologicalSort(t){let n=new Map,S=new Map;for(let C of t.edges.keys())n.set(C,new Set),S.set(C,0);for(let[C,N]of t.edges)for(let t of N)n.has(t)&&(n.get(t).add(C),S.set(C,(S.get(C)??0)+1));let C=[];for(let[t,n]of S)n===0&&C.push(t);C.sort();let N=[];for(;C.length>0;){let F=C.shift(),I=t.byName.get(F);I&&N.push(I);let H=n.get(F);if(H){let t=[];for(let n of H){let C=(S.get(n)??1)-1;S.set(n,C),C===0&&t.push(n)}t.sort(),C.push(...t)}}if(N.length!==S.size){let t=[...S.entries()].filter(([,t])=>t>0).map(([t])=>t);throw Error(`@gjsify/workspace: dependency cycle detected involving ${t.join(`, `)}`)}return N}function buildReverseDependencyGraph(t,n={}){let S=buildDependencyGraph(t,n),C=new Map;for(let t of S.edges.keys())C.set(t,new Set);for(let[t,n]of S.edges)for(let S of n){let n=C.get(S);n&&n.add(t)}return{edges:C,byName:S.byName,unlinked:S.unlinked}}function affectedClosure(t,n){let S=new Set,C=[];for(let N of n)t.byName.has(N)&&(S.has(N)||(S.add(N),C.push(N)));for(;C.length>0;){let n=C.shift(),N=t.edges.get(n);if(N)for(let t of N)S.has(t)||(S.add(t),C.push(t))}return S}var DP=__esmMin(()=>{SP(),EP()}),OP=__esmMin(()=>{bP(),SP(),DP(),jn()});function stripBom(t){return t.charCodeAt(0)===65279?t.slice(1):t}function readPackageJson$2(t){try{return JSON.parse(stripBom(readFileSync(t,`utf-8`)))}catch{return null}}var kP=__esmMin(()=>{Md(),__name$1(readPackageJson$2,`readPackageJson`)});function findWorkspaceRoot(t){let n=t;for(let S=0;S<12;S++){let S=xn(n,`package.json`);if(existsSync(S)&&readPackageJson$2(S)?.workspaces!==void 0)try{let S=discoverWorkspaces(n);if(n===t||S.some(n=>n.location===t))return n}catch{}let C=vn(n,`..`);if(C===n)break;n=C}return null}var AP=__esmMin(()=>{Md(),jn(),OP(),kP()});function resolveNpmPackage(t,n={}){let S=n.cwd??process.cwd(),C=process.env.GJSIFY_NODE_PATH;if(C)for(let n of C.split(kn).filter(Boolean)){let S=tryResolveFromDir(t,vn(n));if(S)return S}let N=tryResolveFromDir(t,S);if(N)return N;let F=findWorkspaceRoot(S);if(F&&F!==S){let n=tryResolveFromDir(t,F);if(n)return n}if(n.bundleUrl)try{return createRequire(n.bundleUrl).resolve(t)}catch{}let I=vn(S,`..`);for(let n=0;n<8;n++){let n=tryResolveFromDir(t,I);if(n)return n;let S=vn(I,`..`);if(S===I)break;I=S}return null}function tryResolveFromDir(t,n){try{let S=pathToFileURL(xn(n,`__gjsify_resolve__.js`)).href;return createRequire(S).resolve(t)}catch{return null}}function resolveInstalledPackage(t,n={}){let S=n.resolve??((t,S)=>S===`project`?resolveNpmPackage(t,{cwd:n.cwd,bundleUrl:n.bundleUrl}):tryResolveFromFile(t,jP)),C=S(t,`project`);if(C===null)return null;let N=S(t,`nowhere`);return N!==null&&N===C?null:C}function tryResolveFromFile(t,n){try{return createRequire(pathToFileURL(n).href).resolve(t)}catch{return null}}var jP,MP=__esmMin(()=>{Al(),Hn(),Dg(),jn(),AP(),jP=xn(tmpdir(),`.gjsify-nonexistent-control-anchor`,`__gjsify_resolve__.js`)});function giLibraryDirsForTypelibDir(t){let n=PP(t);return NP(t)===`girepository-1.0`?[n]:[t,n]}function splitSearchPath(t,n=`:`){return(t??``).split(n).filter(Boolean)}function isDirectory$1(t){try{return statSync(t).isDirectory()}catch{return!1}}function pkgConfigSearchDirs(t){if(RP)return RP;let n=splitSearchPath(t.PKG_CONFIG_PATH),S=spawnSync(`pkg-config`,[`--variable=pc_path`,`pkg-config`],{encoding:`utf8`,timeout:1e4});return!S.error&&S.status===0&&n.push(...splitSearchPath(String(S.stdout).trim())),RP=n,n}function systemGiLibraryDirs({platform:t=process.platform,env:n=process.env,existsDir:S=isDirectory$1,searchDirs:C=pkgConfigSearchDirs}={}){let N=IP[t];if(!N)return[];let F=[],add=t=>{t&&t!==`/`&&!F.includes(t)&&F.push(t)};for(let t of splitSearchPath(n.GI_TYPELIB_PATH))for(let n of giLibraryDirsForTypelibDir(t))S(n)&&add(n);let I=[];for(let t of C(n))NP(t)===`pkgconfig`&&I.push(PP(t));I.push(...N);for(let t of I)S(FP(t,`girepository-1.0`))&&add(t);return F}function dyldDefaultFallbackDirs(t=process.env){let n=t.HOME;return[...n?[`${n}/lib`]:[],`/usr/local/lib`,`/lib`,`/usr/lib`]}function composeDyldFallback(t,n=process.env){return[...new Set([...t,...splitSearchPath(n.DYLD_FALLBACK_LIBRARY_PATH),...dyldDefaultFallbackDirs(n)])].join(`:`)}var NP,PP,FP,IP,LP,RP,zP=__esmMin(()=>{w_(),Md(),jn(),{basename:NP,dirname:PP,join:FP}=un,IP={darwin:[`/opt/homebrew/lib`,`/usr/local/lib`,`/opt/local/lib`]},LP=`girepository-1.0`,RP=null,__name$1(isDirectory$1,`isDirectory`)});function isDirectory(t){try{return statSync(t).isDirectory()}catch{return!1}}function subdirectories(t){try{return readdirSync(t,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function systemGiTypelibDirs({platform:t=process.platform,env:n=process.env,existsDir:S=isDirectory,listDirs:C=subdirectories,searchDirs:N=pkgConfigSearchDirs}={}){let{join:F,dirname:I,basename:H}=t===`win32`?fn:un,W=t===`win32`?`;`:`:`,q=[],add=t=>{t&&!q.includes(t)&&q.push(t)};for(let t of splitSearchPath(n.GI_TYPELIB_PATH,W))S(t)&&add(t);let Y=[];for(let t of N(n))H(t)===`pkgconfig`&&Y.push(I(t));if(t===`linux`){Y.push(...BP);for(let t of VP)for(let n of C(t))Y.push(F(t,n))}else if(t===`darwin`)Y.push(...systemGiLibraryDirs({platform:t,env:n,existsDir:S,searchDirs:N}));else if(t===`win32`)for(let t of splitSearchPath(n.PATH,W))H(t).toLowerCase()===`bin`&&Y.push(F(I(t),`lib`));for(let t of Y){let n=F(t,LP);S(n)&&add(n)}return q}function findSystemTypelib(t,n,{existsFile:S=existsSync,...C}={}){let{join:N}=C.platform===`win32`?fn:un,F=`${t}-${n}.typelib`;for(let t of systemGiTypelibDirs(C)){let n=N(t,F);if(S(n))return n}return null}var BP,VP,HP=__esmMin(()=>{Md(),jn(),zP(),BP=[`/usr/lib`,`/usr/lib64`,`/usr/local/lib`],VP=[`/usr/lib`]});function tryExecFile(t,n){let S=toSpawnable(t,n),C=spawnSync(S.cmd,S.args,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],windowsVerbatimArguments:S.windowsVerbatimArguments});return C.error||C.status!==0?null:C.stdout.trim()}function isOnPath(t,n=hostPathContext()){return findOnPath(t,n)!==void 0}function hostPathContext(){return{platform:process.platform,env:process.env,exists:existsSync,join:xn}}function checkBinary(t,n,S,C,N,F,I){let H=tryExecFile(S,C);return H===null?{id:t,name:n,found:!1,severity:N,requiredBy:I}:{id:t,name:n,found:!0,version:F?F(H):H.split(`
|
|
779
779
|
`)[0]??H,severity:N,requiredBy:I}}function checkPkgConfig(t,n,S,C,N){let F=tryExecFile(`pkg-config`,[`--modversion`,S]);return F===null?{id:t,name:n,found:!1,severity:C,requiredBy:N}:{id:t,name:n,found:!0,version:F.split(`
|
|
780
780
|
`)[0],severity:C,requiredBy:N}}function checkGiLibrary(t,n,S,C,N,F,I){return findSystemTypelib(S,C)===null?{id:t,name:n,found:!1,severity:F,requiredBy:I}:{id:t,name:n,found:!0,version:tryExecFile(`pkg-config`,[`--modversion`,N])?.split(`
|
|
781
|
-
`)[0],severity:F,requiredBy:I}}function checkNpmPackage(t,n,S,C,N,F){try{return createRequire(pathToFileURL(xn(C,`_check_.js`)).href).resolve(S),{id:t,name:n,found:!0,severity:N,requiredBy:F}}catch{}try{return createRequire(import.meta.url).resolve(S),{id:t,name:n,found:!0,severity:N,requiredBy:F}}catch{return{id:t,name:n,found:!1,severity:N,requiredBy:F}}}function detectPackageManager$1(){if(process.platform===`win32`)return tryExecFile(`where`,[`winget`])===null?`unknown`:`winget`;let t=process.platform===`darwin`?[`brew`]:[`apt`,`dnf`,`pacman`,`zypper`,`apk`,`brew`];for(let n of t)if(isOnPath(n))return n;return`unknown`}function checkMsvcRuntime(){let t=process.env.SystemRoot??process.env.SYSTEMROOT??`C:\\Windows`,n=[`vcruntime140.dll`,`vcruntime140_1.dll`,`msvcp140.dll`].filter(n=>!existsSync(`${t}\\System32\\${n}`));return{id:`msvc-runtime`,name:n.length===0?`Microsoft Visual C++ runtime`:`Microsoft Visual C++ runtime (missing ${n.join(`, `)} — the GTK bundle's DLLs are MSVC-ABI and will not load)`,found:n.length===0,severity:`required`}}function missingSystemDepsFor(t){let n=
|
|
782
|
-
`)[0]??t)),process.platform===`win32`&&t.push(checkMsvcRuntime()),t}function checkGwebgl(t){return checkNpmPackage(`gwebgl`,`gwebgl (@gjsify/webgl)`,`@gjsify/webgl`,t,`optional`,[`@gjsify/webgl`])}function runRequiredChecks(t){let n=[];return n.push(checkBinary(`pkg-config`,`pkg-config`,`pkg-config`,[`--version`],`required`)),n.push(checkBinary(`meson`,`Meson`,`meson`,[`--version`],`required`)),n.push(checkGiLibrary(`gtk4`,`GTK4`,`Gtk`,`4.0`,`gtk4`,`required`)),n.push(checkGiLibrary(`libadwaita`,`libadwaita`,`Adw`,`1`,`libadwaita-1`,`required`)),n.push(checkGiLibrary(`libsoup3`,`libsoup3`,`Soup`,`3.0`,`libsoup-3.0`,`required`)),n.push(checkPkgConfig(`gobject-introspection`,`GObject Introspection`,`gobject-introspection-1.0`,`required`)),n}function runNativeBuildToolchainChecks(){let t=[`@gjsify/http-soup-bridge`,`@gjsify/http2-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`,`@gjsify/rolldown-native`,`@gjsify/sab-native`,`@gjsify/terminal-native`,`@gjsify/tls-native`,`@gjsify/webgl`,`@gjsify/webrtc-native`];return[checkBinary(`ninja`,`Ninja`,`ninja`,[`--version`],`optional`,void 0,t),checkBinary(`vala`,`Vala`,`valac`,[`--version`],`optional`,t=>t.replace(/^Vala\s+/i,``),t),checkBinary(`cargo`,`Cargo (Rust)`,`cargo`,[`--version`],`optional`,t=>t.replace(/^cargo\s+/i,``).split(` `)[0]??t,[`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`,`@gjsify/rolldown-native`])]}function runOptionalChecks(t,n){let S=[];for(let[n,C]of Object.entries(
|
|
783
|
-
`):null}function readGirsLibraryVersion(t,n){for(let S of[pathToFileURL(xn(t,`_girs_.js`)).href,import.meta.url]){let t;try{t=wn(createRequire(S).resolve(n))}catch{continue}for(let S=0;S<5;S++){let S=xn(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`));if(t.name===n)return t.libraryVersion??null}catch{return null}let C=wn(t);if(C===t)break;t=C}}return null}function majorMinor(t){let n=/^(\d+)\.(\d+)/.exec(t.trim());return n?[Number(n[1]),Number(n[2])]:null}function isDegenerate(t,n){let S=t.trim(),C=n.split(`.`);for(let t=C.length;t<=3;t++)if(S===[...C,...Array(t-C.length).fill(`0`)].join(`.`))return!0;return!1}function checkTypeSkew(t,n={}){let S=n.readDeclared??readGirsLibraryVersion,C=n.readInstalled??(t=>tryExecFile(`pkg-config`,[`--modversion`,t])),N=[];for(let n of
|
|
781
|
+
`)[0],severity:F,requiredBy:I}}function checkNpmPackage(t,n,S,C,N,F){try{return createRequire(pathToFileURL(xn(C,`_check_.js`)).href).resolve(S),{id:t,name:n,found:!0,severity:N,requiredBy:F}}catch{}try{return createRequire(import.meta.url).resolve(S),{id:t,name:n,found:!0,severity:N,requiredBy:F}}catch{return{id:t,name:n,found:!1,severity:N,requiredBy:F}}}function detectPackageManager$1(){if(process.platform===`win32`)return tryExecFile(`where`,[`winget`])===null?`unknown`:`winget`;let t=process.platform===`darwin`?[`brew`]:[`apt`,`dnf`,`pacman`,`zypper`,`apk`,`brew`];for(let n of t)if(isOnPath(n))return n;return`unknown`}function checkMsvcRuntime(){let t=process.env.SystemRoot??process.env.SYSTEMROOT??`C:\\Windows`,n=[`vcruntime140.dll`,`vcruntime140_1.dll`,`msvcp140.dll`].filter(n=>!existsSync(`${t}\\System32\\${n}`));return{id:`msvc-runtime`,name:n.length===0?`Microsoft Visual C++ runtime`:`Microsoft Visual C++ runtime (missing ${n.join(`, `)} — the GTK bundle's DLLs are MSVC-ABI and will not load)`,found:n.length===0,severity:`required`}}function missingSystemDepsFor(t){let n=WP[t];if(!n)return[];let S=[];for(let C of n){let n=UP[C];if(!n?.pkgName)continue;let N=checkPkgConfig(n.id,n.name,n.pkgName,`optional`,[t]);N.found||S.push(N)}return S}function findProjectRoot(t){let n=vn(t);for(;;){if(existsSync(xn(n,`package.json`)))return n;let t=vn(n,`..`);if(t===n)return null;n=t}}function discoverGjsifyPackages(t){let n=findProjectRoot(t);if(!n)return null;let S=xn(n,`node_modules`,`@gjsify`);if(!existsSync(S))return new Set;let C=xn(n,`package.json`),N={};try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{}let F={...N.dependencies,...N.devDependencies},I=new Set;try{for(let t of readdirSync(S,{withFileTypes:!0}))(t.isDirectory()||t.isSymbolicLink())&&I.add(`@gjsify/${t.name}`)}catch{}for(let t of Object.keys(F))t.startsWith(`@gjsify/`)&&I.add(t);return I}function computeNeededOptionalDeps(t){let n=discoverGjsifyPackages(t);if(n===null)return null;let S=new Set;for(let t of n){let n=WP[t];if(n)for(let t of n)S.add(t)}return S}function runAllChecks(t){let n=computeNeededOptionalDeps(t);return[...runMinimalChecks(),...runRequiredChecks(t),...runNativeBuildToolchainChecks(),...runOptionalChecks(n,t)]}function checkNodeRuntime(){return isNode()?{id:`nodejs`,name:`Node.js`,found:!0,version:process.version,severity:`optional`}:checkBinary(`nodejs`,`Node.js`,`node`,[`--version`],`optional`)}function runMinimalChecks(){let t=[];return t.push(checkNodeRuntime()),t.push(checkBinary(`gjs`,`GJS`,`gjs`,[`--version`],`required`,t=>t.replace(/^GJS\s+/i,``).split(`
|
|
782
|
+
`)[0]??t)),process.platform===`win32`&&t.push(checkMsvcRuntime()),t}function checkGwebgl(t){return checkNpmPackage(`gwebgl`,`gwebgl (@gjsify/webgl)`,`@gjsify/webgl`,t,`optional`,[`@gjsify/webgl`])}function runRequiredChecks(t){let n=[];return n.push(checkBinary(`pkg-config`,`pkg-config`,`pkg-config`,[`--version`],`required`)),n.push(checkBinary(`meson`,`Meson`,`meson`,[`--version`],`required`)),n.push(checkGiLibrary(`gtk4`,`GTK4`,`Gtk`,`4.0`,`gtk4`,`required`)),n.push(checkGiLibrary(`libadwaita`,`libadwaita`,`Adw`,`1`,`libadwaita-1`,`required`)),n.push(checkGiLibrary(`libsoup3`,`libsoup3`,`Soup`,`3.0`,`libsoup-3.0`,`required`)),n.push(checkPkgConfig(`gobject-introspection`,`GObject Introspection`,`gobject-introspection-1.0`,`required`)),n}function runNativeBuildToolchainChecks(){let t=[`@gjsify/http-soup-bridge`,`@gjsify/http2-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`,`@gjsify/rolldown-native`,`@gjsify/sab-native`,`@gjsify/terminal-native`,`@gjsify/tls-native`,`@gjsify/webgl`,`@gjsify/webrtc-native`];return[checkBinary(`ninja`,`Ninja`,`ninja`,[`--version`],`optional`,void 0,t),checkBinary(`vala`,`Vala`,`valac`,[`--version`],`optional`,t=>t.replace(/^Vala\s+/i,``),t),checkBinary(`cargo`,`Cargo (Rust)`,`cargo`,[`--version`],`optional`,t=>t.replace(/^cargo\s+/i,``).split(` `)[0]??t,[`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`,`@gjsify/rolldown-native`])]}function runOptionalChecks(t,n){let S=[];for(let[n,C]of Object.entries(UP)){if(t!==null&&!t.has(n))continue;let N=Object.entries(WP).filter(([,t])=>t.includes(n)).map(([t])=>t);S.push(checkPkgConfig(C.id,C.name,C.pkgName,`optional`,N))}return(t===null||t.has(`gwebgl`))&&S.push(checkGwebgl(n)),S}function buildInstallCommand(t,n){if(t===`unknown`)return null;let S=GP[t],C=[],N=[];for(let t of n){if(t.id===`gwebgl`){N.push(`@gjsify/webgl`);continue}let n=S[t.id];n&&C.push(n)}let F=[];return C.length>0&&F.push(`${KP[t]} ${[...new Set(C)].join(` `)}`),N.length>0&&F.push(`npm install ${N.join(` `)}`),F.length>0?F.join(`
|
|
783
|
+
`):null}function readGirsLibraryVersion(t,n){for(let S of[pathToFileURL(xn(t,`_girs_.js`)).href,import.meta.url]){let t;try{t=wn(createRequire(S).resolve(n))}catch{continue}for(let S=0;S<5;S++){let S=xn(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`));if(t.name===n)return t.libraryVersion??null}catch{return null}let C=wn(t);if(C===t)break;t=C}}return null}function majorMinor(t){let n=/^(\d+)\.(\d+)/.exec(t.trim());return n?[Number(n[1]),Number(n[2])]:null}function isDegenerate(t,n){let S=t.trim(),C=n.split(`.`);for(let t=C.length;t<=3;t++)if(S===[...C,...Array(t-C.length).fill(`0`)].join(`.`))return!0;return!1}function checkTypeSkew(t,n={}){let S=n.readDeclared??readGirsLibraryVersion,C=n.readInstalled??(t=>tryExecFile(`pkg-config`,[`--modversion`,t])),N=[];for(let n of qP){let F=S(t,n.typePackage);if(F===null||isDegenerate(F,n.namespaceVersion))continue;let I=C(n.pkgConfig);if(I===null)continue;let H=majorMinor(F),W=majorMinor(I.split(`
|
|
784
784
|
`)[0]??I);!H||!W||H[0]===W[0]&&H[1]===W[1]||N.push({typePackage:n.typePackage,pkgConfig:n.pkgConfig,declared:F,installed:I.split(`
|
|
785
|
-
`)[0]??I,relation:H[0]>W[0]||H[0]===W[0]&&H[1]>W[1]?`ahead`:`behind`})}return N}var HP,UP,WP,GP,KP,qP=__esmMin(()=>{w_(),jn(),Al(),Hn(),Md(),t_(),VP(),j_(),k_(),__name$1(detectPackageManager$1,`detectPackageManager`),HP={manette:{id:`manette`,name:`libmanette`,pkgName:`manette-0.2`},gstreamer:{id:`gstreamer`,name:`GStreamer`,pkgName:`gstreamer-1.0`},"gst-app":{id:`gst-app`,name:`GStreamer App`,pkgName:`gstreamer-app-1.0`},"gdk-pixbuf":{id:`gdk-pixbuf`,name:`GdkPixbuf`,pkgName:`gdk-pixbuf-2.0`},pango:{id:`pango`,name:`Pango`,pkgName:`pango`},pangocairo:{id:`pangocairo`,name:`PangoCairo`,pkgName:`pangocairo`},webkitgtk:{id:`webkitgtk`,name:`WebKitGTK`,pkgName:`webkitgtk-6.0`},cairo:{id:`cairo`,name:`Cairo`,pkgName:`cairo`},gnutls:{id:`gnutls`,name:`GnuTLS`,pkgName:`gnutls`},nghttp2:{id:`nghttp2`,name:`libnghttp2`,pkgName:`libnghttp2`},"json-glib":{id:`json-glib`,name:`JSON-GLib`,pkgName:`json-glib-1.0`},epoxy:{id:`epoxy`,name:`libepoxy`,pkgName:`epoxy`},"gst-webrtc":{id:`gst-webrtc`,name:`GStreamer WebRTC`,pkgName:`gstreamer-webrtc-1.0`}},UP={"@gjsify/gamepad":[`manette`],"@gjsify/webaudio":[`gstreamer`,`gst-app`],"@gjsify/iframe":[`webkitgtk`],"@gjsify/canvas2d":[`gdk-pixbuf`,`pango`,`pangocairo`,`cairo`],"@gjsify/canvas2d-core":[`gdk-pixbuf`,`pango`,`pangocairo`,`cairo`],"@gjsify/dom-elements":[`gdk-pixbuf`],"@gjsify/webgl":[`gwebgl`,`gdk-pixbuf`,`epoxy`],"@gjsify/tls-native":[`gnutls`],"@gjsify/http2-native":[`nghttp2`],"@gjsify/rolldown-native":[`json-glib`],"@gjsify/webrtc-native":[`gstreamer`,`gst-webrtc`]},WP={apt:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkg-config`,meson:`meson`,ninja:`ninja-build`,vala:`valac`,cargo:`cargo`,gtk4:`libgtk-4-dev`,libadwaita:`libadwaita-1-dev`,libsoup3:`libsoup-3.0-dev`,webkitgtk:`libwebkit2gtk-6.0-dev`,"gobject-introspection":`gobject-introspection libgirepository1.0-dev`,manette:`libmanette-0.2-0 gir1.2-manette-0.2`,gstreamer:`libgstreamer1.0-dev`,"gst-app":`libgstreamer-plugins-base1.0-dev gir1.2-gst-plugins-base-1.0`,"gdk-pixbuf":`libgdk-pixbuf-2.0-dev`,pango:`libpango1.0-dev`,pangocairo:`libpango1.0-dev`,cairo:`libcairo2-dev`,gnutls:`libgnutls28-dev`,nghttp2:`libnghttp2-dev`,"json-glib":`libjson-glib-dev`,epoxy:`libepoxy-dev`},dnf:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf-pkg-config`,meson:`meson`,ninja:`ninja-build`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4-devel`,libadwaita:`libadwaita-devel`,libsoup3:`libsoup3-devel`,webkitgtk:`webkitgtk6.0-devel`,"gobject-introspection":`gobject-introspection-devel`,manette:`libmanette-devel`,gstreamer:`gstreamer1-devel`,"gst-app":`gstreamer1-plugins-base-devel`,"gdk-pixbuf":`gdk-pixbuf2-devel`,pango:`pango-devel`,pangocairo:`pango-devel`,cairo:`cairo-devel`,gnutls:`gnutls-devel`,nghttp2:`libnghttp2-devel`,"json-glib":`json-glib-devel`,epoxy:`libepoxy-devel`},pacman:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`rust`,gtk4:`gtk4`,libadwaita:`libadwaita`,libsoup3:`libsoup3`,webkitgtk:`webkitgtk-6.0`,"gobject-introspection":`gobject-introspection`,manette:`libmanette`,gstreamer:`gstreamer`,"gst-app":`gst-plugins-base`,"gdk-pixbuf":`gdk-pixbuf2`,pango:`pango`,pangocairo:`pango`,cairo:`cairo`,gnutls:`gnutls`,nghttp2:`libnghttp2`,"json-glib":`json-glib`,epoxy:`libepoxy`},zypper:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkg-config`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4-devel`,libadwaita:`libadwaita-devel`,libsoup3:`libsoup-3_0-devel`,webkitgtk:`webkitgtk6_0-devel`,"gobject-introspection":`gobject-introspection-devel`,manette:`libmanette-0_2-0-devel`,gstreamer:`gstreamer-devel`,"gst-app":`gstreamer-plugins-base-devel`,"gdk-pixbuf":`gdk-pixbuf-devel`,pango:`pango-devel`,pangocairo:`pango-devel`,cairo:`cairo-devel`,gnutls:`libgnutls-devel`,nghttp2:`libnghttp2-devel`,"json-glib":`json-glib-devel`,epoxy:`libepoxy-devel`},apk:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4.0-dev`,libadwaita:`libadwaita-dev`,libsoup3:`libsoup3-dev`,webkitgtk:`webkit2gtk-6.0-dev`,"gobject-introspection":`gobject-introspection-dev`,manette:`libmanette-dev`,gstreamer:`gstreamer-dev`,"gst-app":`gst-plugins-base-dev`,"gdk-pixbuf":`gdk-pixbuf-dev`,pango:`pango-dev`,pangocairo:`pango-dev`,cairo:`cairo-dev`,gnutls:`gnutls-dev`,nghttp2:`nghttp2-dev`,"json-glib":`json-glib-dev`,epoxy:`libepoxy-dev`},brew:{nodejs:`node`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`rust`,gtk4:`gtk4`,libadwaita:`libadwaita`,libsoup3:`libsoup`,"gobject-introspection":`gobject-introspection`,gstreamer:`gstreamer`,"gst-app":`gst-plugins-base`,"gdk-pixbuf":`gdk-pixbuf`,pango:`pango`,pangocairo:`pango`,cairo:`cairo`,gnutls:`gnutls`,nghttp2:`nghttp2`,"json-glib":`json-glib`,epoxy:`libepoxy`},winget:{"msvc-runtime":`Microsoft.VCRedist.2015+.x64`},unknown:{}},GP={apt:`sudo apt install`,dnf:`sudo dnf install`,pacman:`sudo pacman -S`,zypper:`sudo zypper install`,apk:`sudo apk add`,brew:`brew install`,winget:`winget install --id`,unknown:``},KP=[{pkgConfig:`gtk4`,typePackage:`@girs/gtk-4.0`,namespaceVersion:`4.0`},{pkgConfig:`libadwaita-1`,typePackage:`@girs/adw-1`,namespaceVersion:`1`},{pkgConfig:`libsoup-3.0`,typePackage:`@girs/soup-3.0`,namespaceVersion:`3.0`},{pkgConfig:`glib-2.0`,typePackage:`@girs/glib-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gobject-2.0`,typePackage:`@girs/gobject-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gio-2.0`,typePackage:`@girs/gio-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gstreamer-1.0`,typePackage:`@girs/gst-1.0`,namespaceVersion:`1.0`},{pkgConfig:`webkitgtk-6.0`,typePackage:`@girs/webkit-6.0`,namespaceVersion:`6.0`},{pkgConfig:`manette-0.2`,typePackage:`@girs/manette-0.2`,namespaceVersion:`0.2`},{pkgConfig:`pango`,typePackage:`@girs/pango-1.0`,namespaceVersion:`1.0`},{pkgConfig:`harfbuzz`,typePackage:`@girs/harfbuzz-0.0`,namespaceVersion:`0.0`}]});function parsePlatformToken(t){let n=t.endsWith(XP),S=n?t.slice(0,-5):t,C=S.indexOf(`-`),N=C<0?S:S.slice(0,C);return{os:N,arch:C<0?``:S.slice(C+1),libc:n&&N===`linux`?`musl`:null}}function canonicalPlatformToken(t){let{os:n,arch:S,libc:C}=parsePlatformToken(t);if(!S)return t;let N=`${n}-${YP[S]??S}`;return C===`musl`||t.endsWith(XP)?`${N}${XP}`:N}function hostPlatformTokens(t,n,S){let C=`${t}-${n}`;return S===`musl`&&t===`linux`?[`${C}${XP}`,C]:[C]}function prebuildDirCandidates(t,n,S,C){let N=hostPlatformTokens(t,n,C),F=JP[n]??n,I=[],push=t=>{I.includes(t)||I.push(t)};for(let t of N){for(let n of S??[])typeof n==`string`&&canonicalPlatformToken(n)===t&&push(n);push(t)}return push(`${t}-${F}`),I}function resolvePrebuildDirName(t){let{platform:n,arch:S,declaredPlatforms:C,existingDirs:N,libc:F}=t;for(let t of prebuildDirCandidates(n,S,C,F))if(N.includes(t))return t;return null}function platformPackageName(t,n){return`${t}-${n}`}function scanNodeModules(t,n){let S=[],C=[];if(!existsSync(t))return{resolved:S,declared:C};let N;try{N=readdirSync(t)}catch{return{resolved:S,declared:C}}let take=t=>{t&&(t.kind===`resolved`?S.push(t.pkg):C.push(t.candidate))};for(let S of N)if(!S.startsWith(`.`))if(S.startsWith(`@`)){let C=xn(t,S),N;try{N=readdirSync(C)}catch{continue}for(let t of N)take(checkPackage(xn(C,t),`${S}/${t}`,n))}else take(checkPackage(xn(t,S),S,n));return{resolved:S,declared:C}}function checkPackage(t,n,S){let C=readPackageJson$2(xn(t,`package.json`));if(!C)return null;let N=C.gjsify;if(!N||typeof N!=`object`)return null;let F=N,I=F.prebuilds;if(typeof I!=`string`)return null;let H=F.platforms,W=Array.isArray(H)?H.filter(t=>typeof t==`string`):void 0,q=xn(t,I),Y;try{Y=readdirSync(q,{withFileTypes:!0}).filter(t=>t.isDirectory()||t.isSymbolicLink()).map(t=>t.name)}catch{return{kind:`declared`,candidate:{name:n,pkgDir:t}}}let X=resolvePrebuildDirName({platform:S.platform,arch:S.arch,declaredPlatforms:W,existingDirs:Y,libc:S.libc});return X?{kind:`resolved`,pkg:{name:n,prebuildsDir:xn(q,X)}}:{kind:`declared`,candidate:{name:n,pkgDir:t}}}function resolvePlatformSibling(t,n){let S=hostPlatformTokens(n.platform,n.arch,n.libc),C=vn(t.pkgDir);for(;;){for(let N of S){let S=platformPackageName(t.name,N),F=checkPackage(xn(C,`node_modules`,...S.split(`/`)),S,n);if(F?.kind===`resolved`)return F.pkg}let N=vn(C,`..`);if(N===C)return null;C=N}}function detectNativePackages(t,n={}){let S={platform:n.platform??process.platform,arch:n.arch??process.arch,libc:n.libc===void 0?detectHostLibc(n.platform??process.platform):n.libc},C=[],N=new Set,F=[],I=vn(t);for(;;){let t=xn(I,`node_modules`);if(existsSync(t)){let n=scanNodeModules(t,S);for(let t of n.resolved)N.has(t.name)||(N.add(t.name),C.push(t));for(let t of n.declared)F.some(n=>n.name===t.name)||F.push(t)}let n=vn(I,`..`);if(n===I)break;I=n}for(let t of F){if(N.has(t.name))continue;let n=resolvePlatformSibling(t,S);!n||N.has(n.name)||(N.add(n.name),C.push(n))}return C}function resolveHostLibc(t){return t.platform===`linux`?typeof t.glibcVersionRuntime==`string`&&t.glibcVersionRuntime.length>0?`glibc`:t.muslLoaderPresent?`musl`:`glibc`:null}function detectHostLibc(t){if(t!==`linux`)return null;let n=process.report?.getReport()?.header;return resolveHostLibc({platform:t,glibcVersionRuntime:typeof n?.glibcVersionRuntime==`string`?n.glibcVersionRuntime:void 0,muslLoaderPresent:existsSync(`/lib`)&&readdirSync(`/lib`).some(t=>t.startsWith(`ld-musl-`))})}function muslPrebuildFallbacks(t,n){return t===`musl`?n.filter(t=>parsePlatformToken(Tn(t.prebuildsDir)).libc!==`musl`).map(t=>t.name):[]}function libraryPathVar(t){return t===`darwin`?{name:`DYLD_LIBRARY_PATH`,separator:`:`}:t===`win32`?{name:`PATH`,separator:`;`}:{name:`LD_LIBRARY_PATH`,separator:`:`}}function buildNativeEnv(t,n={}){let S=n.platform??process.platform,C=n.env??process.env,N=t.map(t=>t.prebuildsDir),F=S===`win32`?`;`:`:`,{name:I,separator:H}=libraryPathVar(S),W=S===`win32`?Object.keys(C).find(t=>t.toLowerCase()===I.toLowerCase())??I:I,prepend=(t,n)=>[...N,...t?[t]:[]].join(n),q={GI_TYPELIB_PATH:prepend(C.GI_TYPELIB_PATH,F)};q[W]=prepend(C[W],H);let Y=(n.systemGiDirs??systemGiLibraryDirs)({platform:S,env:C});return Y.length>0&&(q[ZP]=composeDyldFallback(Y,C)),q}var JP,YP,XP,ZP,QP=__esmMin(()=>{Md(),jn(),OP(),RP(),JP={x64:`x86_64`,arm64:`aarch64`,arm:`armv7`,ia32:`i686`},YP={x86_64:`x64`,amd64:`x64`,aarch64:`arm64`},XP=`-musl`,ZP=`DYLD_FALLBACK_LIBRARY_PATH`});function defaultRepository(){let t=(globalThis.imports?.gi)?.GIRepository?.Repository;return typeof t?.dup_default==`function`?t.dup_default():null}function activateNativePrebuilds(){if($P)return $P;$P=[];try{let t=defaultRepository();if(!t)return $P;let n=detectNativePackages(process.cwd()),S=new Set(n.map(t=>t.name)),C=detectNativePackages(wn(fileURLToPath(import.meta.url))),N=[...n,...C.filter(t=>!S.has(t.name))];for(let n of N)t.prepend_search_path(n.prebuildsDir),t.prepend_library_path(n.prebuildsDir);$P=N}catch{}return $P}var $P,eF=__esmMin(()=>{jn(),Hn(),QP(),$P=null});async function loadNpmRolldown(){if(isGjs())throw Error("gjsify build: no usable bundler engine under GJS — `@gjsify/rolldown-native` is not loadable, and the npm `rolldown` engine is a Rust napi crate that cannot run under GJS.\n"+diagnoseNativeEngine());return(await import(resolveImportTargetForGjs(`rolldown`))).rolldown}function diagnoseNativeEngine(){let t=null;try{let n=wn(fileURLToPath(import.meta.url));t=findRolldownNativeDir(process.cwd(),n)}catch{t=null}if(t===null)return`\`@gjsify/rolldown-native\` is NOT INSTALLED — no node_modules/@gjsify/rolldown-native was found walking up from ${process.cwd()} or from the CLI bundle's own directory.\nInstall it: \`gjsify install @gjsify/rolldown-native\` (in the gjsify repo: \`gjsify install\`). Running the build under Node also works — there the npm \`rolldown\` crate is used instead.`;let n=xn(t,`lib`,`esm`,`index.js`);if(!existsSync(n))return`The engine's JS facade is NOT BUILT: ${n} does not exist.\nIt is a BUILD OUTPUT, so this is almost certainly a clone of the gjsify REPOSITORY rather than a consumer install: in a clone, node_modules/@gjsify/rolldown-native is a symlink to the workspace package, whose \`lib/\` no \`gjsify install\` produces. An installed package from npm is NOT affected — the published tarball does contain \`lib/esm/index.js\` (verified against 0.26.1), so a consumer that hit this message should report it.
|
|
785
|
+
`)[0]??I,relation:H[0]>W[0]||H[0]===W[0]&&H[1]>W[1]?`ahead`:`behind`})}return N}var UP,WP,GP,KP,qP,JP=__esmMin(()=>{w_(),jn(),Al(),Hn(),Md(),t_(),HP(),j_(),k_(),__name$1(detectPackageManager$1,`detectPackageManager`),UP={manette:{id:`manette`,name:`libmanette`,pkgName:`manette-0.2`},gstreamer:{id:`gstreamer`,name:`GStreamer`,pkgName:`gstreamer-1.0`},"gst-app":{id:`gst-app`,name:`GStreamer App`,pkgName:`gstreamer-app-1.0`},"gdk-pixbuf":{id:`gdk-pixbuf`,name:`GdkPixbuf`,pkgName:`gdk-pixbuf-2.0`},pango:{id:`pango`,name:`Pango`,pkgName:`pango`},pangocairo:{id:`pangocairo`,name:`PangoCairo`,pkgName:`pangocairo`},webkitgtk:{id:`webkitgtk`,name:`WebKitGTK`,pkgName:`webkitgtk-6.0`},cairo:{id:`cairo`,name:`Cairo`,pkgName:`cairo`},gnutls:{id:`gnutls`,name:`GnuTLS`,pkgName:`gnutls`},nghttp2:{id:`nghttp2`,name:`libnghttp2`,pkgName:`libnghttp2`},"json-glib":{id:`json-glib`,name:`JSON-GLib`,pkgName:`json-glib-1.0`},epoxy:{id:`epoxy`,name:`libepoxy`,pkgName:`epoxy`},"gst-webrtc":{id:`gst-webrtc`,name:`GStreamer WebRTC`,pkgName:`gstreamer-webrtc-1.0`}},WP={"@gjsify/gamepad":[`manette`],"@gjsify/webaudio":[`gstreamer`,`gst-app`],"@gjsify/iframe":[`webkitgtk`],"@gjsify/canvas2d":[`gdk-pixbuf`,`pango`,`pangocairo`,`cairo`],"@gjsify/canvas2d-core":[`gdk-pixbuf`,`pango`,`pangocairo`,`cairo`],"@gjsify/dom-elements":[`gdk-pixbuf`],"@gjsify/webgl":[`gwebgl`,`gdk-pixbuf`,`epoxy`],"@gjsify/tls-native":[`gnutls`],"@gjsify/http2-native":[`nghttp2`],"@gjsify/rolldown-native":[`json-glib`],"@gjsify/webrtc-native":[`gstreamer`,`gst-webrtc`]},GP={apt:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkg-config`,meson:`meson`,ninja:`ninja-build`,vala:`valac`,cargo:`cargo`,gtk4:`libgtk-4-dev`,libadwaita:`libadwaita-1-dev`,libsoup3:`libsoup-3.0-dev`,webkitgtk:`libwebkit2gtk-6.0-dev`,"gobject-introspection":`gobject-introspection libgirepository1.0-dev`,manette:`libmanette-0.2-0 gir1.2-manette-0.2`,gstreamer:`libgstreamer1.0-dev`,"gst-app":`libgstreamer-plugins-base1.0-dev gir1.2-gst-plugins-base-1.0`,"gdk-pixbuf":`libgdk-pixbuf-2.0-dev`,pango:`libpango1.0-dev`,pangocairo:`libpango1.0-dev`,cairo:`libcairo2-dev`,gnutls:`libgnutls28-dev`,nghttp2:`libnghttp2-dev`,"json-glib":`libjson-glib-dev`,epoxy:`libepoxy-dev`},dnf:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf-pkg-config`,meson:`meson`,ninja:`ninja-build`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4-devel`,libadwaita:`libadwaita-devel`,libsoup3:`libsoup3-devel`,webkitgtk:`webkitgtk6.0-devel`,"gobject-introspection":`gobject-introspection-devel`,manette:`libmanette-devel`,gstreamer:`gstreamer1-devel`,"gst-app":`gstreamer1-plugins-base-devel`,"gdk-pixbuf":`gdk-pixbuf2-devel`,pango:`pango-devel`,pangocairo:`pango-devel`,cairo:`cairo-devel`,gnutls:`gnutls-devel`,nghttp2:`libnghttp2-devel`,"json-glib":`json-glib-devel`,epoxy:`libepoxy-devel`},pacman:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`rust`,gtk4:`gtk4`,libadwaita:`libadwaita`,libsoup3:`libsoup3`,webkitgtk:`webkitgtk-6.0`,"gobject-introspection":`gobject-introspection`,manette:`libmanette`,gstreamer:`gstreamer`,"gst-app":`gst-plugins-base`,"gdk-pixbuf":`gdk-pixbuf2`,pango:`pango`,pangocairo:`pango`,cairo:`cairo`,gnutls:`gnutls`,nghttp2:`libnghttp2`,"json-glib":`json-glib`,epoxy:`libepoxy`},zypper:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkg-config`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4-devel`,libadwaita:`libadwaita-devel`,libsoup3:`libsoup-3_0-devel`,webkitgtk:`webkitgtk6_0-devel`,"gobject-introspection":`gobject-introspection-devel`,manette:`libmanette-0_2-0-devel`,gstreamer:`gstreamer-devel`,"gst-app":`gstreamer-plugins-base-devel`,"gdk-pixbuf":`gdk-pixbuf-devel`,pango:`pango-devel`,pangocairo:`pango-devel`,cairo:`cairo-devel`,gnutls:`libgnutls-devel`,nghttp2:`libnghttp2-devel`,"json-glib":`json-glib-devel`,epoxy:`libepoxy-devel`},apk:{nodejs:`nodejs`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`cargo`,gtk4:`gtk4.0-dev`,libadwaita:`libadwaita-dev`,libsoup3:`libsoup3-dev`,webkitgtk:`webkit2gtk-6.0-dev`,"gobject-introspection":`gobject-introspection-dev`,manette:`libmanette-dev`,gstreamer:`gstreamer-dev`,"gst-app":`gst-plugins-base-dev`,"gdk-pixbuf":`gdk-pixbuf-dev`,pango:`pango-dev`,pangocairo:`pango-dev`,cairo:`cairo-dev`,gnutls:`gnutls-dev`,nghttp2:`nghttp2-dev`,"json-glib":`json-glib-dev`,epoxy:`libepoxy-dev`},brew:{nodejs:`node`,gjs:`gjs`,"pkg-config":`pkgconf`,meson:`meson`,ninja:`ninja`,vala:`vala`,cargo:`rust`,gtk4:`gtk4`,libadwaita:`libadwaita`,libsoup3:`libsoup`,"gobject-introspection":`gobject-introspection`,gstreamer:`gstreamer`,"gst-app":`gst-plugins-base`,"gdk-pixbuf":`gdk-pixbuf`,pango:`pango`,pangocairo:`pango`,cairo:`cairo`,gnutls:`gnutls`,nghttp2:`nghttp2`,"json-glib":`json-glib`,epoxy:`libepoxy`},winget:{"msvc-runtime":`Microsoft.VCRedist.2015+.x64`},unknown:{}},KP={apt:`sudo apt install`,dnf:`sudo dnf install`,pacman:`sudo pacman -S`,zypper:`sudo zypper install`,apk:`sudo apk add`,brew:`brew install`,winget:`winget install --id`,unknown:``},qP=[{pkgConfig:`gtk4`,typePackage:`@girs/gtk-4.0`,namespaceVersion:`4.0`},{pkgConfig:`libadwaita-1`,typePackage:`@girs/adw-1`,namespaceVersion:`1`},{pkgConfig:`libsoup-3.0`,typePackage:`@girs/soup-3.0`,namespaceVersion:`3.0`},{pkgConfig:`glib-2.0`,typePackage:`@girs/glib-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gobject-2.0`,typePackage:`@girs/gobject-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gio-2.0`,typePackage:`@girs/gio-2.0`,namespaceVersion:`2.0`},{pkgConfig:`gstreamer-1.0`,typePackage:`@girs/gst-1.0`,namespaceVersion:`1.0`},{pkgConfig:`webkitgtk-6.0`,typePackage:`@girs/webkit-6.0`,namespaceVersion:`6.0`},{pkgConfig:`manette-0.2`,typePackage:`@girs/manette-0.2`,namespaceVersion:`0.2`},{pkgConfig:`pango`,typePackage:`@girs/pango-1.0`,namespaceVersion:`1.0`},{pkgConfig:`harfbuzz`,typePackage:`@girs/harfbuzz-0.0`,namespaceVersion:`0.0`}]});function parsePlatformToken(t){let n=t.endsWith(ZP),S=n?t.slice(0,-5):t,C=S.indexOf(`-`),N=C<0?S:S.slice(0,C);return{os:N,arch:C<0?``:S.slice(C+1),libc:n&&N===`linux`?`musl`:null}}function canonicalPlatformToken(t){let{os:n,arch:S,libc:C}=parsePlatformToken(t);if(!S)return t;let N=`${n}-${XP[S]??S}`;return C===`musl`||t.endsWith(ZP)?`${N}${ZP}`:N}function hostPlatformTokens(t,n,S){let C=`${t}-${n}`;return S===`musl`&&t===`linux`?[`${C}${ZP}`,C]:[C]}function prebuildDirCandidates(t,n,S,C){let N=hostPlatformTokens(t,n,C),F=YP[n]??n,I=[],push=t=>{I.includes(t)||I.push(t)};for(let t of N){for(let n of S??[])typeof n==`string`&&canonicalPlatformToken(n)===t&&push(n);push(t)}return push(`${t}-${F}`),I}function resolvePrebuildDirName(t){let{platform:n,arch:S,declaredPlatforms:C,existingDirs:N,libc:F}=t;for(let t of prebuildDirCandidates(n,S,C,F))if(N.includes(t))return t;return null}function platformPackageName(t,n){return`${t}-${n}`}function scanNodeModules(t,n){let S=[],C=[];if(!existsSync(t))return{resolved:S,declared:C};let N;try{N=readdirSync(t)}catch{return{resolved:S,declared:C}}let take=t=>{t&&(t.kind===`resolved`?S.push(t.pkg):C.push(t.candidate))};for(let S of N)if(!S.startsWith(`.`))if(S.startsWith(`@`)){let C=xn(t,S),N;try{N=readdirSync(C)}catch{continue}for(let t of N)take(checkPackage(xn(C,t),`${S}/${t}`,n))}else take(checkPackage(xn(t,S),S,n));return{resolved:S,declared:C}}function checkPackage(t,n,S){let C=readPackageJson$2(xn(t,`package.json`));if(!C)return null;let N=C.gjsify;if(!N||typeof N!=`object`)return null;let F=N,I=F.prebuilds;if(typeof I!=`string`)return null;let H=F.platforms,W=Array.isArray(H)?H.filter(t=>typeof t==`string`):void 0,q=xn(t,I),Y;try{Y=readdirSync(q,{withFileTypes:!0}).filter(t=>t.isDirectory()||t.isSymbolicLink()).map(t=>t.name)}catch{return{kind:`declared`,candidate:{name:n,pkgDir:t}}}let X=resolvePrebuildDirName({platform:S.platform,arch:S.arch,declaredPlatforms:W,existingDirs:Y,libc:S.libc});return X?{kind:`resolved`,pkg:{name:n,prebuildsDir:xn(q,X)}}:{kind:`declared`,candidate:{name:n,pkgDir:t}}}function resolvePlatformSibling(t,n){let S=hostPlatformTokens(n.platform,n.arch,n.libc),C=vn(t.pkgDir);for(;;){for(let N of S){let S=platformPackageName(t.name,N),F=checkPackage(xn(C,`node_modules`,...S.split(`/`)),S,n);if(F?.kind===`resolved`)return F.pkg}let N=vn(C,`..`);if(N===C)return null;C=N}}function detectNativePackages(t,n={}){let S={platform:n.platform??process.platform,arch:n.arch??process.arch,libc:n.libc===void 0?detectHostLibc(n.platform??process.platform):n.libc},C=[],N=new Set,F=[],I=vn(t);for(;;){let t=xn(I,`node_modules`);if(existsSync(t)){let n=scanNodeModules(t,S);for(let t of n.resolved)N.has(t.name)||(N.add(t.name),C.push(t));for(let t of n.declared)F.some(n=>n.name===t.name)||F.push(t)}let n=vn(I,`..`);if(n===I)break;I=n}for(let t of F){if(N.has(t.name))continue;let n=resolvePlatformSibling(t,S);!n||N.has(n.name)||(N.add(n.name),C.push(n))}return C}function resolveHostLibc(t){return t.platform===`linux`?typeof t.glibcVersionRuntime==`string`&&t.glibcVersionRuntime.length>0?`glibc`:t.muslLoaderPresent?`musl`:`glibc`:null}function detectHostLibc(t){if(t!==`linux`)return null;let n=process.report?.getReport()?.header;return resolveHostLibc({platform:t,glibcVersionRuntime:typeof n?.glibcVersionRuntime==`string`?n.glibcVersionRuntime:void 0,muslLoaderPresent:existsSync(`/lib`)&&readdirSync(`/lib`).some(t=>t.startsWith(`ld-musl-`))})}function muslPrebuildFallbacks(t,n){return t===`musl`?n.filter(t=>parsePlatformToken(Tn(t.prebuildsDir)).libc!==`musl`).map(t=>t.name):[]}function libraryPathVar(t){return t===`darwin`?{name:`DYLD_LIBRARY_PATH`,separator:`:`}:t===`win32`?{name:`PATH`,separator:`;`}:{name:`LD_LIBRARY_PATH`,separator:`:`}}function buildNativeEnv(t,n={}){let S=n.platform??process.platform,C=n.env??process.env,N=t.map(t=>t.prebuildsDir),F=S===`win32`?`;`:`:`,{name:I,separator:H}=libraryPathVar(S),W=S===`win32`?Object.keys(C).find(t=>t.toLowerCase()===I.toLowerCase())??I:I,prepend=(t,n)=>[...N,...t?[t]:[]].join(n),q={GI_TYPELIB_PATH:prepend(C.GI_TYPELIB_PATH,F)};q[W]=prepend(C[W],H);let Y=(n.systemGiDirs??systemGiLibraryDirs)({platform:S,env:C});return Y.length>0&&(q[QP]=composeDyldFallback(Y,C)),q}var YP,XP,ZP,QP,$P=__esmMin(()=>{Md(),jn(),kP(),zP(),YP={x64:`x86_64`,arm64:`aarch64`,arm:`armv7`,ia32:`i686`},XP={x86_64:`x64`,amd64:`x64`,aarch64:`arm64`},ZP=`-musl`,QP=`DYLD_FALLBACK_LIBRARY_PATH`});function defaultRepository(){let t=(globalThis.imports?.gi)?.GIRepository?.Repository;return typeof t?.dup_default==`function`?t.dup_default():null}function activateNativePrebuilds(){if(eF)return eF;eF=[];try{let t=defaultRepository();if(!t)return eF;let n=detectNativePackages(process.cwd()),S=new Set(n.map(t=>t.name)),C=detectNativePackages(wn(fileURLToPath(import.meta.url))),N=[...n,...C.filter(t=>!S.has(t.name))];for(let n of N)t.prepend_search_path(n.prebuildsDir),t.prepend_library_path(n.prebuildsDir);eF=N}catch{}return eF}var eF,tF=__esmMin(()=>{jn(),Hn(),$P(),eF=null});async function loadNpmRolldown(){if(isGjs())throw Error("gjsify build: no usable bundler engine under GJS — `@gjsify/rolldown-native` is not loadable, and the npm `rolldown` engine is a Rust napi crate that cannot run under GJS.\n"+diagnoseNativeEngine());return(await import(resolveImportTargetForGjs(`rolldown`))).rolldown}function diagnoseNativeEngine(){let t=null;try{let n=wn(fileURLToPath(import.meta.url));t=findRolldownNativeDir(process.cwd(),n)}catch{t=null}if(t===null)return`\`@gjsify/rolldown-native\` is NOT INSTALLED — no node_modules/@gjsify/rolldown-native was found walking up from ${process.cwd()} or from the CLI bundle's own directory.\nInstall it: \`gjsify install @gjsify/rolldown-native\` (in the gjsify repo: \`gjsify install\`). Running the build under Node also works — there the npm \`rolldown\` crate is used instead.`;let n=xn(t,`lib`,`esm`,`index.js`);if(!existsSync(n))return`The engine's JS facade is NOT BUILT: ${n} does not exist.\nIt is a BUILD OUTPUT, so this is almost certainly a clone of the gjsify REPOSITORY rather than a consumer install: in a clone, node_modules/@gjsify/rolldown-native is a symlink to the workspace package, whose \`lib/\` no \`gjsify install\` produces. An installed package from npm is NOT affected — the published tarball does contain \`lib/esm/index.js\` (verified against 0.26.1), so a consumer that hit this message should report it.
|
|
786
786
|
Build it from the gjsify repo root — both are idempotent and skip already-built facades in seconds, and NEITHER requires Node any more:
|
|
787
787
|
gjsify run build:infra # the full cold-tree chain
|
|
788
788
|
gjsify run --node-script scripts/bootstrap-native-facades.mjs # just the facades
|
|
789
789
|
Under Node the facades are built by the CLI's own Node entry (npm \`rolldown\`); under GJS by the \`gjsify\` on PATH, which carries its own engine when it was installed with \`gjs -m install.mjs\`.
|
|
790
|
-
If you are READING THIS ON A GJS HOST, that global engine is what could not be reached: this workspace symlink shadowed it, because \`require.resolve\` returned the package DIRECTORY instead of failing. That is fixed in \`@gjsify/module\`, so a \`gjsify\` OLDER than the fix still stops here — update it (\`gjs -m install.mjs\`), or seed \`lib/\` from the published package, which ships it.`;let S=[`The JS facade is built, so this is the typelib/prebuild lookup failing.`],C=missingSystemDepsFor(`@gjsify/rolldown-native`),N=C.map(t=>t.name).join(`, `),F=C.length>0?buildInstallCommand(detectPackageManager$1(),C):null,I=C.length===0?void 0:F?`Install it:\n ${F}`:`Install ${N} with your system package manager (this host's manager was not recognised, so no command is suggested rather than a wrong one).`;if(
|
|
791
|
-
`)}function resolveImportTargetForGjs(t){if(!isGjs())return t;let n=resolveNpmPackage(t,{bundleUrl:import.meta.url});return n?pathToFileURL(n).href:t}async function bundleToChunks(t){if(await shouldUseNative()){let n=await tryLoadNative();if(!n)throw Error(`@gjsify/rolldown-native not loadable`);let S=t.rolldownInput.plugins??[],C=[];for(let t of S)isPluginObject(t)&&C.push(toNativePlugin(t));let N=liftTransformExtras(stripUnserializable({...t.rolldownInput,input:normalizeInputForNative(t.rolldownInput.input),format:t.format}));delete N.plugins;let F=await n.bundleWithPlugins(N,C);reportNativeWarnings(F,t.rolldownInput);let I=[];for(let t of F.output)t.type===`chunk`&&I.push(t.code);return I}let n=await(await loadNpmRolldown())(t.rolldownInput);try{let S=await n.generate({format:t.format,minify:!1,sourcemap:!1}),C=[];for(let t of S.output)t.type===`chunk`&&C.push(t.code);return C}finally{await n.close()}}async function runWatch(t){if(await shouldUseNative())throw Error("`gjsify build --watch` requires the npm `rolldown` engine. The native engine (`@gjsify/rolldown-native`) does not expose a watcher API. Run the watch loop under Node (`node lib/index.js build … --watch`) or set `GJSIFY_BUNDLER=npm`.");let n=await import(resolveImportTargetForGjs(`rolldown`)),S=t.output??{};return n.watch({...t,output:S})}function warnNoNativeWatchList(){tF||(tF=!0,ge.warn("[gjsify] this `@gjsify/rolldown-native` build reports no watch list: it predates `addWatchFile`, so a file a plugin read itself (a stylesheet’s `@import` chain, an inlined `readFileSync`) cannot be declared as a build input. `gjsify test` will rebuild the affected bundles on every run rather than trust a set it cannot see. Upgrade the engine (it ships in the same release train as the CLI)."))}async function runBundle(t,n={}){if(await shouldUseNative())return await runNativeBundle(t,n);let S=await(await loadNpmRolldown())(t);try{let C=await S.write(t.output??{});return n.onWatchFiles&&n.onWatchFiles({files:await S.watchFiles,reportedByEngine:!0}),C}finally{await S.close()}}function resolveNativeLibraryModule(t={}){let n=`@gjsify/utils/native-library`;return resolveNpmPackage(n,t)??createRequire(t.bundleUrl??import.meta.url).resolve(n)}async function utilsCore(){return iF===null&&(iF=await import(pathToFileURL(resolveNativeLibraryModule({bundleUrl:import.meta.url})).href)),iF}async function shouldUseNative(){let t=(globalThis.process?.env??{}).GJSIFY_BUNDLER;if(t===`npm`)return!1;if(t===`native`){if(!await tryLoadNative())throw Error(`GJSIFY_BUNDLER=native but @gjsify/rolldown-native is not loadable (no prebuild for this architecture, or not running under GJS).`+(isGjs()?`\n${diagnoseNativeEngine()}`:``));return!0}return isGjs()?await tryLoadNative()!==null:!1}function findRolldownNativeDir(t,n){let S=xn(`node_modules`,`@gjsify`,`rolldown-native`,`package.json`),C=[t];n&&n!==t&&C.push(n);for(let t of C){let n=t;for(let t=0;t<12;t++){if(existsSync(xn(n,S)))return xn(n,`node_modules`,`@gjsify`,`rolldown-native`);let t=vn(n,`..`);if(t===n)break;n=t}}return null}async function tryLoadNative(){return nF||(nF=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let t=`@gjsify/rolldown-native`,n=t;if(isGjs()){let S=wn(fileURLToPath(import.meta.url)),C=resolveNpmPackage(t,{bundleUrl:import.meta.url}),N=C?null:(()=>{let n=findRolldownNativeDir(process.cwd(),S);if(!n)return null;try{return createRequire(pathToFileURL(xn(n,`__gjsify_resolve__.js`)).href).resolve(t)}catch{return null}})();n=pathToFileURL(C??N??createRequire(import.meta.url).resolve(t)).href}let S=await import(n);if(!S.hasNativeRolldown())return null;let C=null;try{C=await utilsCore()}catch(t){aF=t}return C!==null&&(rF=C.probeNativeLibrary(`GjsifyRolldown`),rF)?null:S}catch{return null}})(),nF)}async function runNativeBundle(t,n={}){let S=await tryLoadNative();if(!S)throw Error(`@gjsify/rolldown-native not loadable`);let C=t.plugins??[],N=[];for(let t of C)isPluginObject(t)&&N.push(toNativePlugin(t));let{output:F,plugins:I,...H}=t,W=liftTransformExtras(stripUnserializable({...H,...F,input:normalizeInputForNative(t.input)}));globalThis.process?.env?.GJSIFY_DEBUG_NATIVE_OPTS&&ge.error(`[gjsify-bundler-pick] native opts JSON:`,JSON.stringify(W));let q=await S.bundleWithPlugins(W,N);reportNativeWarnings(q,t),n.onWatchFiles&&(q.watchedFiles===void 0?(warnNoNativeWatchList(),n.onWatchFiles({files:[],reportedByEngine:!1})):n.onWatchFiles({files:q.watchedFiles,reportedByEngine:!0}));let Y=t.output??{},X=Y.dir??(Y.file?wn(Y.file):process.cwd());X&&await pd.mkdir(X,{recursive:!0});for(let t of q.output){let n=Y.file&&t.type===`chunk`&&q.output.length===1?Y.file:xn(X,t.fileName);await pd.mkdir(wn(n),{recursive:!0}),t.type===`chunk`?(await pd.writeFile(n,t.code,`utf8`),typeof t.map==`string`&&await pd.writeFile(`${n}.map`,t.map,`utf8`)):t.sourceText!==void 0&&await pd.writeFile(n,t.sourceText,`utf8`)}return synthRolldownOutput(q)}function reportNativeWarnings(t,n){if(n.logLevel===`silent`||!Array.isArray(t.warnings)||t.warnings.length===0)return;let S=new Set;for(let n of t.warnings)S.has(n)||(S.add(n),ge.warn(`[gjsify-bundler] ${n}`))}function stripUnserializable(t){let n={};for(let[S,C]of Object.entries(t)){if(typeof C==`function`){if(!oF.has(S)){oF.add(S);let t=S===`external`?" Function `external` predicates are NOT supported by the native engine — pass exact names as a string array and/or enforce shape rules via a resolveId plugin returning `{ external: true }` (see externalsPlugin in @gjsify/rolldown-plugin-gjsify).":` Function-valued options do not survive the JSON boundary to the Rust core.`;ge.warn(`[gjsify-bundler] dropping non-serializable option "${S}" for the native rolldown engine — behavior may diverge from npm rolldown.${t}`)}continue}if(S===`external`&&Array.isArray(C)){let t=C.find(t=>typeof t!=`string`);if(t!==void 0)throw Error(`gjsify build: \`external\` entries must be exact string names under the native rolldown engine (got ${t instanceof RegExp?t.toString():typeof t}). RegExp/function externals are only supported by npm rolldown — use exact names or a resolveId plugin returning \`{ external: true }\`.`);n[S]=C;continue}if(S===`sourcemap`){let t=translateSourcemapOption(C);t!==void 0&&(n[S]=t);continue}n[S]=C}return n}function translateSourcemapOption(t){if(t===!0||t===`file`||t===`File`)return`File`;if(t===`inline`||t===`Inline`)return`Inline`;if(t===`hidden`||t===`Hidden`)return`Hidden`}function liftTransformExtras(t){let n=t.transform;if(!n)return t;let S={},C={...n};for(let t of[`define`,`inject`])t in C&&(S[t]=C[t],delete C[t]);return S.inject!==void 0&&!Array.isArray(S.inject)&&(S.inject=mapToInjectArray(S.inject)),{...t,transform:Object.keys(C).length===0?void 0:C,...S}}function mapToInjectArray(t){let n=[];for(let[S,C]of Object.entries(t))if(typeof C==`string`)n.push({type:`named`,imported:`default`,from:C,alias:S});else{let[t,N]=C;N===`*`?n.push({type:`namespace`,from:t,alias:S}):n.push({type:`named`,from:t,imported:N,alias:S})}return n}function normalizeInputForNative(t){return t===void 0?[]:typeof t==`string`?[{import:t}]:Array.isArray(t)?t.map(t=>typeof t==`string`?{import:t}:t):Object.entries(t).map(([t,n])=>({name:t,import:n}))}function isPluginObject(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function pickHook(t){if(typeof t==`function`)return{fn:t};if(typeof t==`object`&&t&&`handler`in t){let n=t,S=filterToRegexSource(n.filter?.id),C={fn:n.handler};return S!==void 0&&(C.idFilter=S),C}}function filterToRegexSource(t){if(t!==void 0){if(Array.isArray(t)){let n=t.map(oneToSource).filter(t=>t!==void 0);return n.length===0?void 0:n.length===1?n[0]:`(?:${n.join(`|`)})`}return oneToSource(t)}}function oneToSource(t){if(t instanceof RegExp)return t.source;if(typeof t==`string`)return t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function toNativePlugin(t){let n={name:typeof t.name==`string`?t.name:`unnamed-plugin`},S={},C=pickHook(t.load);C&&(n.load=C.fn,C.idFilter&&(S.load=C.idFilter));let N=pickHook(t.transform);N&&(n.transform=N.fn,N.idFilter&&(S.transform=N.idFilter));let F=pickHook(t.resolveId);F&&(n.resolveId=F.fn,F.idFilter&&(S.resolveId=F.idFilter));let I=pickHook(t.renderChunk);I&&(n.renderChunk=I.fn);let H=pickHook(t.banner);H&&(n.banner=H.fn);let W=pickHook(t.footer);W&&(n.footer=W.fn);let q=pickHook(t.intro);q&&(n.intro=q.fn);let Y=pickHook(t.outro);Y&&(n.outro=Y.fn);let X=pickHook(t.buildStart);X&&(n.buildStart=X.fn);let Z=pickHook(t.buildEnd);Z&&(n.buildEnd=Z.fn);let te=pickHook(t.generateBundle);te&&(n.generateBundle=te.fn);let ne=pickHook(t.writeBundle);ne&&(n.writeBundle=ne.fn);let re=pickHook(t.closeBundle);return re&&(n.closeBundle=re.fn),Object.keys(S).length>0&&(n.idFilter=S),n}function synthRolldownOutput(t){return{output:t.output.map(t=>t.type===`chunk`?{type:`chunk`,fileName:t.fileName,code:t.code,name:t.name,isEntry:t.isEntry,isDynamicEntry:t.isDynamicEntry,map:t.map??null,sourcemapFileName:t.sourcemapFilename??null,imports:t.imports,dynamicImports:t.dynamicImports,facadeModuleId:null,moduleIds:[],modules:{},exports:[],referencedFiles:[],importedBindings:{}}:{type:`asset`,fileName:t.fileName,names:t.names,originalFileNames:t.originalFileNames,source:t.sourceText??``,needsCodeReference:!1})}}var tF,nF,rF,iF,aF,oF,sF=__esmMin(()=>{_e(),Md(),jn(),Al(),Hn(),jP(),qP(),eF(),t_(),tF=!1,nF=null,rF=null,iF=null,aF=null,oF=new Set});function isPluginByName(t){return typeof t==`object`&&!!t&&typeof t.name==`string`&&!(`apply`in t)&&!(`resolveId`in t)&&!(`load`in t)&&!(`transform`in t)&&!(`renderChunk`in t)&&!(`generateBundle`in t)}async function resolveUserPlugins(t,n,S={}){let C=S.loadModule??defaultLoadModule,N=createRequire(xn(n,`package.json`)),F=[];for(let S of t){if(!isPluginByName(S)){F.push(S);continue}let t;try{t=N.resolve(S.name)}catch(t){throw Error(`gjsify config: failed to resolve plugin "${S.name}" from ${n}. Add it to your project's dependencies, or pass a Plugin object directly. (${t.message})`)}let I=await C(t,S.name),H=S.export??`default`,W=I[H];if(typeof W!=`function`){let t=Object.keys(I).filter(t=>typeof I[t]==`function`);throw Error(`gjsify config: plugin "${S.name}" has no function export "${H}". Available function exports: ${t.length?t.join(`, `):`(none)`}.`)}let q=await W(S.options);if(q==null)throw Error(`gjsify config: plugin "${S.name}" factory returned ${q}. Check the plugin's signature — it should return a Rolldown/Vite plugin object.`);F.push(q)}return F}var defaultLoadModule,cF=__esmMin(()=>{Al(),jn(),Hn(),defaultLoadModule=async t=>await import(pathToFileURL(t).href)}),lF,uF=__esmMin(()=>{lF={"@gjsify/buffer/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/canvas2d/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/canvas":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/document":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/font-face":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/image":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/location":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/match-media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/observers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/domparser/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/gamepad/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`Navigator`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`dispatchEvent`,`navigator`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/iframe/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`HTMLIFrameElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/buffer":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/encoding":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/microtask":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/navigator":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`Navigator`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`navigator`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/process":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/structured-clone":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/timers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/url":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`URL`,`URLSearchParams`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/formdata":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`FormData`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/performance":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webaudio/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webgl/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WebGL2RenderingContext`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/data-channel":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MessageEvent`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/error":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MediaStream`,`MediaStreamTrack`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media-devices":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CountQueuingStrategy.DOMException.Event.EventTarget.File.MediaStream.MediaStreamTrack.Navigator.ReadableStream.TextDecoderStream.TextEncoderStream.TransformStream.WritableStream.atob.btoa.clearTimeout.navigator.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"@gjsify/webrtc/register/peer-connection":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CountQueuingStrategy.DOMException.Event.EventTarget.File.MediaStream.MediaStreamTrack.MessageEvent.RTCSessionDescription.ReadableStream.TextDecoderStream.TextEncoderStream.TransformStream.WritableStream.atob.btoa.clearTimeout.crypto.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"abort-controller/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"compression-streams/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CompressionStream`,`CountQueuingStrategy`,`DOMException`,`DecompressionStream`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/custom-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/event-target":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/global-event-target":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/ui-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-exception/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"eventsource/register":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.Event.EventSource.EventTarget.File.Headers.MessageEvent.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/fetch":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.File.Headers.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/xhr":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.File.Headers.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.XMLHttpRequest.XMLHttpRequestUpload.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"message-channel/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`MessageChannel`,`MessagePort`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/queuing":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/readable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/text-streams":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/transform":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/writable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webassembly/register/promise":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WebAssembly`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webcrypto/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`crypto`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"websocket/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`]}});function expandWithClosure(t,n){let S=new Set(t),C=[...t];for(;C.length>0;){let t=C.pop(),N=dF[t];if(!N)continue;let F=fF[N];if(F)for(let t of F)n.has(t)||dF[t]&&(S.has(t)||(S.add(t),C.push(t)))}return S}function isSubset(t,n){for(let S of t)if(!n.has(S))return!1;return!0}async function applyExcludeGlobals(t,n,S,C,N,F=N){if(C?.length)for(let n of C)t.delete(n);let I=detectedToRegisterPaths(t);for(let t of S)I.add(t);if(emitGiBackedDiagnostic(I,t,F),!C?.length)return{detected:t,injectPath:n};let H=F?filterResolvableRegisterPaths(I,F):I;return{detected:t,injectPath:H.size>0?await writeRegisterInjectFile(H,N)??void 0:void 0}}function detectedToRegisterPaths(t){let n=new Set;for(let S of t){let t=dF[S];t&&n.add(t)}return n}function giNamespacesForRegister(t){for(let n of Object.keys(pF))if(t===n||t.startsWith(n+`/`))return pF[n];return null}function describeGiBackedInjection(t,n){let S=new Set,C=new Set;for(let n of t){let t=giNamespacesForRegister(n);if(t){S.add(n);for(let n of t)C.add(n)}}if(S.size===0)return null;let N=[...n].filter(t=>{let n=dF[t];return!!n&&S.has(n)}).sort();return`[gjsify] note: --globals auto injected GTK/GNOME-backed register(s) — this bundle now requires ${[...C].sort().map(t=>`gi://${t}`).join(`, `)} at load.`+(N.length?` Triggered by: ${N.join(`, `)}.`:``)+` If it runs headless / SSR / in a GTK-less container it will throw "Typelib … not found"; drop those globals via excludeGlobals or pin an explicit --globals allowlist (e.g. node).`}function emitGiBackedDiagnostic(t,n,S){if(hF)return;let C=new Set;for(let n of t)giNamespacesForRegister(n)&&(S&&!isRegisterPathResolvable(n,S)||C.add(n));let N=describeGiBackedInjection(C,n);N&&(hF=!0,ge.warn(N))}function isFullConfig(t){return typeof t==`object`&&!!t&&!Array.isArray(t)&&`plugins`in t&&`options`in t}function mergeTransformOptions(t,n){if(!t)return n;if(!n)return t;let S={...t,...n};return(t.define||n.define)&&(S.define={...t.define,...n.define}),(t.inject||n.inject)&&(S.inject={...t.inject,...n.inject}),S}function mergeResolveOptions(t,n){return t?n?{...t,...n}:t:n}async function detectAutoGlobals(t,n,S,C,N={},F=defaultBundler){let I=N.extraGlobalsList?resolveGlobalsList(N.extraGlobalsList):new Set,H=new Set(N.excludeGlobals??[]),W=N.cwd,q=W&&N.toolchainDir?[W,N.toolchainDir]:W,Y=new Set,X;I.size>0&&(X=await writeRegisterInjectFile(q?filterResolvableRegisterPaths(I,q):I,W)??void 0);let Z=(t.plugins??[]).filter(t=>{let n=t&&typeof t==`object`&&`name`in t?t.name:void 0;return n!==`gjsify`&&n!==`gjsify-orchestrator`});for(let te=1;te<=mF;te++){let ne=await S({...n,autoGlobalsInject:X,skipProcessStub:!0}),re,ie;isFullConfig(ne)?(ie=ne.options,re=ne.plugins):re=ne;let ae=X?appendInjectAsEntry(t.input,X):t.input,oe=mergeResolveOptions(ie?.resolve,t.resolve),Q=t.external??ie?.external,se=mergeTransformOptions(ie?.transform,t.transform),ce=ie?.treeshake,le=Array.isArray(re)?re:[re],ue=await F({rolldownInput:{input:ae,external:Q,resolve:oe,transform:se,plugins:[...Z,...le],logLevel:`silent`,...ce===void 0?{}:{treeshake:ce}},format:t.format??`esm`});if(ue.length===0)return{detected:new Set,injectPath:X};let de=new Set;for(let t=0;t<ue.length;t++){let n=ue[t]??``;try{for(let t of detectFreeGlobals(n))de.add(t)}catch(S){if(globalThis.process?.env?.GJSIFY_DEBUG_AUTO_GLOBALS){let S=await Promise.resolve().then(()=>(Dg(),yg)),C=(await Promise.resolve().then(()=>(jn(),gn))).join(S.tmpdir(),`gjsify-auto-globals-failed-chunk-${t}.mjs`);try{(await Promise.resolve().then(()=>(Md(),Ad))).writeFileSync(C,n),ge.error(`[gjsify-auto-globals] parse failed on chunk #${t} — wrote ${C} for inspection`)}catch{}}throw S}}if(H.size>0)for(let t of H)de.delete(t);if(isSubset(de,Y)){if(C){let t=[...Y].sort(),n=I.size>0?` (+ ${I.size} extra register module(s))`:``;ge.debug(`[gjsify] --globals auto: converged after ${te-1} iteration(s), ${Y.size} global(s)${t.length?`: `+t.join(`, `):``}${n}`)}return applyExcludeGlobals(Y,X,I,N.excludeGlobals,W,q)}let fe=N.disableClosureExpansion?de:expandWithClosure(de,H);C&&fe.size>de.size&&ge.debug(`[gjsify] --globals auto: closure map expanded ${de.size} → ${fe.size} global(s)`),te>1&&C&&ge.debug("[gjsify] --globals auto: detection grew past the closure-map expansion — the committed register-globals-closure map looks stale. Regenerate via `node packages/infra/cli/scripts/generate-register-closure.mjs`."),Y=new Set([...Y,...fe]);let pe=detectedToRegisterPaths(Y);for(let t of I)pe.add(t);if(q&&(pe=filterResolvableRegisterPaths(pe,q)),pe.size===0)return{detected:Y,injectPath:void 0};if(X=await writeRegisterInjectFile(pe,W)??void 0,C){let t=[...Y].sort();ge.debug(`[gjsify] --globals auto: iteration ${te}, ${Y.size} global(s)${t.length?`: `+t.join(`, `):``}`)}}return C&&ge.debug(`[gjsify] --globals auto: hit max iterations (${mF}), using last detected set`),applyExcludeGlobals(Y,X,I,N.excludeGlobals,W,q)}async function detectNodeGiGlobals(t,n,S,C=defaultBundler){let N=await S(n),F,I;isFullConfig(N)?(I=N.options,F=N.plugins):F=N;let H=(t.plugins??[]).filter(t=>{let n=t&&typeof t==`object`&&`name`in t?t.name:void 0;return n!==`gjsify`&&n!==`gjsify-orchestrator`}),W=Array.isArray(F)?F:[F],q=I?{...I}:{};delete q.output;let Y;try{Y=await C({rolldownInput:{...q,input:t.input,external:t.external??q.external,resolve:mergeResolveOptions(q.resolve,t.resolve),transform:mergeTransformOptions(q.transform,t.transform),plugins:[...H,...W],logLevel:`silent`},format:t.format??`esm`})}catch(t){return ge.warn(`[gjsify] --app node: could not analyse the bundle for GJS ambient globals (${t instanceof Error?t.message:String(t)}); skipping @gjsify/node-gi/globals injection. If this build uses print/imports/ARGV, add \`import '@gjsify/node-gi/globals'\` to the entry or pass --globals.`),!1}for(let t of Y)if(detectGjsAmbientGlobals(t).size>0||detectNodeGiModuleImports(t))return!0;return!1}function appendInjectAsEntry(t,n){return t===void 0?[n]:typeof t==`string`?[t,n]:Array.isArray(t)?[...t,n]:{...t,__gjsify_inject:n}}var defaultBundler,dF,fF,pF,mF,hF,gF=__esmMin(()=>{_e(),Jx(),$x(),Lx(),uF(),defaultBundler=async({rolldownInput:t,format:n})=>{let S=await(await import(`rolldown`)).rolldown(t);try{let t=await S.generate({format:n,minify:!1,sourcemap:!1}),C=[];for(let n of t.output)n.type===`chunk`&&C.push(n.code);return C}finally{await S.close()}},dF=Px,fF=lF,pF=Ix,mF=5,hF=!1}),_F=__esmMin(()=>{$x(),Jx(),gF()});function findPnpRoot(t){let n=t;for(;;){if(existsSync(xn(n,`.pnp.cjs`)))return n;let t=wn(n);if(t===n)return null;n=t}}async function loadPnpApi(){try{let t=await import(`pnpapi`);return t.default??t}catch{return null}}async function pnpPlugin(t={}){let n=t.issuerUrl??import.meta.url;if(!findPnpRoot(process.cwd()))return null;let S=await loadPnpApi();if(S===null)return null;let C=fileURLToPath(n),N=createRequire(C),F=t.relayPackages??[`@gjsify/node-polyfills`,`@gjsify/web-polyfills`],I=[];for(let t of F)try{I.push(N.resolve(`${t}/package.json`))}catch{}return{name:`gjsify-pnp`,resolveId:{order:`pre`,async handler(t,n){if(t.startsWith(`.`)||t.startsWith(`/`))return null;if(t.startsWith(`gi://`))return{id:t,external:!0};if(t.startsWith(`node:`))return await this.resolve(t,n,{skipSelf:!0});if(!n)return null;let N=n.startsWith(`file://`)?fileURLToPath(n):n;try{let n=S.resolveRequest(t,N);return n===null?null:{id:n}}catch(n){if(!isUndeclaredDependency(n))throw n;try{let n=S.resolveRequest(t,C);if(n!==null)return{id:n}}catch(t){if(!isUndeclaredDependency(t))throw t}for(let n of I)try{let C=S.resolveRequest(t,n);if(C!==null)return{id:C}}catch(t){if(!isUndeclaredDependency(t))throw t}return null}}},async load(t){if(!t.includes(`/.yarn/`)&&!t.includes(`.zip/`))return null;try{return{code:await readFile$1(t,`utf8`)}}catch(n){let S=n instanceof Error?n.message:String(n);this.error(`gjsify-pnp: failed to read ${t}: ${S}`)}}}}function isUndeclaredDependency(t){return typeof t==`object`&&!!t&&`pnpCode`in t&&t.pnpCode===`UNDECLARED_DEPENDENCY`}var vF=__esmMin(()=>{Al(),Hn(),jn(),Md(),hd()});function normalizeBundlerOptions(t){let n=t.bundler??{},S=n;if(typeof n.define==`object`&&n.define!==null){bF||(bF=!0,ge.warn(`[gjsify] WARNING: 'bundler.define' is not a valid Rolldown option and would be silently ignored — it has been auto-mapped to 'bundler.transform.define'. Move 'define' under 'bundler.transform.define' in your config to suppress this warning and avoid a ReferenceError at GJS load time.`));let{define:t,...C}=n;S={...C,transform:{...C.transform,define:{...t,...C.transform?.define}}}}if(!t.esbuild)return S;yF||(yF=!0,ge.warn(`[gjsify] DEPRECATION: the 'esbuild' config key is deprecated and will be removed in 0.5.0. Rename it to 'bundler' (typed as RolldownOptions). See the migration notes in the gjsify CHANGELOG.`));let C=legacyEsbuildToRolldown(t.esbuild),N={...C,...S};return(C.output||S.output)&&(N.output={...C.output,...S.output}),(C.transform||S.transform)&&(N.transform={...C.transform,...S.transform},(C.transform?.define||S.transform?.define)&&(N.transform.define={...C.transform?.define,...S.transform?.define})),(C.resolve||S.resolve)&&(N.resolve={...C.resolve,...S.resolve}),N}function legacyEsbuildToRolldown(t){let n={},S={},C={},N={};return t.outfile!==void 0&&(S.file=t.outfile),t.outdir!==void 0&&(S.dir=t.outdir),t.format!==void 0&&(S.format=t.format),t.minify!==void 0&&(S.minify=t.minify),t.sourcemap!==void 0&&(S.sourcemap=t.sourcemap===`inline`?`inline`:!!t.sourcemap),t.banner?.js!==void 0&&(S.banner=t.banner.js),t.target!==void 0&&(C.target=Array.isArray(t.target)?t.target.join(`,`):t.target),t.define!==void 0&&(C.define=t.define),t.mainFields!==void 0&&(N.mainFields=t.mainFields),t.conditions!==void 0&&(N.conditionNames=t.conditions),t.external!==void 0&&(n.external=t.external),t.platform!==void 0&&(n.platform=t.platform),Object.keys(S).length>0&&(n.output=S),Object.keys(C).length>0&&(n.transform=C),Object.keys(N).length>0&&(n.resolve=N),n}function mergeBundlerOptions(t,n){let{input:S,external:C,...N}=n,F={...t,...N};return(t.output||n.output)&&(F.output={...t.output,...n.output}),(t.transform||n.transform)&&(F.transform={...t.transform,...n.transform},(t.transform?.define||n.transform?.define)&&(F.transform.define={...t.transform?.define,...n.transform?.define}),(t.transform?.inject||n.transform?.inject)&&(F.transform.inject={...t.transform?.inject,...n.transform?.inject})),(t.resolve||n.resolve)&&(F.resolve={...t.resolve,...n.resolve}),F}var yF,bF,xF=__esmMin(()=>{_e(),yF=!1,bF=!1});function inputSourceDirs(t,n){let S=[],push=t=>{typeof t==`string`&&t.length>0&&S.push(t)};typeof t==`string`?push(t):Array.isArray(t)?t.forEach(push):t&&typeof t==`object`&&Object.values(t).forEach(push);let C=vn(n),N=new Set;for(let t of S){let n=t.replace(/\\/g,`/`),S=n.search(/[*?{}[\]()!+@]/),F=S===-1?n:n.slice(0,S);F=S===-1?$(F)?wn(F):F:F.replace(/\/[^/]*$/,``);let I=vn(C,F||`.`);I!==C&&N.add(I)}return[...N]}function isInsideOrEqual(t,n){let S=Sn(n,t);return S===``||!S.startsWith(`..`)&&!bn(S)}function isOutdirInsideSource(t,n,S){let C=vn(S,t);return n.some(t=>isInsideOrEqual(C,t))}function libraryOutputLeakError(t){return Error(`gjsify build --library: refusing to write output into "${t}", which holds the input source — a library build there produces src/*.js duplicates, *2.js, a _virtual/ helper dir, and a nested preserve-modules tree, silently corrupting the sources. This output dir was derived from package.json "main"/"module" pointing at a source path. Fix it by pointing "main"/"module" at the built library (e.g. lib/index.js) or by passing an explicit --outdir <dir> outside the source tree.`)}var SF=__esmMin(()=>{jn()});function detectHtmlEntry(t){if(!t)return null;let isHtml=t=>typeof t==`string`&&/\.html?$/i.test(t);if(typeof t==`string`)return isHtml(t)?t:null;if(Array.isArray(t))return t.length===1&&isHtml(t[0])?t[0]:null;if(typeof t==`object`){let n=Object.values(t);return n.length===1&&isHtml(n[0])?n[0]:null}return null}function parseHtmlEntry(t,n){for(let S of n.matchAll(CF)){let n=S[0],C=wF.exec(n);if(!C)continue;let N=C[1];if(!TF.test(N))return{moduleEntry:bn(N)?N:vn(wn(t),N),scriptTag:n,scriptSrc:N}}throw Error(`gjsify build: ${t} has no local <script type="module" src="…"> to bundle. Add one pointing at your app entry (e.g. <script type="module" src="./main.ts">).`)}function emitBrowserHtml(t){let{htmlSource:n,scriptTag:S,scriptSrc:C,jsOutPath:N,outHtmlPath:F}=t,I=Sn(wn(F),N).split(/[\\/]/).join(`/`);I.startsWith(`.`)||(I=`./${I}`);let H=S.replace(wF,t=>t.replace(C,I));return n.replace(S,H)}function htmlOutPathFor(t){return vn(wn(t),`index.html`)}var CF,wF,TF,EF=__esmMin(()=>{jn(),CF=/<script\b[^>]*\btype\s*=\s*["']module["'][^>]*>(?:<\/script>)?/gi,wF=/\bsrc\s*=\s*["']([^"']+)["']/i,TF=/^(?:https?:)?\/\//i});function findDisallowedNodeImports(t,n=DF){let S=new Set;for(let C of t)for(let t of C.imports??[])t.startsWith(`node:`)&&(n.includes(t)||S.add(t));return[...S].sort()}function isBareSpecifier(t){return t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`\\`)?!1:!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function findUnresolvableBareImports(t,n={}){let S=new Set(n.emitted??[]),C=new Set;for(let N of t)for(let t of N.imports??[])t.startsWith(`node:`)||isBareSpecifier(t)&&(S.has(t)||n.isExternal?.(t)||C.add(t));return[...C].sort()}function assertGjsBundleLoadable(t,n,S={}){let C=findDisallowedNodeImports(t);if(C.length>0)throw Error(`gjsify build --app gjs: ${n} still imports ${C.length} bare \`node:\` module(s), which stock GJS cannot resolve — it would fail at load with "ImportError: Unsupported URI scheme for importing: node".
|
|
790
|
+
If you are READING THIS ON A GJS HOST, that global engine is what could not be reached: this workspace symlink shadowed it, because \`require.resolve\` returned the package DIRECTORY instead of failing. That is fixed in \`@gjsify/module\`, so a \`gjsify\` OLDER than the fix still stops here — update it (\`gjs -m install.mjs\`), or seed \`lib/\` from the published package, which ships it.`;let S=[`The JS facade is built, so this is the typelib/prebuild lookup failing.`],C=missingSystemDepsFor(`@gjsify/rolldown-native`),N=C.map(t=>t.name).join(`, `),F=C.length>0?buildInstallCommand(detectPackageManager$1(),C):null,I=C.length===0?void 0:F?`Install it:\n ${F}`:`Install ${N} with your system package manager (this host's manager was not recognised, so no command is suggested rather than a wrong one).`;if(oF!==null&&S.push(`\nNOT MEASURED — the native-library probe could not be loaded, so nothing below is a reading of this host:\n ${oF instanceof Error?oF.message:String(oF)}`),iF&&aF?S.push(`\nMEASURED CAUSE — ${new aF.NativeLibraryLoadError(iF,I).message}`):C.length>0&&(S.push(`\nMEASURED CAUSE — a system library the engine's prebuild loads is MISSING: ${N}.\nThe prebuild is present but its typelib cannot open its backing library, which GJS reports as \`Unsupported type void, deriving from fundamental void\` — a message that names nothing. This is a system package, not an npm one.`),I&&S.push(I)),C.length===0&&!iF){let t=activateNativePrebuilds().find(t=>t.name.startsWith(`@gjsify/rolldown-native`));S.push(t?`\nEvery declared system library resolves and ${t.name}'s prebuild (${t.prebuildsDir}) IS on girepository's search paths, so it is present but did not load.`:`\nEvery declared system library resolves, so most likely no prebuild exists for ${process.platform}/${process.arch} — no @gjsify/rolldown-native prebuild directory was found walking up from ${process.cwd()}.`)}return S.push("\nRunning the build under Node also works — there the npm `rolldown` crate is used instead."),S.join(`
|
|
791
|
+
`)}function resolveImportTargetForGjs(t){if(!isGjs())return t;let n=resolveNpmPackage(t,{bundleUrl:import.meta.url});return n?pathToFileURL(n).href:t}async function bundleToChunks(t){if(await shouldUseNative()){let n=await tryLoadNative();if(!n)throw Error(`@gjsify/rolldown-native not loadable`);let S=t.rolldownInput.plugins??[],C=[];for(let t of S)isPluginObject(t)&&C.push(toNativePlugin(t));let N=liftTransformExtras(stripUnserializable({...t.rolldownInput,input:normalizeInputForNative(t.rolldownInput.input),format:t.format}));delete N.plugins;let F=await n.bundleWithPlugins(N,C);reportNativeWarnings(F,t.rolldownInput);let I=[];for(let t of F.output)t.type===`chunk`&&I.push(t.code);return I}let n=await(await loadNpmRolldown())(t.rolldownInput);try{let S=await n.generate({format:t.format,minify:!1,sourcemap:!1}),C=[];for(let t of S.output)t.type===`chunk`&&C.push(t.code);return C}finally{await n.close()}}async function runWatch(t){if(await shouldUseNative())throw Error("`gjsify build --watch` requires the npm `rolldown` engine. The native engine (`@gjsify/rolldown-native`) does not expose a watcher API. Run the watch loop under Node (`node lib/index.js build … --watch`) or set `GJSIFY_BUNDLER=npm`.");let n=await import(resolveImportTargetForGjs(`rolldown`)),S=t.output??{};return n.watch({...t,output:S})}function warnNoNativeWatchList(){nF||(nF=!0,ge.warn("[gjsify] this `@gjsify/rolldown-native` build reports no watch list: it predates `addWatchFile`, so a file a plugin read itself (a stylesheet’s `@import` chain, an inlined `readFileSync`) cannot be declared as a build input. `gjsify test` will rebuild the affected bundles on every run rather than trust a set it cannot see. Upgrade the engine (it ships in the same release train as the CLI)."))}async function runBundle(t,n={}){if(await shouldUseNative())return await runNativeBundle(t,n);let S=await(await loadNpmRolldown())(t);try{let C=await S.write(t.output??{});return n.onWatchFiles&&n.onWatchFiles({files:await S.watchFiles,reportedByEngine:!0}),C}finally{await S.close()}}function resolveNativeLibraryModule(t={}){let n=`@gjsify/utils/native-library`;return resolveNpmPackage(n,t)??createRequire(t.bundleUrl??import.meta.url).resolve(n)}async function utilsCore(){return aF===null&&(aF=await import(pathToFileURL(resolveNativeLibraryModule({bundleUrl:import.meta.url})).href)),aF}async function shouldUseNative(){let t=(globalThis.process?.env??{}).GJSIFY_BUNDLER;if(t===`npm`)return!1;if(t===`native`){if(!await tryLoadNative())throw Error(`GJSIFY_BUNDLER=native but @gjsify/rolldown-native is not loadable (no prebuild for this architecture, or not running under GJS).`+(isGjs()?`\n${diagnoseNativeEngine()}`:``));return!0}return isGjs()?await tryLoadNative()!==null:!1}function findRolldownNativeDir(t,n){let S=xn(`node_modules`,`@gjsify`,`rolldown-native`,`package.json`),C=[t];n&&n!==t&&C.push(n);for(let t of C){let n=t;for(let t=0;t<12;t++){if(existsSync(xn(n,S)))return xn(n,`node_modules`,`@gjsify`,`rolldown-native`);let t=vn(n,`..`);if(t===n)break;n=t}}return null}async function tryLoadNative(){return rF||(rF=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let t=`@gjsify/rolldown-native`,n=t;if(isGjs()){let S=wn(fileURLToPath(import.meta.url)),C=resolveNpmPackage(t,{bundleUrl:import.meta.url}),N=C?null:(()=>{let n=findRolldownNativeDir(process.cwd(),S);if(!n)return null;try{return createRequire(pathToFileURL(xn(n,`__gjsify_resolve__.js`)).href).resolve(t)}catch{return null}})();n=pathToFileURL(C??N??createRequire(import.meta.url).resolve(t)).href}let S=await import(n);if(!S.hasNativeRolldown())return null;let C=null;try{C=await utilsCore()}catch(t){oF=t}return C!==null&&(iF=C.probeNativeLibrary(`GjsifyRolldown`),iF)?null:S}catch{return null}})(),rF)}async function runNativeBundle(t,n={}){let S=await tryLoadNative();if(!S)throw Error(`@gjsify/rolldown-native not loadable`);let C=t.plugins??[],N=[];for(let t of C)isPluginObject(t)&&N.push(toNativePlugin(t));let{output:F,plugins:I,...H}=t,W=liftTransformExtras(stripUnserializable({...H,...F,input:normalizeInputForNative(t.input)}));globalThis.process?.env?.GJSIFY_DEBUG_NATIVE_OPTS&&ge.error(`[gjsify-bundler-pick] native opts JSON:`,JSON.stringify(W));let q=await S.bundleWithPlugins(W,N);reportNativeWarnings(q,t),n.onWatchFiles&&(q.watchedFiles===void 0?(warnNoNativeWatchList(),n.onWatchFiles({files:[],reportedByEngine:!1})):n.onWatchFiles({files:q.watchedFiles,reportedByEngine:!0}));let Y=t.output??{},X=Y.dir??(Y.file?wn(Y.file):process.cwd());X&&await pd.mkdir(X,{recursive:!0});for(let t of q.output){let n=Y.file&&t.type===`chunk`&&q.output.length===1?Y.file:xn(X,t.fileName);await pd.mkdir(wn(n),{recursive:!0}),t.type===`chunk`?(await pd.writeFile(n,t.code,`utf8`),typeof t.map==`string`&&await pd.writeFile(`${n}.map`,t.map,`utf8`)):t.sourceText!==void 0&&await pd.writeFile(n,t.sourceText,`utf8`)}return synthRolldownOutput(q)}function reportNativeWarnings(t,n){if(n.logLevel===`silent`||!Array.isArray(t.warnings)||t.warnings.length===0)return;let S=new Set;for(let n of t.warnings)S.has(n)||(S.add(n),ge.warn(`[gjsify-bundler] ${n}`))}function stripUnserializable(t){let n={};for(let[S,C]of Object.entries(t)){if(typeof C==`function`){if(!sF.has(S)){sF.add(S);let t=S===`external`?" Function `external` predicates are NOT supported by the native engine — pass exact names as a string array and/or enforce shape rules via a resolveId plugin returning `{ external: true }` (see externalsPlugin in @gjsify/rolldown-plugin-gjsify).":` Function-valued options do not survive the JSON boundary to the Rust core.`;ge.warn(`[gjsify-bundler] dropping non-serializable option "${S}" for the native rolldown engine — behavior may diverge from npm rolldown.${t}`)}continue}if(S===`external`&&Array.isArray(C)){let t=C.find(t=>typeof t!=`string`);if(t!==void 0)throw Error(`gjsify build: \`external\` entries must be exact string names under the native rolldown engine (got ${t instanceof RegExp?t.toString():typeof t}). RegExp/function externals are only supported by npm rolldown — use exact names or a resolveId plugin returning \`{ external: true }\`.`);n[S]=C;continue}if(S===`sourcemap`){let t=translateSourcemapOption(C);t!==void 0&&(n[S]=t);continue}n[S]=C}return n}function translateSourcemapOption(t){if(t===!0||t===`file`||t===`File`)return`File`;if(t===`inline`||t===`Inline`)return`Inline`;if(t===`hidden`||t===`Hidden`)return`Hidden`}function liftTransformExtras(t){let n=t.transform;if(!n)return t;let S={},C={...n};for(let t of[`define`,`inject`])t in C&&(S[t]=C[t],delete C[t]);return S.inject!==void 0&&!Array.isArray(S.inject)&&(S.inject=mapToInjectArray(S.inject)),{...t,transform:Object.keys(C).length===0?void 0:C,...S}}function mapToInjectArray(t){let n=[];for(let[S,C]of Object.entries(t))if(typeof C==`string`)n.push({type:`named`,imported:`default`,from:C,alias:S});else{let[t,N]=C;N===`*`?n.push({type:`namespace`,from:t,alias:S}):n.push({type:`named`,from:t,imported:N,alias:S})}return n}function normalizeInputForNative(t){return t===void 0?[]:typeof t==`string`?[{import:t}]:Array.isArray(t)?t.map(t=>typeof t==`string`?{import:t}:t):Object.entries(t).map(([t,n])=>({name:t,import:n}))}function isPluginObject(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function pickHook(t){if(typeof t==`function`)return{fn:t};if(typeof t==`object`&&t&&`handler`in t){let n=t,S=filterToRegexSource(n.filter?.id),C={fn:n.handler};return S!==void 0&&(C.idFilter=S),C}}function filterToRegexSource(t){if(t!==void 0){if(Array.isArray(t)){let n=t.map(oneToSource).filter(t=>t!==void 0);return n.length===0?void 0:n.length===1?n[0]:`(?:${n.join(`|`)})`}return oneToSource(t)}}function oneToSource(t){if(t instanceof RegExp)return t.source;if(typeof t==`string`)return t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function toNativePlugin(t){let n={name:typeof t.name==`string`?t.name:`unnamed-plugin`},S={},C=pickHook(t.load);C&&(n.load=C.fn,C.idFilter&&(S.load=C.idFilter));let N=pickHook(t.transform);N&&(n.transform=N.fn,N.idFilter&&(S.transform=N.idFilter));let F=pickHook(t.resolveId);F&&(n.resolveId=F.fn,F.idFilter&&(S.resolveId=F.idFilter));let I=pickHook(t.renderChunk);I&&(n.renderChunk=I.fn);let H=pickHook(t.banner);H&&(n.banner=H.fn);let W=pickHook(t.footer);W&&(n.footer=W.fn);let q=pickHook(t.intro);q&&(n.intro=q.fn);let Y=pickHook(t.outro);Y&&(n.outro=Y.fn);let X=pickHook(t.buildStart);X&&(n.buildStart=X.fn);let Z=pickHook(t.buildEnd);Z&&(n.buildEnd=Z.fn);let te=pickHook(t.generateBundle);te&&(n.generateBundle=te.fn);let ne=pickHook(t.writeBundle);ne&&(n.writeBundle=ne.fn);let re=pickHook(t.closeBundle);return re&&(n.closeBundle=re.fn),Object.keys(S).length>0&&(n.idFilter=S),n}function synthRolldownOutput(t){return{output:t.output.map(t=>t.type===`chunk`?{type:`chunk`,fileName:t.fileName,code:t.code,name:t.name,isEntry:t.isEntry,isDynamicEntry:t.isDynamicEntry,map:t.map??null,sourcemapFileName:t.sourcemapFilename??null,imports:t.imports,dynamicImports:t.dynamicImports,facadeModuleId:null,moduleIds:[],modules:{},exports:[],referencedFiles:[],importedBindings:{}}:{type:`asset`,fileName:t.fileName,names:t.names,originalFileNames:t.originalFileNames,source:t.sourceText??``,needsCodeReference:!1})}}var nF,rF,iF,aF,oF,sF,cF=__esmMin(()=>{_e(),Md(),jn(),Al(),Hn(),MP(),JP(),tF(),t_(),nF=!1,rF=null,iF=null,aF=null,oF=null,sF=new Set});function isPluginByName(t){return typeof t==`object`&&!!t&&typeof t.name==`string`&&!(`apply`in t)&&!(`resolveId`in t)&&!(`load`in t)&&!(`transform`in t)&&!(`renderChunk`in t)&&!(`generateBundle`in t)}async function resolveUserPlugins(t,n,S={}){let C=S.loadModule??defaultLoadModule,N=createRequire(xn(n,`package.json`)),F=[];for(let S of t){if(!isPluginByName(S)){F.push(S);continue}let t;try{t=N.resolve(S.name)}catch(t){throw Error(`gjsify config: failed to resolve plugin "${S.name}" from ${n}. Add it to your project's dependencies, or pass a Plugin object directly. (${t.message})`)}let I=await C(t,S.name),H=S.export??`default`,W=I[H];if(typeof W!=`function`){let t=Object.keys(I).filter(t=>typeof I[t]==`function`);throw Error(`gjsify config: plugin "${S.name}" has no function export "${H}". Available function exports: ${t.length?t.join(`, `):`(none)`}.`)}let q=await W(S.options);if(q==null)throw Error(`gjsify config: plugin "${S.name}" factory returned ${q}. Check the plugin's signature — it should return a Rolldown/Vite plugin object.`);F.push(q)}return F}var defaultLoadModule,lF=__esmMin(()=>{Al(),jn(),Hn(),defaultLoadModule=async t=>await import(pathToFileURL(t).href)}),uF,dF=__esmMin(()=>{uF={"@gjsify/buffer/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/canvas2d/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/canvas":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/document":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/font-face":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/image":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/location":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/match-media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/observers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/domparser/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/gamepad/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`Navigator`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`dispatchEvent`,`navigator`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/iframe/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`HTMLIFrameElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/buffer":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/encoding":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/microtask":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/navigator":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`Navigator`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`navigator`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/process":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/structured-clone":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/timers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/url":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`URL`,`URLSearchParams`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/formdata":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`FormData`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/performance":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webaudio/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webgl/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`Path2D`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WebGL2RenderingContext`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/data-channel":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MessageEvent`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/error":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MediaStream`,`MediaStreamTrack`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media-devices":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CountQueuingStrategy.DOMException.Event.EventTarget.File.MediaStream.MediaStreamTrack.Navigator.ReadableStream.TextDecoderStream.TextEncoderStream.TransformStream.WritableStream.atob.btoa.clearTimeout.navigator.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"@gjsify/webrtc/register/peer-connection":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CountQueuingStrategy.DOMException.Event.EventTarget.File.MediaStream.MediaStreamTrack.MessageEvent.RTCSessionDescription.ReadableStream.TextDecoderStream.TextEncoderStream.TransformStream.WritableStream.atob.btoa.clearTimeout.crypto.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"abort-controller/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"compression-streams/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CompressionStream`,`CountQueuingStrategy`,`DOMException`,`DecompressionStream`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/custom-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/event-target":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/global-event-target":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/ui-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-exception/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"eventsource/register":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.Event.EventSource.EventTarget.File.Headers.MessageEvent.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/fetch":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.File.Headers.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/xhr":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.File.Headers.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.XMLHttpRequest.XMLHttpRequestUpload.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"message-channel/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`MessageChannel`,`MessagePort`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/queuing":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/readable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/text-streams":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/transform":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/writable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webassembly/register/promise":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WebAssembly`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webcrypto/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`crypto`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"websocket/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`]}});function expandWithClosure(t,n){let S=new Set(t),C=[...t];for(;C.length>0;){let t=C.pop(),N=fF[t];if(!N)continue;let F=pF[N];if(F)for(let t of F)n.has(t)||fF[t]&&(S.has(t)||(S.add(t),C.push(t)))}return S}function isSubset(t,n){for(let S of t)if(!n.has(S))return!1;return!0}async function applyExcludeGlobals(t,n,S,C,N,F=N){if(C?.length)for(let n of C)t.delete(n);let I=detectedToRegisterPaths(t);for(let t of S)I.add(t);if(emitGiBackedDiagnostic(I,t,F),!C?.length)return{detected:t,injectPath:n};let H=F?filterResolvableRegisterPaths(I,F):I;return{detected:t,injectPath:H.size>0?await writeRegisterInjectFile(H,N)??void 0:void 0}}function detectedToRegisterPaths(t){let n=new Set;for(let S of t){let t=fF[S];t&&n.add(t)}return n}function giNamespacesForRegister(t){for(let n of Object.keys(mF))if(t===n||t.startsWith(n+`/`))return mF[n];return null}function describeGiBackedInjection(t,n){let S=new Set,C=new Set;for(let n of t){let t=giNamespacesForRegister(n);if(t){S.add(n);for(let n of t)C.add(n)}}if(S.size===0)return null;let N=[...n].filter(t=>{let n=fF[t];return!!n&&S.has(n)}).sort();return`[gjsify] note: --globals auto injected GTK/GNOME-backed register(s) — this bundle now requires ${[...C].sort().map(t=>`gi://${t}`).join(`, `)} at load.`+(N.length?` Triggered by: ${N.join(`, `)}.`:``)+` If it runs headless / SSR / in a GTK-less container it will throw "Typelib … not found"; drop those globals via excludeGlobals or pin an explicit --globals allowlist (e.g. node).`}function emitGiBackedDiagnostic(t,n,S){if(gF)return;let C=new Set;for(let n of t)giNamespacesForRegister(n)&&(S&&!isRegisterPathResolvable(n,S)||C.add(n));let N=describeGiBackedInjection(C,n);N&&(gF=!0,ge.warn(N))}function isFullConfig(t){return typeof t==`object`&&!!t&&!Array.isArray(t)&&`plugins`in t&&`options`in t}function mergeTransformOptions(t,n){if(!t)return n;if(!n)return t;let S={...t,...n};return(t.define||n.define)&&(S.define={...t.define,...n.define}),(t.inject||n.inject)&&(S.inject={...t.inject,...n.inject}),S}function mergeResolveOptions(t,n){return t?n?{...t,...n}:t:n}async function detectAutoGlobals(t,n,S,C,N={},F=defaultBundler){let I=N.extraGlobalsList?resolveGlobalsList(N.extraGlobalsList):new Set,H=new Set(N.excludeGlobals??[]),W=N.cwd,q=W&&N.toolchainDir?[W,N.toolchainDir]:W,Y=new Set,X;I.size>0&&(X=await writeRegisterInjectFile(q?filterResolvableRegisterPaths(I,q):I,W)??void 0);let Z=(t.plugins??[]).filter(t=>{let n=t&&typeof t==`object`&&`name`in t?t.name:void 0;return n!==`gjsify`&&n!==`gjsify-orchestrator`});for(let te=1;te<=hF;te++){let ne=await S({...n,autoGlobalsInject:X,skipProcessStub:!0}),re,ie;isFullConfig(ne)?(ie=ne.options,re=ne.plugins):re=ne;let ae=X?appendInjectAsEntry(t.input,X):t.input,oe=mergeResolveOptions(ie?.resolve,t.resolve),Q=t.external??ie?.external,se=mergeTransformOptions(ie?.transform,t.transform),ce=ie?.treeshake,le=Array.isArray(re)?re:[re],ue=await F({rolldownInput:{input:ae,external:Q,resolve:oe,transform:se,plugins:[...Z,...le],logLevel:`silent`,...ce===void 0?{}:{treeshake:ce}},format:t.format??`esm`});if(ue.length===0)return{detected:new Set,injectPath:X};let de=new Set;for(let t=0;t<ue.length;t++){let n=ue[t]??``;try{for(let t of detectFreeGlobals(n))de.add(t)}catch(S){if(globalThis.process?.env?.GJSIFY_DEBUG_AUTO_GLOBALS){let S=await Promise.resolve().then(()=>(Dg(),yg)),C=(await Promise.resolve().then(()=>(jn(),gn))).join(S.tmpdir(),`gjsify-auto-globals-failed-chunk-${t}.mjs`);try{(await Promise.resolve().then(()=>(Md(),Ad))).writeFileSync(C,n),ge.error(`[gjsify-auto-globals] parse failed on chunk #${t} — wrote ${C} for inspection`)}catch{}}throw S}}if(H.size>0)for(let t of H)de.delete(t);if(isSubset(de,Y)){if(C){let t=[...Y].sort(),n=I.size>0?` (+ ${I.size} extra register module(s))`:``;ge.debug(`[gjsify] --globals auto: converged after ${te-1} iteration(s), ${Y.size} global(s)${t.length?`: `+t.join(`, `):``}${n}`)}return applyExcludeGlobals(Y,X,I,N.excludeGlobals,W,q)}let fe=N.disableClosureExpansion?de:expandWithClosure(de,H);C&&fe.size>de.size&&ge.debug(`[gjsify] --globals auto: closure map expanded ${de.size} → ${fe.size} global(s)`),te>1&&C&&ge.debug("[gjsify] --globals auto: detection grew past the closure-map expansion — the committed register-globals-closure map looks stale. Regenerate via `node packages/infra/cli/scripts/generate-register-closure.mjs`."),Y=new Set([...Y,...fe]);let pe=detectedToRegisterPaths(Y);for(let t of I)pe.add(t);if(q&&(pe=filterResolvableRegisterPaths(pe,q)),pe.size===0)return{detected:Y,injectPath:void 0};if(X=await writeRegisterInjectFile(pe,W)??void 0,C){let t=[...Y].sort();ge.debug(`[gjsify] --globals auto: iteration ${te}, ${Y.size} global(s)${t.length?`: `+t.join(`, `):``}`)}}return C&&ge.debug(`[gjsify] --globals auto: hit max iterations (${hF}), using last detected set`),applyExcludeGlobals(Y,X,I,N.excludeGlobals,W,q)}async function detectNodeGiGlobals(t,n,S,C=defaultBundler){let N=await S(n),F,I;isFullConfig(N)?(I=N.options,F=N.plugins):F=N;let H=(t.plugins??[]).filter(t=>{let n=t&&typeof t==`object`&&`name`in t?t.name:void 0;return n!==`gjsify`&&n!==`gjsify-orchestrator`}),W=Array.isArray(F)?F:[F],q=I?{...I}:{};delete q.output;let Y;try{Y=await C({rolldownInput:{...q,input:t.input,external:t.external??q.external,resolve:mergeResolveOptions(q.resolve,t.resolve),transform:mergeTransformOptions(q.transform,t.transform),plugins:[...H,...W],logLevel:`silent`},format:t.format??`esm`})}catch(t){return ge.warn(`[gjsify] --app node: could not analyse the bundle for GJS ambient globals (${t instanceof Error?t.message:String(t)}); skipping @gjsify/node-gi/globals injection. If this build uses print/imports/ARGV, add \`import '@gjsify/node-gi/globals'\` to the entry or pass --globals.`),!1}for(let t of Y)if(detectGjsAmbientGlobals(t).size>0||detectNodeGiModuleImports(t))return!0;return!1}function appendInjectAsEntry(t,n){return t===void 0?[n]:typeof t==`string`?[t,n]:Array.isArray(t)?[...t,n]:{...t,__gjsify_inject:n}}var defaultBundler,fF,pF,mF,hF,gF,_F=__esmMin(()=>{_e(),Jx(),$x(),Lx(),dF(),defaultBundler=async({rolldownInput:t,format:n})=>{let S=await(await import(`rolldown`)).rolldown(t);try{let t=await S.generate({format:n,minify:!1,sourcemap:!1}),C=[];for(let n of t.output)n.type===`chunk`&&C.push(n.code);return C}finally{await S.close()}},fF=Px,pF=uF,mF=Ix,hF=5,gF=!1}),vF=__esmMin(()=>{$x(),Jx(),_F()});function findPnpRoot(t){let n=t;for(;;){if(existsSync(xn(n,`.pnp.cjs`)))return n;let t=wn(n);if(t===n)return null;n=t}}async function loadPnpApi(){try{let t=await import(`pnpapi`);return t.default??t}catch{return null}}async function pnpPlugin(t={}){let n=t.issuerUrl??import.meta.url;if(!findPnpRoot(process.cwd()))return null;let S=await loadPnpApi();if(S===null)return null;let C=fileURLToPath(n),N=createRequire(C),F=t.relayPackages??[`@gjsify/node-polyfills`,`@gjsify/web-polyfills`],I=[];for(let t of F)try{I.push(N.resolve(`${t}/package.json`))}catch{}return{name:`gjsify-pnp`,resolveId:{order:`pre`,async handler(t,n){if(t.startsWith(`.`)||t.startsWith(`/`))return null;if(t.startsWith(`gi://`))return{id:t,external:!0};if(t.startsWith(`node:`))return await this.resolve(t,n,{skipSelf:!0});if(!n)return null;let N=n.startsWith(`file://`)?fileURLToPath(n):n;try{let n=S.resolveRequest(t,N);return n===null?null:{id:n}}catch(n){if(!isUndeclaredDependency(n))throw n;try{let n=S.resolveRequest(t,C);if(n!==null)return{id:n}}catch(t){if(!isUndeclaredDependency(t))throw t}for(let n of I)try{let C=S.resolveRequest(t,n);if(C!==null)return{id:C}}catch(t){if(!isUndeclaredDependency(t))throw t}return null}}},async load(t){if(!t.includes(`/.yarn/`)&&!t.includes(`.zip/`))return null;try{return{code:await readFile$1(t,`utf8`)}}catch(n){let S=n instanceof Error?n.message:String(n);this.error(`gjsify-pnp: failed to read ${t}: ${S}`)}}}}function isUndeclaredDependency(t){return typeof t==`object`&&!!t&&`pnpCode`in t&&t.pnpCode===`UNDECLARED_DEPENDENCY`}var yF=__esmMin(()=>{Al(),Hn(),jn(),Md(),hd()});function normalizeBundlerOptions(t){let n=t.bundler??{},S=n;if(typeof n.define==`object`&&n.define!==null){xF||(xF=!0,ge.warn(`[gjsify] WARNING: 'bundler.define' is not a valid Rolldown option and would be silently ignored — it has been auto-mapped to 'bundler.transform.define'. Move 'define' under 'bundler.transform.define' in your config to suppress this warning and avoid a ReferenceError at GJS load time.`));let{define:t,...C}=n;S={...C,transform:{...C.transform,define:{...t,...C.transform?.define}}}}if(!t.esbuild)return S;bF||(bF=!0,ge.warn(`[gjsify] DEPRECATION: the 'esbuild' config key is deprecated and will be removed in 0.5.0. Rename it to 'bundler' (typed as RolldownOptions). See the migration notes in the gjsify CHANGELOG.`));let C=legacyEsbuildToRolldown(t.esbuild),N={...C,...S};return(C.output||S.output)&&(N.output={...C.output,...S.output}),(C.transform||S.transform)&&(N.transform={...C.transform,...S.transform},(C.transform?.define||S.transform?.define)&&(N.transform.define={...C.transform?.define,...S.transform?.define})),(C.resolve||S.resolve)&&(N.resolve={...C.resolve,...S.resolve}),N}function legacyEsbuildToRolldown(t){let n={},S={},C={},N={};return t.outfile!==void 0&&(S.file=t.outfile),t.outdir!==void 0&&(S.dir=t.outdir),t.format!==void 0&&(S.format=t.format),t.minify!==void 0&&(S.minify=t.minify),t.sourcemap!==void 0&&(S.sourcemap=t.sourcemap===`inline`?`inline`:!!t.sourcemap),t.banner?.js!==void 0&&(S.banner=t.banner.js),t.target!==void 0&&(C.target=Array.isArray(t.target)?t.target.join(`,`):t.target),t.define!==void 0&&(C.define=t.define),t.mainFields!==void 0&&(N.mainFields=t.mainFields),t.conditions!==void 0&&(N.conditionNames=t.conditions),t.external!==void 0&&(n.external=t.external),t.platform!==void 0&&(n.platform=t.platform),Object.keys(S).length>0&&(n.output=S),Object.keys(C).length>0&&(n.transform=C),Object.keys(N).length>0&&(n.resolve=N),n}function mergeBundlerOptions(t,n){let{input:S,external:C,...N}=n,F={...t,...N};return(t.output||n.output)&&(F.output={...t.output,...n.output}),(t.transform||n.transform)&&(F.transform={...t.transform,...n.transform},(t.transform?.define||n.transform?.define)&&(F.transform.define={...t.transform?.define,...n.transform?.define}),(t.transform?.inject||n.transform?.inject)&&(F.transform.inject={...t.transform?.inject,...n.transform?.inject})),(t.resolve||n.resolve)&&(F.resolve={...t.resolve,...n.resolve}),F}var bF,xF,SF=__esmMin(()=>{_e(),bF=!1,xF=!1});function inputSourceDirs(t,n){let S=[],push=t=>{typeof t==`string`&&t.length>0&&S.push(t)};typeof t==`string`?push(t):Array.isArray(t)?t.forEach(push):t&&typeof t==`object`&&Object.values(t).forEach(push);let C=vn(n),N=new Set;for(let t of S){let n=t.replace(/\\/g,`/`),S=n.search(/[*?{}[\]()!+@]/),F=S===-1?n:n.slice(0,S);F=S===-1?$(F)?wn(F):F:F.replace(/\/[^/]*$/,``);let I=vn(C,F||`.`);I!==C&&N.add(I)}return[...N]}function isInsideOrEqual(t,n){let S=Sn(n,t);return S===``||!S.startsWith(`..`)&&!bn(S)}function isOutdirInsideSource(t,n,S){let C=vn(S,t);return n.some(t=>isInsideOrEqual(C,t))}function libraryOutputLeakError(t){return Error(`gjsify build --library: refusing to write output into "${t}", which holds the input source — a library build there produces src/*.js duplicates, *2.js, a _virtual/ helper dir, and a nested preserve-modules tree, silently corrupting the sources. This output dir was derived from package.json "main"/"module" pointing at a source path. Fix it by pointing "main"/"module" at the built library (e.g. lib/index.js) or by passing an explicit --outdir <dir> outside the source tree.`)}var CF=__esmMin(()=>{jn()});function detectHtmlEntry(t){if(!t)return null;let isHtml=t=>typeof t==`string`&&/\.html?$/i.test(t);if(typeof t==`string`)return isHtml(t)?t:null;if(Array.isArray(t))return t.length===1&&isHtml(t[0])?t[0]:null;if(typeof t==`object`){let n=Object.values(t);return n.length===1&&isHtml(n[0])?n[0]:null}return null}function parseHtmlEntry(t,n){for(let S of n.matchAll(wF)){let n=S[0],C=TF.exec(n);if(!C)continue;let N=C[1];if(!EF.test(N))return{moduleEntry:bn(N)?N:vn(wn(t),N),scriptTag:n,scriptSrc:N}}throw Error(`gjsify build: ${t} has no local <script type="module" src="…"> to bundle. Add one pointing at your app entry (e.g. <script type="module" src="./main.ts">).`)}function emitBrowserHtml(t){let{htmlSource:n,scriptTag:S,scriptSrc:C,jsOutPath:N,outHtmlPath:F}=t,I=Sn(wn(F),N).split(/[\\/]/).join(`/`);I.startsWith(`.`)||(I=`./${I}`);let H=S.replace(TF,t=>t.replace(C,I));return n.replace(S,H)}function htmlOutPathFor(t){return vn(wn(t),`index.html`)}var wF,TF,EF,DF=__esmMin(()=>{jn(),wF=/<script\b[^>]*\btype\s*=\s*["']module["'][^>]*>(?:<\/script>)?/gi,TF=/\bsrc\s*=\s*["']([^"']+)["']/i,EF=/^(?:https?:)?\/\//i});function findDisallowedNodeImports(t,n=OF){let S=new Set;for(let C of t)for(let t of C.imports??[])t.startsWith(`node:`)&&(n.includes(t)||S.add(t));return[...S].sort()}function isBareSpecifier(t){return t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`\\`)?!1:!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function findUnresolvableBareImports(t,n={}){let S=new Set(n.emitted??[]),C=new Set;for(let N of t)for(let t of N.imports??[])t.startsWith(`node:`)||isBareSpecifier(t)&&(S.has(t)||n.isExternal?.(t)||C.add(t));return[...C].sort()}function assertGjsBundleLoadable(t,n,S={}){let C=findDisallowedNodeImports(t);if(C.length>0)throw Error(`gjsify build --app gjs: ${n} still imports ${C.length} bare \`node:\` module(s), which stock GJS cannot resolve — it would fail at load with "ImportError: Unsupported URI scheme for importing: node".
|
|
792
792
|
`+C.map(t=>` - ${t}`).join(`
|
|
793
793
|
`)+"\n\nThese should have been aliased to their `@gjsify/*` polyfills. The usual cause is that the alias TARGET could not be resolved, so the bundler externalised the import instead (look for UNRESOLVED_IMPORT warnings above): e.g. a workspace checkout whose `@gjsify/*` packages have no built `lib/`. Build the workspace first (`gjsify run build:infra`), or fix the resolution, then rebuild.");let N=findUnresolvableBareImports(t,S);if(N.length!==0)throw Error(`gjsify build --app gjs: ${n} statically imports ${N.length} bare package specifier(s) nothing in this build resolves or declares external. GJS has no node_modules walker and does not follow \`package.json#exports\`, so it aborts the whole module graph at load with "ImportError: Module not found: <specifier>".
|
|
794
794
|
`+N.map(t=>` - ${t}`).join(`
|
|
795
|
-
`)+'\n\nRolldown reports these as UNRESOLVED_IMPORT WARNINGS and re-emits the original specifier, which is why the build reached this point at all. Likely causes:\n - the package is not installed — add it as a dependency and `gjsify install`.\n - a JSX entry with no JSX configuration: oxc then defaults to the automatic runtime with `importSource: "react"`, so the bundle imports `react/jsx-runtime`. Point `gjsify.bundler.transform.jsx.importSource` (or tsconfig `"jsxImportSource"`) at a runtime this project HAS, or use `"jsx": "preserve"` plus the framework compiler that consumes it.\n - the specifier is meant to be provided by the host at runtime — then say so, with `gjsify.bundler.external`.')}function assertGjsBundleParses(t,n){for(let S of t){let t=S.code;if(typeof t!=`string`||t.length===0)continue;let C=locateSurvivingJsx(t);if(C!==null)throw Error(formatSurvivingJsx(C,S.fileName?`${n} (${S.fileName})`:n))}}var
|
|
795
|
+
`)+'\n\nRolldown reports these as UNRESOLVED_IMPORT WARNINGS and re-emits the original specifier, which is why the build reached this point at all. Likely causes:\n - the package is not installed — add it as a dependency and `gjsify install`.\n - a JSX entry with no JSX configuration: oxc then defaults to the automatic runtime with `importSource: "react"`, so the bundle imports `react/jsx-runtime`. Point `gjsify.bundler.transform.jsx.importSource` (or tsconfig `"jsxImportSource"`) at a runtime this project HAS, or use `"jsx": "preserve"` plus the framework compiler that consumes it.\n - the specifier is meant to be provided by the host at runtime — then say so, with `gjsify.bundler.external`.')}function assertGjsBundleParses(t,n){for(let S of t){let t=S.code;if(typeof t!=`string`||t.length===0)continue;let C=locateSurvivingJsx(t);if(C!==null)throw Error(formatSurvivingJsx(C,S.fileName?`${n} (${S.fileName})`:n))}}var OF,kF=__esmMin(()=>{Vj(),OF=[]});function describeJsxConfig(t){let{transformJsx:n,tsconfigJsx:S,tsconfigJsxImportSource:C}=t;return{configured:n!==void 0||S!==void 0||C!==void 0,preserves:n===void 0?S===`preserve`:n===`preserve`}}function collectEntryPaths(t){return typeof t==`string`?[t]:Array.isArray(t)?t.filter(t=>typeof t==`string`):typeof t==`object`&&t?Object.values(t).filter(t=>typeof t==`string`):[]}function findJsxEntryPoint(t){return t.find(t=>AF.test(t))}function jsxConfigMissingError(t){return Error(`gjsify build --app gjs: ${t} contains JSX, but nothing configures a JSX transform — not \`gjsify.bundler.transform.jsx\`, and not tsconfig \`compilerOptions.jsx\`.
|
|
796
796
|
|
|
797
797
|
Left unset, the bundler's transformer defaults to the automatic runtime with \`importSource: "react"\`, so the bundle would import \`react/jsx-runtime\`. GJS cannot resolve a bare specifier at all (no node_modules walker, no \`exports\` map), so the build would exit 0 with an UNRESOLVED_IMPORT warning and the artifact would abort at load with "ImportError: Module not found: react/jsx-runtime" — and where react IS installed it would render React elements, which a GTK host does nothing with.
|
|
798
798
|
|
|
@@ -807,23 +807,23 @@ Configure one of:
|
|
|
807
807
|
or the same in tsconfig: \`"jsx": "react-jsx"\` + \`"jsxImportSource": "<pkg>"\`. NOT
|
|
808
808
|
\`@gjsify/gtk-host\` — its \`/jsx-runtime\` is a TYPE surface and throws when called.
|
|
809
809
|
- \`"jsx": false\`, if this entry should contain no JSX at all: the transformer then
|
|
810
|
-
reports the JSX itself instead of compiling it for a runtime that is not there.`)}var
|
|
810
|
+
reports the JSX itself instead of compiling it for a runtime that is not there.`)}var AF,jF=__esmMin(()=>{AF=/\.(?:jsx|tsx|mjsx|cjsx|mtsx|ctsx)$/i});function giSystemProbes(){let t=new Map;for(let[n,S]of Object.entries(IP)){let C=MF[n];if(!C)throw Error(`[gjsify] PROBED_GI_LIBDIRS names '${n}' but HOST_MARKERS does not: a bundle cannot ask process.platform, so an ungated candidate would be prepended on every host that happens to have the directory.`);for(let n of S)t.set(`${n}\u0000${C}`,[n,`${n}/${LP}`,C])}return[...t.entries()].sort(([t],[n])=>t<n?-1:+(t>n)).map(([,t])=>t)}var MF,NF=__esmMin(()=>{zP(),MF={darwin:`/System/Library/CoreServices/SystemVersion.plist`}});function escapeRawNulForGjs(t){let n=t.split(`\0`);return{code:n.join(`\\x00`),replaced:n.length-1}}var PF=__esmMin(()=>{});function findUnshimmedGjsGlobals(t){return[...detectGjsAmbientGlobals(t)].sort()}function assertNodeBundleGlobalsShimmed(t,n){let S=findUnshimmedGjsGlobals(t);if(S.length!==0)throw Error(`gjsify build --app node: ${n} references ${S.length} GJS ambient global(s) that nothing installs on node/bun/deno, so the bundle throws \`ReferenceError: <name> is not defined\` the first time that code runs:
|
|
811
811
|
`+S.map(t=>` - ${t}`).join(`
|
|
812
|
-
`)+"\n\nThe `@gjsify/node-gi/globals` shim seeds them, but it is injected only when the pre-build detection pass finds them — and that pass did not. The two passes therefore disagreed about the module graph. Either the detection ran against a different graph than the one emitted (check that anything feeding `isGjsSourceBuild()` — the `--globals` register stub, `nodeGiGlobalsInject` — is settled BEFORE `detectNodeGiGlobals`), or the offending package should stop reaching for the legacy `imports` object: `gi://<Ns>` and the bare `system`/`gettext`/`cairo` built-ins resolve on both runtimes, `imports` does not.")}var
|
|
813
|
-
\r*?{}[]~#!`,LF
|
|
812
|
+
`)+"\n\nThe `@gjsify/node-gi/globals` shim seeds them, but it is injected only when the pre-build detection pass finds them — and that pass did not. The two passes therefore disagreed about the module graph. Either the detection ran against a different graph than the one emitted (check that anything feeding `isGjsSourceBuild()` — the `--globals` register stub, `nodeGiGlobalsInject` — is settled BEFORE `detectNodeGiGlobals`), or the offending package should stop reaching for the legacy `imports` object: `gi://<Ns>` and the bare `system`/`gettext`/`cairo` built-ins resolve on both runtimes, `imports` does not.")}var FF=__esmMin(()=>{vF()});function hasWildcard(t){return t.includes(`*`)||t.includes(`?`)}function segmentToRegExp(t){let n=t.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/\\\\]*`).replace(/\?/g,`[^/\\\\]`);return RegExp(`^${n}$`)}function assertInsideCwd(t,n,S){let C=Sn(S,t);if(C===``)throw Error(`gjsify clear: refusing to delete the working directory itself ("${n}").`);if(C===`..`||C.startsWith(`..${On}`)||bn(C))throw Error(`gjsify clear: "${n}" resolves to ${t}, outside the working directory ${S}. Only paths inside the package may be cleared.`)}function resolveClearTargets(t,n){let S=[],C=new Set;for(let N of t)for(let t of expandTarget(N,n))assertInsideCwd(t,N,n.cwd),!C.has(t)&&(C.add(t),S.push(t));return S}function expandTarget(t,n){let S=Tn(t),C=wn(t);if(hasWildcard(C))throw Error(`gjsify clear: a wildcard is only supported in the last path segment — got "${t}".`);if(!hasWildcard(S))return[vn(n.cwd,t)];let N=vn(n.cwd,C);assertInsideCwdOrSelf(N,t,n.cwd);let F=segmentToRegExp(S),I;try{I=n.readdir(N)}catch{return[]}return I.filter(t=>F.test(t)).sort().map(t=>xn(N,t))}function assertInsideCwdOrSelf(t,n,S){Sn(S,t)!==``&&assertInsideCwd(t,n,S)}var IF=__esmMin(()=>{jn()});function tokenizeSimpleCommand(t,n={}){let S=n.allowGlobs===!0?RF:LF,C=[],N=``,F=!1,I=null;for(let n=0;n<t.length;n++){let H=t[n];if(I===`'`){H===`'`?I=null:N+=H;continue}if(I===`"`){if(H===`"`)I=null;else if(H===`\\`&&(t[n+1]===`"`||t[n+1]===`\\`))N+=t[++n];else if(H===`$`||H==="`")return null;else N+=H;continue}if(H===`'`||H===`"`){I=H,F=!0;continue}if(H===` `||H===` `){F&&=(C.push(N),N=``,!1);continue}if(S.includes(H))return null;N+=H,F=!0}return I?null:(F&&C.push(N),C)}function gjsifyCommandArgv(t,n={}){let S=tokenizeSimpleCommand(t,n);return!S||S.length<2||S[0]!==`gjsify`?null:S.slice(1)}var LF,RF,zF=__esmMin(()=>{LF=`|&;<>\`$()\\
|
|
813
|
+
\r*?{}[]~#!`,RF=LF.replace(`*`,``).replace(`?`,``)});function packageOutputPaths(t){let n=t?.scripts?.clear;if(n===void 0)return[...BF];let S=gjsifyCommandArgv(n,{allowGlobs:!0});return S===null||S[0]!==`clear`?[]:[...S.slice(1).filter(t=>!t.startsWith(`-`)),...BF]}function readPackageManifest(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf-8`))}catch{return null}}function makeOutputMatcher(t){let n=t.map(t=>t.split(/[\\/]+/).filter(t=>t!==``&&t!==`.`).map(t=>hasWildcard(t)?segmentToRegExp(t):t)).filter(t=>t.length>0);return t=>{let S=t.split(`/`);for(let t of n){if(t.length>S.length)continue;let n=!0;for(let C=0;C<t.length;C++){let N=t[C],F=S[C];if(typeof N==`string`?N!==F:!N.test(F)){n=!1;break}}if(n)return!0}return!1}}function walk(t,n,S,C){let N;try{N=readdirSync(t)}catch{return}N.sort();for(let F of N){if(F===`node_modules`||F.startsWith(`.`))continue;let N=n===``?F:`${n}/${F}`;if(S(N))continue;let I=xn(t,F),H;try{H=lstatSync(I)}catch{continue}H.isSymbolicLink()?C.push({rel:N,abs:I,link:readLinkTarget(I)}):H.isDirectory()?walk(I,N,S,C):H.isFile()&&C.push({rel:N,abs:I})}}function readLinkTarget(t){try{return readlinkSync(t)}catch{return``}}function packageBuildInputs(t,n={}){let S=[...packageOutputPaths(n.manifest===void 0?readPackageManifest(t):n.manifest),...n.extraOutputs??[]],C=[];return walk(t,``,makeOutputMatcher(S),C),C}function newestInputMtimeMs(t){let n=0;for(let S of t)try{let{mtimeMs:t}=statSync(S.abs);t>n&&(n=t)}catch{return 1/0}return n}function newestDepSignalMtimeMs(t){let n=0,S=t;for(;;){for(let t of VF){let C=xn(S,t);if(existsSync(C))try{let{mtimeMs:t}=statSync(C);t>n&&(n=t)}catch{}}let t=wn(S);if(t===S)return n;S=t}}var BF,VF,HF=__esmMin(()=>{Md(),jn(),IF(),zF(),BF=[`lib`,`dist`,`dist-templates`],VF=[`gjsify-lock.json`,`package-lock.json`,`yarn.lock`,`pnpm-lock.yaml`]}),UF=__exportAll$5({BuildAction:()=>GF});function isUnsafeDefaultOutput(t){if(/\.[cm]?tsx?$/i.test(t))return!0;let n=t.replace(/\\/g,`/`);return!!/(?:^|\/)src\//.test(n)}async function buildPnpPlugin(){return pnpPlugin({issuerUrl:import.meta.url})}function shortHash(t){let n=5381;for(let S=0;S<t.length;S++)n=(n<<5)+n+t.charCodeAt(S)>>>0;return n.toString(16).padStart(8,`0`)}function isTruthyEnv(t){return t===`1`||t===`true`||t===`yes`}async function newestLockfileMtime(t){let n=0;for(let S of VF)try{let C=await stat$1(xn(t,S));C.mtimeMs>n&&(n=C.mtimeMs)}catch{}return n}function runningCliFile(){try{return fileURLToPath(import.meta.url)}catch{return null}}async function isBundleFresh(t,n,S,C){try{let N=await stat$1(t),F=await stat$1(n),I=await newestLockfileMtime(S),H=C===void 0?0:(await stat$1(C)).mtimeMs;return N.mtimeMs>=Math.max(F.mtimeMs,I,H)}catch{return!1}}async function runOneLibraryBuild(t){let n=await gjsifyPlugin({input:t.userBundler.input,output:t.output,userAliases:t.userAliases},t.pluginOpts);return await runBundle({...mergeBundlerOptions(n.options,t.userBundler),plugins:[...t.pnpPlugins,...n.prePlugins,...t.userPlugins,...n.plugins]})}var WF,GF,KF=__esmMin(()=>{_e(),cF(),Vj(),t_(),lF(),vF(),yF(),jn(),Hn(),hd(),SF(),CF(),DF(),kF(),jF(),NF(),PF(),FF(),HF(),WF=`#!/usr/bin/env -S gjs -m`,GF=class BuildAction{configData;constructor(t={}){this.configData=t}async buildLibrary(){let{verbose:t,library:n,typescript:S,exclude:C,aliases:N}=this.configData,F=n??{},I=normalizeBundlerOptions(this.configData),H=process.cwd(),W=inputSourceDirs(I.input,H),assertDerivedOutdirSafe=t=>{if(t&&isOutdirInsideSource(t,W,H))throw libraryOutputLeakError(t)},q=F.module?wn(F.module):void 0,Y=F.main?wn(F.main):void 0,X=F.module?$(F.module):`.js`,Z=F.main?$(F.main):`.js`,te=q&&Y&&q!==Y,ne=await buildPnpPlugin(),re=ne?[ne]:[],ie=textLoaderPlugin({loaders:this.configData.loaders}),ae=ie?[ie]:[];if(I.plugins?.length){let n=await resolveUserPlugins(I.plugins,process.cwd(),isGjs()?{loadModule:(n,S)=>this.loadPluginViaGjsBundle(n,S,t)}:{});ae.push(...n)}let oe=[];if(te){assertDerivedOutdirSafe(q),assertDerivedOutdirSafe(Y);let n=q.includes(`/cjs`)||X===`.cjs`?`cjs`:`esm`;oe.push(await runOneLibraryBuild({pluginOpts:{debug:t,library:n,exclude:C,reflection:S?.reflection,jsExtension:X},userBundler:I,output:{dir:q},userAliases:N,pnpPlugins:re,userPlugins:ae}));let F=Y.includes(`/cjs`)||Z===`.cjs`?`cjs`:`esm`;oe.push(await runOneLibraryBuild({pluginOpts:{debug:t,library:F,exclude:C,reflection:S?.reflection,jsExtension:Z},userBundler:I,output:{dir:Y},userAliases:N,pnpPlugins:re,userPlugins:ae}))}else{let n=I.output?.dir,H=I.output?.file??F.module??F.main,W=H?$(H):`.js`,q=n??(H?wn(H):void 0);n===void 0&&assertDerivedOutdirSafe(q);let Y=I.output?.format??(q?.includes(`/cjs`)||W===`.cjs`?`cjs`:`esm`);oe.push(await runOneLibraryBuild({pluginOpts:{debug:t,library:Y,exclude:C,reflection:S?.reflection,jsExtension:W},userBundler:I,output:{dir:q},userAliases:N,pnpPlugins:re,userPlugins:ae}))}return oe}parseGlobalsValue(t){if(t===void 0)return{autoMode:!0,extras:``};if(t===`none`||t===``)return{autoMode:!1,extras:``};let n=t.split(`,`).map(t=>t.trim()).filter(Boolean);return{autoMode:n.includes(`auto`),extras:n.filter(t=>t!==`auto`).join(`,`)}}async resolveGlobalsInject(t,n,S){if(t!==`gjs`&&t!==`node`||!n)return;let C=resolveGlobalsList(n);if(C.size===0)return;let N=await writeRegisterInjectFile(C,process.cwd(),{reverseBridgeOverride:t===`node`});return S&&N&&ge.debug(`[gjsify] globals: injected ${C.size} register module(s) from --globals ${n}`),N??void 0}async applyShebang(t,n,S){if(!n){S&&ge.warn(`[gjsify] --shebang skipped: no single outfile (use --outfile for executables)`);return}let C=t===`node`?fj:WF,N=resolveShebangLine(this.configData.shebang,C)??C,F=await readFile$1(n,`utf-8`);F.startsWith(`#!`)?S&&ge.debug(`[gjsify] --shebang skipped: ${n} already starts with a shebang`):await writeFile$1(n,N+`
|
|
814
814
|
`+F),await chmod$1(n,493),S&&ge.debug(`[gjsify] --shebang: wrote ${N} + chmod 0o755 to ${n}`)}async escapeRawNul(t,n,S){let C=[];if(t)C.push(t);else if(n)try{for(let t of await readdir$1(n))(t.endsWith(`.mjs`)||t.endsWith(`.js`))&&C.push(vn(n,t))}catch(t){if(t?.code===`ENOENT`)return;throw t}for(let t of C){let n;try{n=await readFile$1(t,`utf-8`)}catch(t){if(t?.code===`ENOENT`)continue;throw t}let{code:C,replaced:N}=escapeRawNulForGjs(n);N!==0&&(await writeFile$1(t,C),S&&ge.debug(`[gjsify] escaped ${N} raw NUL byte(s) in ${t} so GJS can load it`))}}assertGjsOutputLoadable(t,n,S,C){assertGjsBundleLoadable((t.output??[]).filter(t=>t.type===`chunk`),n??S??`the GJS bundle`,{isExternal:createGjsExternalsPredicate(C??[]),emitted:(t.output??[]).map(t=>t.fileName)})}assertNodeOutputGlobals(t,n,S){let C=n??S??`the node bundle`;for(let n of t.output??[]){if(n.type!==`chunk`)continue;let t=n.code;typeof t!=`string`||t.length===0||assertNodeBundleGlobalsShimmed(t,n.fileName?`${C} (${n.fileName})`:C)}}async applyBrowserHtml(t,n,S){let C=vn(n),N=htmlOutPathFor(C),F=emitBrowserHtml({htmlSource:t.htmlSource,scriptTag:t.scriptTag,scriptSrc:t.scriptSrc,jsOutPath:C,outHtmlPath:N});await mkdir$1(wn(N),{recursive:!0}),await writeFile$1(N,F),S&&ge.debug(`[gjsify] --app browser: wrote ${N}`)}async loadPluginViaGjsBundle(t,n,S){let C=await this.bundlePluginForGjs(t,n,S);try{return await import(pathToFileURL(C).href)}catch(t){throw Error(`gjsify config: failed to import the GJS bundle for plugin "${n}" (bundled to ${C}). (${t.message})`)}}async bundlePluginForGjs(t,n,S){try{return await BuildAction.bundleFileForGjsCached(t,{cacheSubdir:`plugins`,label:n,verbose:S,noCacheEnv:`GJSIFY_NO_PLUGIN_CACHE`,resolveFromToolchain:!0})}catch(t){throw Error(`gjsify config: failed to bundle plugin "${n}" for GJS (needed because GJS can't import packages that use exports-map subpaths directly). (${t.message})`)}}static async bundleFileForGjsCached(t,n){let S=process.cwd(),C=xn(S,`node_modules`,`.cache`,`gjsify`,n.cacheSubdir),N=n.label.replace(/[^a-zA-Z0-9._-]/g,`_`),F=n.resolveFromToolchain===!0?runningCliFile():null,I=xn(C,`${N}-${shortHash(n.globals===void 0&&n.excludeGlobals===void 0&&F===null?t:`${t} ${JSON.stringify([n.globals??null,n.excludeGlobals??null,F])}`)}`,`${Tn(t).replace(/\.[cm]?[jt]sx?$/i,``)}.mjs`);return!(n.cache===!1||n.noCacheEnv&&isTruthyEnv(process.env[n.noCacheEnv]))&&await isBundleFresh(I,t,S,F??void 0)?(n.verbose&&ge.debug(`[gjsify] reusing cached GJS bundle ${I}`),I):(n.verbose&&ge.debug(`[gjsify] bundling ${t} for GJS → ${I}`),await BuildAction.bundleFileForGjs(t,I,{...n,toolchainAnchor:F}),I)}static async bundleFileForGjs(t,n,S){await mkdir$1(wn(n),{recursive:!0}),await new BuildAction({verbose:S.verbose,...S.globals===void 0?{}:{globals:S.globals},...S.excludeGlobals===void 0?{}:{excludeGlobals:S.excludeGlobals},bundler:{input:t,output:{file:n},...S.define?{transform:{define:S.define}}:{},...S.logLevel?{logLevel:S.logLevel}:{}}}).buildApp(`gjs`,{preserveDefaultExport:S.preserveDefaultExport??!0,...S.toolchainAnchor?{toolchainAnchor:S.toolchainAnchor}:{}})}static runningCliFile(){return runningCliFile()}async buildApp(t=`gjs`,n={}){let{verbose:S,typescript:C,exclude:N,library:F,aliases:I,excludeGlobals:H}=this.configData,W=normalizeBundlerOptions(this.configData),q=describeJsxConfig({transformJsx:W.transform?.jsx,tsconfigJsx:C?.compilerOptions?.jsx,tsconfigJsxImportSource:C?.compilerOptions?.jsxImportSource});if(t===`gjs`&&!q.configured){let t=findJsxEntryPoint(collectEntryPaths(await globToEntryPoints(W.input,N)));if(t!==void 0)throw jsxConfigMissingError(t)}let Y=null;if(t===`browser`){let t=detectHtmlEntry(W.input);if(t){let n=await readFile$1(t,`utf-8`),{moduleEntry:S,scriptTag:C,scriptSrc:N}=parseHtmlEntry(t,n);W.input=S,Y={htmlSource:n,scriptTag:C,scriptSrc:N}}}let X=W.output?.format??(W.output?.file?.endsWith(`.cjs`)?`cjs`:`esm`),Z=X===`iife`?`esm`:X,te=W.output?.file,ne=W.output?.dir;if(!te&&!ne&&(F?.main||F?.module)){let t=Z===`cjs`?F.main??F.module:F.module??F.main;if(t&&isUnsafeDefaultOutput(t))throw Error(`gjsify build: refusing to default --outfile to ${t} (would overwrite a TypeScript source file). Pass --outfile/--outdir explicitly, or set "gjsify.bundler.output.file" in package.json.`);te=t}if(Y&&!te)throw Error(`gjsify build: an .html entry needs an explicit --outfile (e.g. --outfile dist-app/app.js); the emitted index.html is written beside it.`);let{consoleShim:re,globals:ie,dialect:ae,giRenderer:oe}=this.configData,Q=Array.isArray(W.external)?W.external:void 0,se=typeof W.output?.banner==`string`?W.output.banner:void 0,ce={debug:S,app:t,format:Z,exclude:N,reflection:C?.reflection,consoleShim:re,...ae===void 0?{}:{dialect:ae},...oe===!0?{giRenderer:!0}:{},...I?{aliases:I}:{},...n.preserveDefaultExport?{preserveDefaultExport:!0}:{},...n.toolchainAnchor===void 0?{}:{toolchainAnchor:n.toolchainAnchor}},{autoMode:le,extras:ue}=this.parseGlobalsValue(ie),de=await buildPnpPlugin(),fe=de?[de]:[],pe=textLoaderPlugin({loaders:this.configData.loaders}),me=pe?[pe]:[];if(W.plugins?.length){let t=await resolveUserPlugins(W.plugins,process.cwd(),isGjs()?{loadModule:(t,n)=>this.loadPluginViaGjsBundle(t,n,S)}:{});me.push(...t)}if(t===`gjs`&&le){let gjsifyPluginFactory=async t=>{let n=await gjsifyPlugin({input:W.input,output:{file:te,dir:ne},userExternal:Q,userBanner:se,userAliases:I,shebang:this.configData.shebang},t);return{options:n.options,plugins:n.plugins}},{injectPath:t}=await detectAutoGlobals({input:W.input,plugins:[...fe,...me],external:W.external,transform:W.transform,format:Z},ce,gjsifyPluginFactory,S,{extraGlobalsList:ue,excludeGlobals:H,cwd:process.cwd(),...n.toolchainAnchor===void 0?{}:{toolchainDir:wn(n.toolchainAnchor)}},bundleToChunks);ce.autoGlobalsInject=t}else if(t===`node`&&le){ue&&(ce.autoGlobalsInject=await this.resolveGlobalsInject(t,ue,S));let gjsifyPluginFactory=async t=>{let n=await gjsifyPlugin({input:W.input,output:{file:te,dir:ne},userExternal:Q,userBanner:se,userAliases:I,shebang:this.configData.shebang},t);return{options:n.options,plugins:n.plugins}};await detectNodeGiGlobals({input:W.input,plugins:[...fe,...me],external:W.external,transform:W.transform,format:Z},ce,gjsifyPluginFactory,bundleToChunks)&&(ce.nodeGiGlobalsInject=!0)}else ue&&(ce.autoGlobalsInject=await this.resolveGlobalsInject(t,ue,S));let he=t===`gjs`?giSystemProbes():void 0,ge=await gjsifyPlugin({input:W.input,output:{file:te,dir:ne},userExternal:Q,userBanner:se,userAliases:I,shebang:this.configData.shebang,giSystemProbes:he},ce),_e={...mergeBundlerOptions(ge.options,W),plugins:[...fe,...ge.prePlugins,...me,...ge.plugins]};if(n.watch)return await this.runWatchLoop(_e,t,te,ne,S),[];let ve=await runBundle(_e,{onWatchFiles:n.onWatchFiles});return t===`gjs`&&await this.escapeRawNul(te,ne,S),(t===`gjs`||t===`node`)&&this.configData.shebang&&await this.applyShebang(t,te,S),t===`gjs`&&(this.assertGjsOutputLoadable(ve,te,ne,Q),q.preserves&&assertGjsBundleParses((ve.output??[]).filter(t=>t.type===`chunk`),te??ne??`the GJS bundle`)),t===`node`&&le&&!ce.nodeGiGlobalsInject&&this.assertNodeOutputGlobals(ve,te,ne),t===`browser`&&Y&&te&&await this.applyBrowserHtml(Y,te,S),[ve]}async runWatchLoop(t,n,S,C,N){let F=await runWatch(t),I=new Promise(t=>{F.on(`close`,()=>t())}),H=!1,shutdown=async()=>{if(!H){H=!0,ge.log(`
|
|
815
|
-
[gjsify build --watch] stopping watcher…`);try{await F.close()}catch(t){ge.error(`[gjsify build --watch] watcher close error:`,t)}}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),F.on(`event`,async t=>{switch(t.code){case`START`:N&&ge.log(`[gjsify build --watch] rebuild start`);break;case`BUNDLE_START`:ge.log(`[gjsify build --watch] building…`);break;case`BUNDLE_END`:ge.log(`[gjsify build --watch] built in ${t.duration}ms`);try{n===`gjs`&&await this.escapeRawNul(S,C,N),(n===`gjs`||n===`node`)&&this.configData.shebang&&await this.applyShebang(n,S,N)}finally{await t.result.close()}break;case`END`:ge.log(`[gjsify build --watch] waiting for changes…`);break;case`ERROR`:ge.error(`[gjsify build --watch] build failed:`,t.error?.message??t.error),N&&t.error?.stack&&ge.error(t.error.stack);try{await t.result.close()}catch{}break}}),N&&F.on(`change`,(t,n)=>{ge.log(`[gjsify build --watch] ${n.event}: ${t}`)}),await I}async start(t={app:`gjs`}){if(t.library){if(t.watch)throw Error(`gjsify build: --watch is not supported with --library (library mode would emit watcher rebuilds for every produced format; use --app gjs|node|browser instead).`);return await this.buildLibrary()}return await this.buildApp(t.app,{watch:t.watch,onWatchFiles:t.onWatchFiles})}}});function isModuleResolutionFailure(t){let n=t instanceof Error?t.message:String(t);return/Unsupported URI scheme|\bnode:|Cannot find (module|package)|Module not found|ERR_MODULE_NOT_FOUND|Failed to resolve/i.test(n)}async function loadConfigViaGjsBundle(t,n){let S;try{let{BuildAction:C}=await Promise.resolve().then(()=>(GF(),HF));S=await C.bundleFileForGjsCached(t,{cacheSubdir:`config`,label:Tn(t),verbose:n,noCacheEnv:`GJSIFY_NO_CONFIG_CACHE`,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)},resolveFromToolchain:!0})}catch(n){throw Error(`gjsify: failed to bundle the config ${t} for the GJS CLI. Fixes: run the build under Node (\`npx gjsify …\`), keep the config to plain values / \`process.env\`, or move settings into \`package.json#gjsify\`. (${n.message})`)}try{let t=await import(pathToFileURL(S).href);return t.default??t}catch(n){throw Error(`gjsify: bundled the config ${t} for GJS but could not import the result (${S}). (${n.message})`)}}function defaultSearchPlaces(t){return[`package.json`,`.${t}rc`,`.${t}rc.json`,`.${t}rc.yaml`,`.${t}rc.yml`,`.${t}rc.js`,`.${t}rc.ts`,`.${t}rc.mjs`,`.${t}rc.cjs`,`${t}.config.js`,`${t}.config.ts`,`${t}.config.mjs`,`${t}.config.cjs`]}function merge(t,...n){for(let S of n)if(S)for(let n of Object.keys(S)){let C=t[n],N=S[n];N!==void 0&&(isPlainObject(C)&&isPlainObject(N)?merge(C,N):t[n]=N)}return t}function isPlainObject(t){return typeof t==`object`&&!!t&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype}function readDottedPath(t,n){if(!n.includes(`.`))return t[n];let S=t;for(let t of n.split(`.`)){if(typeof S!=`object`||!S)return;S=S[t]}return S}var KF,gjsConfigLoader,qF,Config,JF=__esmMin(()=>{_e(),Qm(),KF=e_(),jn(),Hn(),t_(),P_(),Bj(),sv(),eN(),vP(),gjsConfigLoader=async t=>{try{let n=await import(pathToFileURL(t).href);return n.default??n}catch(n){if(!isModuleResolutionFailure(n))throw n;return loadConfigViaGjsBundle(t,!!process.env.GJSIFY_DEBUG)}},qF=isGjs()?{".js":gjsConfigLoader,".mjs":gjsConfigLoader,".cjs":gjsConfigLoader}:{},Config=class{loadOptions={};constructor(t={}){Object.keys(t).length&&(this.loadOptions=t)}async load(t){let n=await(0,KF.cosmiconfig)(Zm,{...this.loadOptions,searchPlaces:(this.loadOptions.searchPlaces??defaultSearchPlaces(`gjsify`)).filter(t=>t!==`package.json`),loaders:{...qF,...this.loadOptions.loaders}}).search(t),S={};try{let n=await this.readPackageJSON(t);isPlainObject(n?.gjsify)&&merge(S,n.gjsify)}catch{}return n?.config&&isPlainObject(n.config)&&merge(S,n.config),S.bundler||={},S.library||={},S.typescript||={},{config:S,filepath:n?.filepath??``,isEmpty:!n&&Object.keys(S).length===3}}async readPackageJSON(t){return t=await resolvePackageJSON(t),await readPackageJSON(t)}async readTSConfig(t){return fP(t)?.config||{}}async forNodeScript(t){let{config:n}=await this.load(wn(t));return{globals:n.nodeScript?.globals??n.globals,excludeGlobals:n.nodeScript?.excludeGlobals??n.excludeGlobals}}async forCommand(t=process.cwd()){let{config:n}=await this.load(t);return n}async forBuild(t){let n=await this.load(process.cwd()),S={...n.config},C=n.filepath||process.cwd(),N=await this.readPackageJSON(C),F=await this.readTSConfig(C);if(F.reflection||=t.reflection,S.verbose=t.verbose||t.logLevel===`debug`||t.logLevel===`verbose`,S.exclude=t.exclude||[],t.consoleShim!==void 0&&(S.consoleShim=t.consoleShim),t.giRenderer!==void 0&&(S.giRenderer=t.giRenderer),t.dialect!==void 0){if(!isSourceDialect(t.dialect))throw Error(`gjsify build: "${t.dialect}" is not a source dialect. Known: ${F_.join(`, `)}. This is the dialect the SOURCE is written in — not gjsify.runtimes, which declares the runtime a package RUNS on.`);S.dialect=t.dialect}if(t.app!==void 0&&(S.app=t.app),S.app??=buildAppForRuntime(hostRuntime$1()),S.dialect!==void 0&&!I_.has(S.app))throw Error(`gjsify build: --dialect ${S.dialect} has no effect on --app ${S.app}. It composes on ${[...I_].join(` and `)} only. Drop the dialect, or build one of those targets.`);if(S.giRenderer===!0&&!J_.includes(S.app))throw Error(`gjsify build: --gi-renderer has no effect on --app ${S.app}. It composes on ${J_.join(` and `)} only — the targets with no GObject introspection to answer \`gi://\` with. \`--app gjs\` resolves it natively and \`--app node\` through @gjsify/node-gi, so neither needs a widget renderer standing in for it.`);if(t.globals!==void 0&&(S.globals=t.globals),S.globals??=`auto`,t.shebang!==void 0&&(S.shebang=t.shebang),t.excludeGlobals){let n=(Array.isArray(t.excludeGlobals)?t.excludeGlobals.join(`,`):String(t.excludeGlobals)).split(`,`).map(t=>t.trim()).filter(Boolean);n.length&&(S.excludeGlobals=[...S.excludeGlobals??[],...n])}merge(S.library??={},N,S.library),merge(S.typescript??={},F,S.typescript);let parseKvPairs=(t,n)=>{let S={};for(let C of t){let t=C.indexOf(`=`);if(t===-1)throw Error(`Invalid --${n} value '${C}'. Expected KEY=VALUE.`);let N=C.slice(0,t).trim(),F=C.slice(t+1);if(!N)throw Error(`Invalid --${n} value '${C}'. Empty key.`);S[N]=F}return S},I=parseKvPairs(t.define??[],`define`),H=parseKvPairs(t.alias??[],`alias`);Object.keys(H).length&&(S.aliases={...S.aliases,...H});let W={};if(S.defineFromPackageJson)for(let[t,n]of Object.entries(S.defineFromPackageJson)){if(!n||typeof n.field!=`string`||!n.field)throw Error(`gjsify config: defineFromPackageJson["${t}"] is missing a "field" string`);let S=readDottedPath(N,n.field);W[t]=S===void 0?`undefined`:JSON.stringify(S)}let q={};if(S.defineFromEnv)for(let[t,n]of Object.entries(S.defineFromEnv)){if(!n||typeof n.env!=`string`||!n.env)throw Error(`gjsify config: defineFromEnv["${t}"] is missing an "env" string`);let S=process.env[n.env],C=S===void 0?n.default:S;q[t]=C===void 0?`undefined`:JSON.stringify(C)}let Y=S.bundler??={},X=Y.output??={},Z=Y.transform??={};return t.entryPoints?.length&&(Y.input=t.entryPoints),Y.input||=[`src/index.ts`],t.outfile!==void 0&&(X.file=t.outfile),t.outdir!==void 0&&(X.dir=t.outdir),t.format!==void 0&&(X.format=t.format),t.minify!==void 0&&(X.minify=t.minify),X.minify===void 0&&(X.minify=!0),X.minify===!0&&(X.keepNames=!0),t.logLevel&&(Y.logLevel={silent:`silent`,error:`warn`,warning:`warn`,warn:`warn`,info:`info`,debug:`debug`,verbose:`debug`}[t.logLevel]??`warn`),t.external?.length&&(Y.external=[...Array.isArray(Y.external)?Y.external:[],...t.external]),(Object.keys(I).length||Object.keys(W).length||Object.keys(q).length)&&(Z.define={...Z.define,...W,...q,...I}),S.verbose&&ge.debug(`configData`,S),S}}}),YF,XF=__esmMin(()=>{JF(),GF(),Bj(),YF={command:`build [entryPoints..]`,description:`Build and bundle your Gjs project`,builder:t=>t.option(`entry-points`,{description:`The entry points you want to bundle. Defaults to bundler.input from package.json#gjsify or .gjsifyrc.js, falling back to src/index.ts when neither is set.`,array:!0,type:`string`,defaultDescription:`src/index.ts (fallback)`,coerce:t=>[...new Set(t)]}).option(`exclude`,{description:`An array of glob patterns to exclude entry-points and aliases`,array:!0,type:`string`,default:[]}).option(`verbose`,{description:`Switch on the verbose mode`,type:`boolean`,default:!1}).option(`app`,{description:"Build target for an application. Defaults to the target of the HOST runtime running the CLI: gjs when run under gjs, node when run under node/bun/deno (both consume the --app node bundle). Set `gjsify.app` in package.json#gjsify to override the host default.",type:`string`,choices:[`gjs`,`node`,`browser`,`nativescript`],defaultDescription:`host runtime target (gjs on gjs, else node)`}).option(`format`,{description:`Override the default output format`,type:`string`,choices:[`iife`,`esm`,`cjs`]}).option(`minify`,{description:`Minify the bundled output. Defaults to true; use --no-minify to emit pretty-printed code (e.g. for debugging or readable bundle review).`,type:`boolean`,defaultDescription:`true`}).option(`library`,{description:`Use this if you want to build a library for Gjsify`,type:`boolean`,default:!1}).option(`outfile`,{alias:`o`,description:`Sets the output file name for the build operation. If no outfile is specified, the outfile will be parsed from the package.json. Only used if application mode is active`,type:`string`,normalize:!0}).option(`outdir`,{alias:`d`,description:`Sets the output directory for the build operation. If no outdir is specified, the outdir will be parsed from the package.json. Only used if library mode is active`,type:`string`,normalize:!0}).option(`reflection`,{alias:`r`,description:`Enables TypeScript types on runtime using Deepkit's type compiler`,type:`boolean`,default:!1}).option(`log-level`,{description:`The log level can be changed to prevent esbuild from printing warning and/or error messages to the terminal`,type:`string`,choices:[`silent`,`error`,`warning`,`info`,`debug`,`verbose`],default:`warning`}).option(`dialect`,{description:`The dialect the SOURCE is written in. 'react-native' aliases 'react-native' onto '@gjsify/react-native' and fails the build on an import whose ADR 0032 support-table status is not supported/partial. GJS and Node app builds. This is NOT gjsify.runtimes['react-native'], which declares the runtime a package RUNS on — the two answer opposite questions.`,type:`string`,choices:[...F_]}).option(`gi-renderer`,{description:"Resolve `gi://Ns?version=X` to the target's widget renderer instead of an empty module (ADR 0034 stage 9): --app browser answers gi://Adw and gi://Gtk out of @gjsify/adwaita-web, --app nativescript out of @gjsify/adwaita-nativescript. A namespace with no renderer, and a ?version= the renderer's vocabulary was not generated against, both FAIL the build by name. Off by default — a gi:// import on those targets is usually a GJS-only code path pulled in transitively.",type:`boolean`}).option(`console-shim`,{description:`Inject a console shim into GJS builds for clean output without the GLib prefix and with working ANSI colors. Use --no-console-shim to disable. Only applies to GJS app builds.`,type:`boolean`,default:!0}).option(`globals`,{description:"Comma-separated list of global identifiers, 'auto' (default) to detect automatically from the bundled output, or 'none' to disable. The 'auto' token may be combined with explicit identifiers/groups (e.g. 'auto,dom') for cases where the detector cannot statically see a global because it's accessed via indirection. Each identifier is mapped to the corresponding `@gjsify/<pkg>/register` module and injected into the bundle. See the CLI Reference docs for the full list of known identifiers. Only applies to GJS app builds.",type:`string`}).option(`shebang`,{description:"Prepend a target-appropriate shebang to the output and mark it executable (chmod 755): `#!/usr/bin/env -S gjs -m` for --app gjs, `#!/usr/bin/env node` for --app node. Applies to GJS and Node app builds with a single --outfile. Default: false (use --shebang to enable, or set `shebang: true` in `.gjsifyrc.js`).",type:`boolean`}).option(`external`,{description:"Module names that should NOT be bundled — EXACT package names only, matched literally on both bundler engines (no globs). Repeat the flag or pass a comma-separated list (e.g. --external typedoc,prettier). Appended to the per-app built-in externals; register subpaths (`<pkg>/register[/…]`) are always force-inlined for --app gjs regardless of this flag.",array:!0,type:`string`,default:[],coerce:t=>t.flatMap(t=>t.split(`,`).map(t=>t.trim()).filter(Boolean))}).option(`define`,{description:`Substitute compile-time constants. Each entry is KEY=VALUE where VALUE is a JS expression (string literals must be quoted: --define VERSION='"1.2.3"'). Repeat the flag or pass comma-separated. See https://esbuild.github.io/api/#define`,array:!0,type:`string`,default:[]}).option(`alias`,{description:`Map module specifiers at bundle time. Each entry is FROM=TO (e.g. --alias typedoc=@gjsify/empty). Layered on top of the built-in alias map. Useful for stubbing heavy deps the test scenario never executes.`,array:!0,type:`string`,default:[],coerce:t=>t.flatMap(t=>t.split(`,`).map(t=>t.trim()).filter(Boolean))}).option(`exclude-globals`,{description:`Comma-separated global identifiers to remove from auto-detection results. Use for false positives from dead browser-compat code whose polyfills require unavailable native libraries (e.g. --exclude-globals fetch,XMLHttpRequest).`,type:`string`}).option(`watch`,{alias:`w`,description:"Watch source files and rebuild on change. Logs each rebuild with duration; clean SIGINT shutdown. Only valid with --app gjs|node|browser (rejected with --library). Requires the npm `rolldown` engine — run under Node, not the GJS-bundled CLI.",type:`boolean`,default:!1}),handler:async t=>{let n=await new Config().forBuild(t);await new WF(n).start({library:t.library,app:n.app,watch:t.watch})}}}),ZF,QF=__esmMin(()=>{_e(),hd(),Md(),jn(),FF(),ZF={command:`clear [paths..]`,description:"Delete build output recursively. Portable replacement for `rm -rf` in package `clear` scripts.",builder:t=>t.positional(`paths`,{description:"Files and directories to delete, relative to the current package. A missing path is not an error. `*` and `?` are honoured in the last segment.",type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be deleted and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is deleted.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths??[];if(S.length===0)throw Error(`gjsify clear: no paths given. Usage: gjsify clear <paths…>`);let C=resolveClearTargets(S,{cwd:n,readdir:readdirSync});for(let S of C){let C=Sn(n,S);if(t.dryRun){let t=await stat$1(S).then(()=>!0,()=>!1);ge.log(`gjsify clear: would remove ${C}${t?``:` (absent)`}`);continue}await rm$1(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100}),t.verbose&&ge.log(`gjsify clear: removed ${C}`)}}}});function isDirectoryDestination(t,n){return n.endsWith(`/`)||n.endsWith(`\\`)||t.length>1?!0:t.some(t=>hasWildcard(t))}function assertWritableDestination(t,n,S,C){let N=Sn(S,t);if(N===``){if(C)return;throw Error(`gjsify copy: "${n}" is the working directory itself. Name a file, or add a trailing "/" to copy INTO the directory.`)}if(N===`..`||N.startsWith(`..${On}`)||bn(N))throw Error(`gjsify copy: "${n}" resolves to ${t}, outside the working directory ${S}. Only paths inside the package may be written.`)}function expandSource(t,n){let S=Tn(t),C=wn(t);if(hasWildcard(C))throw Error(`gjsify copy: a wildcard is only supported in the last path segment — got "${t}".`);if(!hasWildcard(S))return[vn(n.cwd,t)];let N=vn(n.cwd,C),F=segmentToRegExp(S),I;try{I=n.readdir(N)}catch{return[]}return I.filter(t=>F.test(t)).sort().map(t=>xn(N,t))}function planCopy(t,n){if(t.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let S=t.slice(0,-1),C=t[t.length-1];if(C===``)throw Error(`gjsify copy: the destination is empty.`);let N=isDirectoryDestination(S,C),F=vn(n.cwd,C);assertWritableDestination(F,C,n.cwd,N);let I=[];for(let t of S){if(t===``)throw Error(`gjsify copy: a source path is empty.`);I.push(...expandSource(t,n))}if(!N&&I.length!==1)throw Error(`gjsify copy: "${C}" names a single destination, but ${I.length} sources resolved.`);let H=[],W=new Set;for(let t of I){let n=N?xn(F,Tn(t)):F;if(t===n)throw Error(`gjsify copy: "${t}" is its own destination.`);if(W.has(n))throw Error(`gjsify copy: two sources would both be written to ${n}.`);W.add(n),H.push({from:t,to:n})}return H}var $F=__esmMin(()=>{jn(),FF()}),eI,tI=__esmMin(()=>{_e(),hd(),Md(),jn(),$F(),eI={command:`copy [paths..]`,description:"Copy files and directories into the build output. Portable replacement for `mkdir -p` + `cp -r` in package scripts.",builder:t=>t.positional(`paths`,{description:'One or more sources followed by the destination. The destination is a DIRECTORY when it ends with "/", when several sources are given, or when a source carries a wildcard; otherwise it is the exact target path. Missing parent directories are created. `*` and `?` are honoured in the last segment of a source.',type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be copied and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is copied.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths??[];if(S.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let C=planCopy(S,{cwd:n,readdir:readdirSync}),show=t=>{let S=Sn(n,t);return S===``?`.`:S};for(let{from:n,to:S}of C){if(t.dryRun){ge.log(`gjsify copy: would copy ${show(n)} -> ${show(S)}`);continue}await mkdir$1(wn(S),{recursive:!0}),await cpPromises(n,S,{recursive:!0,force:!0}),t.verbose&&ge.log(`gjsify copy: ${show(n)} -> ${show(S)}`)}}}});function doubleDashArgs(t){let n=t[`--`];if(n==null)return[];if(!Array.isArray(n))throw Error(`gjsify: internal error — yargs' \`--\` slot holds a ${typeof n} rather than an array, so the arguments after \`--\` cannot be forwarded. The command builder must set \`parserConfiguration({ 'populate--': true })\`.`);return n.map((t,n)=>{if(typeof t==`string`)return t;throw Error(`gjsify: internal error — the argument after \`--\` at position ${n} arrived as a ${typeof t} (${String(t)}) instead of a string, so forwarding it would change what the caller wrote. The command builder must set \`parserConfiguration({ 'parse-positional-numbers': false })\` alongside \`populate--\`.`)})}var nI=__esmMin(()=>{});function splitEnvArgv(t){let n=[],S=0;for(;S<t.length;S++){let C=rI.exec(t[S]);if(!C)break;n.push([C[1],C[2]])}return S>=t.length?null:{assignments:n,command:t[S],args:t.slice(S+1)}}function joinEnvArgv(t,n){return n.length===0?[...t]:splitEnvArgv(t)?[...t,`--`,...n]:[...t,...n]}function applyAssignments(t,n,S=process.platform){let C={...t};for(let[t,N]of n){if(S===`win32`)for(let n of Object.keys(C))n!==t&&n.toLowerCase()===t.toLowerCase()&&delete C[n];C[t]=N}return C}var rI,iI,aI=__esmMin(()=>{_e(),nI(),j_(),rI=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s,iI={command:`env <entries..>`,description:"Run a command with extra environment variables: `gjsify env NAME=VALUE… <command> [args…]`. Portable replacement for the POSIX `NAME=value command` prefix, which cmd.exe cannot run.",builder:t=>t.positional(`entries`,{description:"`NAME=VALUE` assignments, then the command and its arguments.",type:`string`,array:!0}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=splitEnvArgv(joinEnvArgv(t.entries??[],doubleDashArgs(t)));if(!n)return ge.error(`gjsify env: no command given. Usage: gjsify env NAME=VALUE… <command> [args…]`),process.exit(1);let{assignments:S,command:C,args:N}=n,F;try{F=await spawnToCompletion(C,N,{completion:`exit`,env:applyAssignments(process.env,S)})}catch(t){let n=t;return ge.error(n.code===`ENOENT`?`gjsify env: \`${C}\` not found on PATH`:`gjsify env: ${C}: ${n.message}`),process.exit(127)}return F.code===0?process.exit(0):(F.code===null&&ge.error(`gjsify env: ${C} ended by ${describeExit(F)}`),process.exit(F.code??1))}}});function parseShebang(t){let n=oI.exec(t.trim());return n?{variables:n[1]??``,prog:n[2]??``,args:n[3]??``}:null}function replaceDollarWithPercentPair(t){return t.replace(/\$\{?([^$@#?\- \t{}:]+)\}?/g,(t,n)=>`%${n}%`)}function convertToSetCommands(t){let n=``;for(let S of t.split(` `)){let t=S.indexOf(`=`);if(t<=0)continue;let C=S.slice(0,t).trim(),N=S.slice(t+1).trim();C&&N&&(n+=`@SET ${C}=${replaceDollarWithPercentPair(N)}\r\n`)}return n}function buildCmdShim(t,n){let S=t.split(`\\`).join(`/`),C=S.split(`/`).join(`\\`),N=S,F=n?.prog??``,I=n?.args??``,H=n?.variables??``,W=F?F.split(`\\`).join(`/`):``,q=W?`"${W}$exe"`:``,Y=``,X=``,Z=``;F?(Y=`"%dp0%\\${F}.exe"`,X=`"$basedir/${F}"`,Z=`"$basedir/${F}$exe"`,C=`"%dp0%\\${C}"`,S=`"$basedir_win/${S}"`,N=`"$basedir/${N}"`):(F=`"%dp0%\\${C}"`,W=`"$basedir/${S}"`,q=W,I=``,C=``,S=``,N=``);let te;if(Y){let t=I.trim();te=sI+convertToSetCommands(H)+`\r
|
|
815
|
+
[gjsify build --watch] stopping watcher…`);try{await F.close()}catch(t){ge.error(`[gjsify build --watch] watcher close error:`,t)}}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),F.on(`event`,async t=>{switch(t.code){case`START`:N&&ge.log(`[gjsify build --watch] rebuild start`);break;case`BUNDLE_START`:ge.log(`[gjsify build --watch] building…`);break;case`BUNDLE_END`:ge.log(`[gjsify build --watch] built in ${t.duration}ms`);try{n===`gjs`&&await this.escapeRawNul(S,C,N),(n===`gjs`||n===`node`)&&this.configData.shebang&&await this.applyShebang(n,S,N)}finally{await t.result.close()}break;case`END`:ge.log(`[gjsify build --watch] waiting for changes…`);break;case`ERROR`:ge.error(`[gjsify build --watch] build failed:`,t.error?.message??t.error),N&&t.error?.stack&&ge.error(t.error.stack);try{await t.result.close()}catch{}break}}),N&&F.on(`change`,(t,n)=>{ge.log(`[gjsify build --watch] ${n.event}: ${t}`)}),await I}async start(t={app:`gjs`}){if(t.library){if(t.watch)throw Error(`gjsify build: --watch is not supported with --library (library mode would emit watcher rebuilds for every produced format; use --app gjs|node|browser instead).`);return await this.buildLibrary()}return await this.buildApp(t.app,{watch:t.watch,onWatchFiles:t.onWatchFiles})}}});function isModuleResolutionFailure(t){let n=t instanceof Error?t.message:String(t);return/Unsupported URI scheme|\bnode:|Cannot find (module|package)|Module not found|ERR_MODULE_NOT_FOUND|Failed to resolve/i.test(n)}async function loadConfigViaGjsBundle(t,n){let S;try{let{BuildAction:C}=await Promise.resolve().then(()=>(KF(),UF));S=await C.bundleFileForGjsCached(t,{cacheSubdir:`config`,label:Tn(t),verbose:n,noCacheEnv:`GJSIFY_NO_CONFIG_CACHE`,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)},resolveFromToolchain:!0})}catch(n){throw Error(`gjsify: failed to bundle the config ${t} for the GJS CLI. Fixes: run the build under Node (\`npx gjsify …\`), keep the config to plain values / \`process.env\`, or move settings into \`package.json#gjsify\`. (${n.message})`)}try{let t=await import(pathToFileURL(S).href);return t.default??t}catch(n){throw Error(`gjsify: bundled the config ${t} for GJS but could not import the result (${S}). (${n.message})`)}}function defaultSearchPlaces(t){return[`package.json`,`.${t}rc`,`.${t}rc.json`,`.${t}rc.yaml`,`.${t}rc.yml`,`.${t}rc.js`,`.${t}rc.ts`,`.${t}rc.mjs`,`.${t}rc.cjs`,`${t}.config.js`,`${t}.config.ts`,`${t}.config.mjs`,`${t}.config.cjs`]}function merge(t,...n){for(let S of n)if(S)for(let n of Object.keys(S)){let C=t[n],N=S[n];N!==void 0&&(isPlainObject(C)&&isPlainObject(N)?merge(C,N):t[n]=N)}return t}function isPlainObject(t){return typeof t==`object`&&!!t&&!Array.isArray(t)&&Object.getPrototypeOf(t)===Object.prototype}function readDottedPath(t,n){if(!n.includes(`.`))return t[n];let S=t;for(let t of n.split(`.`)){if(typeof S!=`object`||!S)return;S=S[t]}return S}var qF,gjsConfigLoader,JF,Config,YF=__esmMin(()=>{_e(),Qm(),qF=e_(),jn(),Hn(),t_(),P_(),Vj(),sv(),tN(),yP(),gjsConfigLoader=async t=>{try{let n=await import(pathToFileURL(t).href);return n.default??n}catch(n){if(!isModuleResolutionFailure(n))throw n;return loadConfigViaGjsBundle(t,!!process.env.GJSIFY_DEBUG)}},JF=isGjs()?{".js":gjsConfigLoader,".mjs":gjsConfigLoader,".cjs":gjsConfigLoader}:{},Config=class{loadOptions={};constructor(t={}){Object.keys(t).length&&(this.loadOptions=t)}async load(t){let n=await(0,qF.cosmiconfig)(Zm,{...this.loadOptions,searchPlaces:(this.loadOptions.searchPlaces??defaultSearchPlaces(`gjsify`)).filter(t=>t!==`package.json`),loaders:{...JF,...this.loadOptions.loaders}}).search(t),S={};try{let n=await this.readPackageJSON(t);isPlainObject(n?.gjsify)&&merge(S,n.gjsify)}catch{}return n?.config&&isPlainObject(n.config)&&merge(S,n.config),S.bundler||={},S.library||={},S.typescript||={},{config:S,filepath:n?.filepath??``,isEmpty:!n&&Object.keys(S).length===3}}async readPackageJSON(t){return t=await resolvePackageJSON(t),await readPackageJSON(t)}async readTSConfig(t){return pP(t)?.config||{}}async forNodeScript(t){let{config:n}=await this.load(wn(t));return{globals:n.nodeScript?.globals??n.globals,excludeGlobals:n.nodeScript?.excludeGlobals??n.excludeGlobals}}async forCommand(t=process.cwd()){let{config:n}=await this.load(t);return n}async forBuild(t){let n=await this.load(process.cwd()),S={...n.config},C=n.filepath||process.cwd(),N=await this.readPackageJSON(C),F=await this.readTSConfig(C);if(F.reflection||=t.reflection,S.verbose=t.verbose||t.logLevel===`debug`||t.logLevel===`verbose`,S.exclude=t.exclude||[],t.consoleShim!==void 0&&(S.consoleShim=t.consoleShim),t.giRenderer!==void 0&&(S.giRenderer=t.giRenderer),t.dialect!==void 0){if(!isSourceDialect(t.dialect))throw Error(`gjsify build: "${t.dialect}" is not a source dialect. Known: ${F_.join(`, `)}. This is the dialect the SOURCE is written in — not gjsify.runtimes, which declares the runtime a package RUNS on.`);S.dialect=t.dialect}if(t.app!==void 0&&(S.app=t.app),S.app??=buildAppForRuntime(hostRuntime$1()),S.dialect!==void 0&&!I_.has(S.app))throw Error(`gjsify build: --dialect ${S.dialect} has no effect on --app ${S.app}. It composes on ${[...I_].join(` and `)} only. Drop the dialect, or build one of those targets.`);if(S.giRenderer===!0&&!J_.includes(S.app))throw Error(`gjsify build: --gi-renderer has no effect on --app ${S.app}. It composes on ${J_.join(` and `)} only — the targets with no GObject introspection to answer \`gi://\` with. \`--app gjs\` resolves it natively and \`--app node\` through @gjsify/node-gi, so neither needs a widget renderer standing in for it.`);if(t.globals!==void 0&&(S.globals=t.globals),S.globals??=`auto`,t.shebang!==void 0&&(S.shebang=t.shebang),t.excludeGlobals){let n=(Array.isArray(t.excludeGlobals)?t.excludeGlobals.join(`,`):String(t.excludeGlobals)).split(`,`).map(t=>t.trim()).filter(Boolean);n.length&&(S.excludeGlobals=[...S.excludeGlobals??[],...n])}merge(S.library??={},N,S.library),merge(S.typescript??={},F,S.typescript);let parseKvPairs=(t,n)=>{let S={};for(let C of t){let t=C.indexOf(`=`);if(t===-1)throw Error(`Invalid --${n} value '${C}'. Expected KEY=VALUE.`);let N=C.slice(0,t).trim(),F=C.slice(t+1);if(!N)throw Error(`Invalid --${n} value '${C}'. Empty key.`);S[N]=F}return S},I=parseKvPairs(t.define??[],`define`),H=parseKvPairs(t.alias??[],`alias`);Object.keys(H).length&&(S.aliases={...S.aliases,...H});let W={};if(S.defineFromPackageJson)for(let[t,n]of Object.entries(S.defineFromPackageJson)){if(!n||typeof n.field!=`string`||!n.field)throw Error(`gjsify config: defineFromPackageJson["${t}"] is missing a "field" string`);let S=readDottedPath(N,n.field);W[t]=S===void 0?`undefined`:JSON.stringify(S)}let q={};if(S.defineFromEnv)for(let[t,n]of Object.entries(S.defineFromEnv)){if(!n||typeof n.env!=`string`||!n.env)throw Error(`gjsify config: defineFromEnv["${t}"] is missing an "env" string`);let S=process.env[n.env],C=S===void 0?n.default:S;q[t]=C===void 0?`undefined`:JSON.stringify(C)}let Y=S.bundler??={},X=Y.output??={},Z=Y.transform??={};return t.entryPoints?.length&&(Y.input=t.entryPoints),Y.input||=[`src/index.ts`],t.outfile!==void 0&&(X.file=t.outfile),t.outdir!==void 0&&(X.dir=t.outdir),t.format!==void 0&&(X.format=t.format),t.minify!==void 0&&(X.minify=t.minify),X.minify===void 0&&(X.minify=!0),X.minify===!0&&(X.keepNames=!0),t.logLevel&&(Y.logLevel={silent:`silent`,error:`warn`,warning:`warn`,warn:`warn`,info:`info`,debug:`debug`,verbose:`debug`}[t.logLevel]??`warn`),t.external?.length&&(Y.external=[...Array.isArray(Y.external)?Y.external:[],...t.external]),(Object.keys(I).length||Object.keys(W).length||Object.keys(q).length)&&(Z.define={...Z.define,...W,...q,...I}),S.verbose&&ge.debug(`configData`,S),S}}}),XF,ZF=__esmMin(()=>{YF(),KF(),Vj(),XF={command:`build [entryPoints..]`,description:`Build and bundle your Gjs project`,builder:t=>t.option(`entry-points`,{description:`The entry points you want to bundle. Defaults to bundler.input from package.json#gjsify or .gjsifyrc.js, falling back to src/index.ts when neither is set.`,array:!0,type:`string`,defaultDescription:`src/index.ts (fallback)`,coerce:t=>[...new Set(t)]}).option(`exclude`,{description:`An array of glob patterns to exclude entry-points and aliases`,array:!0,type:`string`,default:[]}).option(`verbose`,{description:`Switch on the verbose mode`,type:`boolean`,default:!1}).option(`app`,{description:"Build target for an application. Defaults to the target of the HOST runtime running the CLI: gjs when run under gjs, node when run under node/bun/deno (both consume the --app node bundle). Set `gjsify.app` in package.json#gjsify to override the host default.",type:`string`,choices:[`gjs`,`node`,`browser`,`nativescript`],defaultDescription:`host runtime target (gjs on gjs, else node)`}).option(`format`,{description:`Override the default output format`,type:`string`,choices:[`iife`,`esm`,`cjs`]}).option(`minify`,{description:`Minify the bundled output. Defaults to true; use --no-minify to emit pretty-printed code (e.g. for debugging or readable bundle review).`,type:`boolean`,defaultDescription:`true`}).option(`library`,{description:`Use this if you want to build a library for Gjsify`,type:`boolean`,default:!1}).option(`outfile`,{alias:`o`,description:`Sets the output file name for the build operation. If no outfile is specified, the outfile will be parsed from the package.json. Only used if application mode is active`,type:`string`,normalize:!0}).option(`outdir`,{alias:`d`,description:`Sets the output directory for the build operation. If no outdir is specified, the outdir will be parsed from the package.json. Only used if library mode is active`,type:`string`,normalize:!0}).option(`reflection`,{alias:`r`,description:`Enables TypeScript types on runtime using Deepkit's type compiler`,type:`boolean`,default:!1}).option(`log-level`,{description:`The log level can be changed to prevent esbuild from printing warning and/or error messages to the terminal`,type:`string`,choices:[`silent`,`error`,`warning`,`info`,`debug`,`verbose`],default:`warning`}).option(`dialect`,{description:`The dialect the SOURCE is written in. 'react-native' aliases 'react-native' onto '@gjsify/react-native' and fails the build on an import whose ADR 0032 support-table status is not supported/partial. GJS and Node app builds. This is NOT gjsify.runtimes['react-native'], which declares the runtime a package RUNS on — the two answer opposite questions.`,type:`string`,choices:[...F_]}).option(`gi-renderer`,{description:"Resolve `gi://Ns?version=X` to the target's widget renderer instead of an empty module (ADR 0034 stage 9): --app browser answers gi://Adw and gi://Gtk out of @gjsify/adwaita-web, --app nativescript out of @gjsify/adwaita-nativescript. A namespace with no renderer, and a ?version= the renderer's vocabulary was not generated against, both FAIL the build by name. Off by default — a gi:// import on those targets is usually a GJS-only code path pulled in transitively.",type:`boolean`}).option(`console-shim`,{description:`Inject a console shim into GJS builds for clean output without the GLib prefix and with working ANSI colors. Use --no-console-shim to disable. Only applies to GJS app builds.`,type:`boolean`,default:!0}).option(`globals`,{description:"Comma-separated list of global identifiers, 'auto' (default) to detect automatically from the bundled output, or 'none' to disable. The 'auto' token may be combined with explicit identifiers/groups (e.g. 'auto,dom') for cases where the detector cannot statically see a global because it's accessed via indirection. Each identifier is mapped to the corresponding `@gjsify/<pkg>/register` module and injected into the bundle. See the CLI Reference docs for the full list of known identifiers. Only applies to GJS app builds.",type:`string`}).option(`shebang`,{description:"Prepend a target-appropriate shebang to the output and mark it executable (chmod 755): `#!/usr/bin/env -S gjs -m` for --app gjs, `#!/usr/bin/env node` for --app node. Applies to GJS and Node app builds with a single --outfile. Default: false (use --shebang to enable, or set `shebang: true` in `.gjsifyrc.js`).",type:`boolean`}).option(`external`,{description:"Module names that should NOT be bundled — EXACT package names only, matched literally on both bundler engines (no globs). Repeat the flag or pass a comma-separated list (e.g. --external typedoc,prettier). Appended to the per-app built-in externals; register subpaths (`<pkg>/register[/…]`) are always force-inlined for --app gjs regardless of this flag.",array:!0,type:`string`,default:[],coerce:t=>t.flatMap(t=>t.split(`,`).map(t=>t.trim()).filter(Boolean))}).option(`define`,{description:`Substitute compile-time constants. Each entry is KEY=VALUE where VALUE is a JS expression (string literals must be quoted: --define VERSION='"1.2.3"'). Repeat the flag or pass comma-separated. See https://esbuild.github.io/api/#define`,array:!0,type:`string`,default:[]}).option(`alias`,{description:`Map module specifiers at bundle time. Each entry is FROM=TO (e.g. --alias typedoc=@gjsify/empty). Layered on top of the built-in alias map. Useful for stubbing heavy deps the test scenario never executes.`,array:!0,type:`string`,default:[],coerce:t=>t.flatMap(t=>t.split(`,`).map(t=>t.trim()).filter(Boolean))}).option(`exclude-globals`,{description:`Comma-separated global identifiers to remove from auto-detection results. Use for false positives from dead browser-compat code whose polyfills require unavailable native libraries (e.g. --exclude-globals fetch,XMLHttpRequest).`,type:`string`}).option(`watch`,{alias:`w`,description:"Watch source files and rebuild on change. Logs each rebuild with duration; clean SIGINT shutdown. Only valid with --app gjs|node|browser (rejected with --library). Requires the npm `rolldown` engine — run under Node, not the GJS-bundled CLI.",type:`boolean`,default:!1}),handler:async t=>{let n=await new Config().forBuild(t);await new GF(n).start({library:t.library,app:n.app,watch:t.watch})}}}),QF,$F=__esmMin(()=>{_e(),hd(),Md(),jn(),IF(),QF={command:`clear [paths..]`,description:"Delete build output recursively. Portable replacement for `rm -rf` in package `clear` scripts.",builder:t=>t.positional(`paths`,{description:"Files and directories to delete, relative to the current package. A missing path is not an error. `*` and `?` are honoured in the last segment.",type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be deleted and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is deleted.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths??[];if(S.length===0)throw Error(`gjsify clear: no paths given. Usage: gjsify clear <paths…>`);let C=resolveClearTargets(S,{cwd:n,readdir:readdirSync});for(let S of C){let C=Sn(n,S);if(t.dryRun){let t=await stat$1(S).then(()=>!0,()=>!1);ge.log(`gjsify clear: would remove ${C}${t?``:` (absent)`}`);continue}await rm$1(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100}),t.verbose&&ge.log(`gjsify clear: removed ${C}`)}}}});function isDirectoryDestination(t,n){return n.endsWith(`/`)||n.endsWith(`\\`)||t.length>1?!0:t.some(t=>hasWildcard(t))}function assertWritableDestination(t,n,S,C){let N=Sn(S,t);if(N===``){if(C)return;throw Error(`gjsify copy: "${n}" is the working directory itself. Name a file, or add a trailing "/" to copy INTO the directory.`)}if(N===`..`||N.startsWith(`..${On}`)||bn(N))throw Error(`gjsify copy: "${n}" resolves to ${t}, outside the working directory ${S}. Only paths inside the package may be written.`)}function expandSource(t,n){let S=Tn(t),C=wn(t);if(hasWildcard(C))throw Error(`gjsify copy: a wildcard is only supported in the last path segment — got "${t}".`);if(!hasWildcard(S))return[vn(n.cwd,t)];let N=vn(n.cwd,C),F=segmentToRegExp(S),I;try{I=n.readdir(N)}catch{return[]}return I.filter(t=>F.test(t)).sort().map(t=>xn(N,t))}function planCopy(t,n){if(t.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let S=t.slice(0,-1),C=t[t.length-1];if(C===``)throw Error(`gjsify copy: the destination is empty.`);let N=isDirectoryDestination(S,C),F=vn(n.cwd,C);assertWritableDestination(F,C,n.cwd,N);let I=[];for(let t of S){if(t===``)throw Error(`gjsify copy: a source path is empty.`);I.push(...expandSource(t,n))}if(!N&&I.length!==1)throw Error(`gjsify copy: "${C}" names a single destination, but ${I.length} sources resolved.`);let H=[],W=new Set;for(let t of I){let n=N?xn(F,Tn(t)):F;if(t===n)throw Error(`gjsify copy: "${t}" is its own destination.`);if(W.has(n))throw Error(`gjsify copy: two sources would both be written to ${n}.`);W.add(n),H.push({from:t,to:n})}return H}var eI=__esmMin(()=>{jn(),IF()}),tI,nI=__esmMin(()=>{_e(),hd(),Md(),jn(),eI(),tI={command:`copy [paths..]`,description:"Copy files and directories into the build output. Portable replacement for `mkdir -p` + `cp -r` in package scripts.",builder:t=>t.positional(`paths`,{description:'One or more sources followed by the destination. The destination is a DIRECTORY when it ends with "/", when several sources are given, or when a source carries a wildcard; otherwise it is the exact target path. Missing parent directories are created. `*` and `?` are honoured in the last segment of a source.',type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be copied and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is copied.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths??[];if(S.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let C=planCopy(S,{cwd:n,readdir:readdirSync}),show=t=>{let S=Sn(n,t);return S===``?`.`:S};for(let{from:n,to:S}of C){if(t.dryRun){ge.log(`gjsify copy: would copy ${show(n)} -> ${show(S)}`);continue}await mkdir$1(wn(S),{recursive:!0}),await cpPromises(n,S,{recursive:!0,force:!0}),t.verbose&&ge.log(`gjsify copy: ${show(n)} -> ${show(S)}`)}}}});function doubleDashArgs(t){let n=t[`--`];if(n==null)return[];if(!Array.isArray(n))throw Error(`gjsify: internal error — yargs' \`--\` slot holds a ${typeof n} rather than an array, so the arguments after \`--\` cannot be forwarded. The command builder must set \`parserConfiguration({ 'populate--': true })\`.`);return n.map((t,n)=>{if(typeof t==`string`)return t;throw Error(`gjsify: internal error — the argument after \`--\` at position ${n} arrived as a ${typeof t} (${String(t)}) instead of a string, so forwarding it would change what the caller wrote. The command builder must set \`parserConfiguration({ 'parse-positional-numbers': false })\` alongside \`populate--\`.`)})}var rI=__esmMin(()=>{});function splitEnvArgv(t){let n=[],S=0;for(;S<t.length;S++){let C=iI.exec(t[S]);if(!C)break;n.push([C[1],C[2]])}return S>=t.length?null:{assignments:n,command:t[S],args:t.slice(S+1)}}function joinEnvArgv(t,n){return n.length===0?[...t]:splitEnvArgv(t)?[...t,`--`,...n]:[...t,...n]}function applyAssignments(t,n,S=process.platform){let C={...t};for(let[t,N]of n){if(S===`win32`)for(let n of Object.keys(C))n!==t&&n.toLowerCase()===t.toLowerCase()&&delete C[n];C[t]=N}return C}var iI,aI,oI=__esmMin(()=>{_e(),rI(),j_(),iI=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s,aI={command:`env <entries..>`,description:"Run a command with extra environment variables: `gjsify env NAME=VALUE… <command> [args…]`. Portable replacement for the POSIX `NAME=value command` prefix, which cmd.exe cannot run.",builder:t=>t.positional(`entries`,{description:"`NAME=VALUE` assignments, then the command and its arguments.",type:`string`,array:!0}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=splitEnvArgv(joinEnvArgv(t.entries??[],doubleDashArgs(t)));if(!n)return ge.error(`gjsify env: no command given. Usage: gjsify env NAME=VALUE… <command> [args…]`),process.exit(1);let{assignments:S,command:C,args:N}=n,F;try{F=await spawnToCompletion(C,N,{completion:`exit`,env:applyAssignments(process.env,S)})}catch(t){let n=t;return ge.error(n.code===`ENOENT`?`gjsify env: \`${C}\` not found on PATH`:`gjsify env: ${C}: ${n.message}`),process.exit(127)}return F.code===0?process.exit(0):(F.code===null&&ge.error(`gjsify env: ${C} ended by ${describeExit(F)}`),process.exit(F.code??1))}}});function parseShebang(t){let n=sI.exec(t.trim());return n?{variables:n[1]??``,prog:n[2]??``,args:n[3]??``}:null}function replaceDollarWithPercentPair(t){return t.replace(/\$\{?([^$@#?\- \t{}:]+)\}?/g,(t,n)=>`%${n}%`)}function convertToSetCommands(t){let n=``;for(let S of t.split(` `)){let t=S.indexOf(`=`);if(t<=0)continue;let C=S.slice(0,t).trim(),N=S.slice(t+1).trim();C&&N&&(n+=`@SET ${C}=${replaceDollarWithPercentPair(N)}\r\n`)}return n}function buildCmdShim(t,n){let S=t.split(`\\`).join(`/`),C=S.split(`/`).join(`\\`),N=S,F=n?.prog??``,I=n?.args??``,H=n?.variables??``,W=F?F.split(`\\`).join(`/`):``,q=W?`"${W}$exe"`:``,Y=``,X=``,Z=``;F?(Y=`"%dp0%\\${F}.exe"`,X=`"$basedir/${F}"`,Z=`"$basedir/${F}$exe"`,C=`"%dp0%\\${C}"`,S=`"$basedir_win/${S}"`,N=`"$basedir/${N}"`):(F=`"%dp0%\\${C}"`,W=`"$basedir/${S}"`,q=W,I=``,C=``,S=``,N=``);let te;if(Y){let t=I.trim();te=cI+convertToSetCommands(H)+`\r
|
|
816
816
|
IF EXIST ${Y} (\r\n SET "_prog=${Y.replace(/(^")|("$)/g,``)}"\r\n) ELSE (\r
|
|
817
817
|
SET "_prog=${F.replace(/(^")|("$)/g,``)}"\r\n)\r
|
|
818
818
|
\r
|
|
819
|
-
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" ${t} ${C} %*\r\n`}else te=`${
|
|
819
|
+
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" ${t} ${C} %*\r\n`}else te=`${cI}${F} ${I} ${C} %*\r\n`;let ne=`#!/bin/sh\n${lI}`;X?ne+=`PROG_EXE=${X.replace(/"$/,`.exe"`)}\nif ! [ -x "\$PROG_EXE" ]; then
|
|
820
820
|
PROG_EXE=${X}\n if ! [ -x "\$PROG_EXE" ]; then
|
|
821
821
|
PROG_EXE=${W}\n if ! [ -x "\$PROG_EXE" ]; then
|
|
822
822
|
PROG_EXE=${W}.exe\n fi
|
|
823
823
|
fi
|
|
824
824
|
fi
|
|
825
825
|
|
|
826
|
-
exec ${H}"$PROG_EXE" ${I} ${S} "$@"\n`:ne+=`exec ${W} ${I} ${S} "$@"\n`;let re=
|
|
826
|
+
exec ${H}"$PROG_EXE" ${I} ${S} "$@"\n`:ne+=`exec ${W} ${I} ${S} "$@"\n`;let re=uI;return Z?re+=`\$ret=0
|
|
827
827
|
if (Test-Path ${Z}) {\n # Support pipeline input
|
|
828
828
|
if (\$MyInvocation.ExpectingInput) {
|
|
829
829
|
$input | & ${Z} ${I} ${N} $args\n } else {
|
|
@@ -842,7 +842,7 @@ if (\$MyInvocation.ExpectingInput) {
|
|
|
842
842
|
$input | & ${q} ${N} $args\n} else {
|
|
843
843
|
& ${q} ${N} $args\n}
|
|
844
844
|
exit \$LASTEXITCODE
|
|
845
|
-
`,{sh:ne,cmd:te,ps1:re}}function buildLauncherShims(t){let{interpreter:n,interpreterArgs:S=[],target:C,prependEnv:N={},fallback:F}=t,I=C.split(`/`).join(`\\`),H=S.length>0?`${S.join(` `)} `:``,W=Object.entries(N),q=F===void 0?``:F.target.split(`/`).join(`\\`),Y=F?.interpreterArgs!==void 0&&F.interpreterArgs.length>0?`${F.interpreterArgs.join(` `)} `:``,X=
|
|
845
|
+
`,{sh:ne,cmd:te,ps1:re}}function buildLauncherShims(t){let{interpreter:n,interpreterArgs:S=[],target:C,prependEnv:N={},fallback:F}=t,I=C.split(`/`).join(`\\`),H=S.length>0?`${S.join(` `)} `:``,W=Object.entries(N),q=F===void 0?``:F.target.split(`/`).join(`\\`),Y=F?.interpreterArgs!==void 0&&F.interpreterArgs.length>0?`${F.interpreterArgs.join(` `)} `:``,X=cI;for(let[t,n]of W)X+=`@SET "${t}=${n};%${t}%"\r\n`;F===void 0?X+=`${n} ${H}"${I}" %*\r\n`:X+=`@where ${n} >NUL 2>NUL\r\n@IF %ERRORLEVEL% EQU 0 (\r\n ${n} ${H}"${I}" %*\r\n) ELSE (\r\n ${F.interpreter} ${Y}"${q}" %*\r\n)\r\n`;let Z=`#!/usr/bin/env pwsh
|
|
846
846
|
`;for(let[t,n]of W)Z+=`$env:${t} = "${n};" + $env:${t}\n`;let te=S.map(t=>`"${t}" `).join(``);if(F===void 0)Z+=`# Support pipeline input
|
|
847
847
|
if (\$MyInvocation.ExpectingInput) {
|
|
848
848
|
$input | & "${n}" ${te}"${I}" $args\n} else {
|
|
@@ -855,7 +855,7 @@ if (\$MyInvocation.ExpectingInput) {
|
|
|
855
855
|
& \$exe @exeArgs \$script \$args
|
|
856
856
|
}
|
|
857
857
|
`}return Z+=`exit $LASTEXITCODE
|
|
858
|
-
`,{cmd:X,ps1:Z}}function shQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function buildNativeEnvPreamble(t,n=[],S={}){let C=S.platform??process.platform,N=S.arch??process.arch,F=S.libc===void 0?detectHostLibc(C):S.libc,{name:I,separator:H}=libraryPathVar(C);if(C===`win32`){if(n.length===0)return``;let t=shQuote(n.join(H));return`GI_TYPELIB_PATH=${t}\${GI_TYPELIB_PATH:+"${H}$GI_TYPELIB_PATH"}\n${I}=${t}\${${I}:+"${H}$${I}"}\nexport GI_TYPELIB_PATH ${I}\n`}let W=`${t.replace(/\/+$/,``)}/node_modules/`,q=n.filter(t=>!t.startsWith(W)),Y=prebuildDirCandidates(C,N,void 0,F),X=[];for(let n of Y)X.push(`${shQuote(t)}/node_modules/@*/*/prebuilds/${n}`),X.push(`${shQuote(t)}/node_modules/*/prebuilds/${n}`);return`gjsify_np=${q.length>0?shQuote(q.join(H)):`''`}\nfor gjsify_d in ${X.join(` `)}; do\n [ -d "$gjsify_d" ] || continue\n for gjsify_t in "$gjsify_d"/*.typelib; do\n if [ -f "$gjsify_t" ]; then gjsify_np="\${gjsify_np:+$gjsify_np${H}}$gjsify_d"; break; fi\n done\ndone\nif [ -n "$gjsify_np" ]; then\n GI_TYPELIB_PATH="$gjsify_np\${GI_TYPELIB_PATH:+${H}$GI_TYPELIB_PATH}"\n ${I}="$gjsify_np\${${I}:+${H}$${I}}"\n export GI_TYPELIB_PATH ${I}\nfi\nunset gjsify_np gjsify_d gjsify_t\n`+dyldFallbackPreamble(C)}function dyldFallbackPreamble(t){return t===`darwin`?`DYLD_FALLBACK_LIBRARY_PATH="\${DYLD_FALLBACK_LIBRARY_PATH:+$DYLD_FALLBACK_LIBRARY_PATH:}${dyldDefaultFallbackDirs({HOME:`$HOME`}).join(`:`)}"\nexport DYLD_FALLBACK_LIBRARY_PATH\n`:``}function shQuoteArg(t){return shQuote(t)}function normalizeBinMap(t,n){let S=new Map;if(typeof n==`string`){let C=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t;return S.set(C,n),S}for(let[t,C]of Object.entries(n))S.set(t,C);return S}function pickBinMap(t,n){let S=n.gjsify?.bin,C=n.bin;return S===void 0?C===void 0?null:{map:normalizeBinMap(t,C),isGjsBin:!1,nodeFallback:null}:{map:normalizeBinMap(t,S),isGjsBin:!0,nodeFallback:C===void 0?null:normalizeBinMap(t,C)}}function buildShLauncher(t,n){let S=n.isGjsBundle?n.envPreamble??``:``,C=n.gjs===void 0||n.gjs===`gjs`?`gjs`:shQuote(n.gjs);return n.isGjsBundle&&n.nodeFallbackAbs!==void 0?`#!/bin/sh\nif command -v ${C} >/dev/null 2>&1; then\n${S}exec ${C} -m ${shQuote(t)} "$@"\nfi\nexec node ${shQuote(n.nodeFallbackAbs)} "$@"\n`:`#!/bin/sh\n${S}${n.isGjsBundle?`exec ${C} -m ${shQuote(t)} "$@"`:`exec ${shQuote(t)} "$@"`}\n`}function isGjsBundlePath(t){return t.endsWith(`.gjs.mjs`)||t.endsWith(`.mjs`)}var
|
|
858
|
+
`,{cmd:X,ps1:Z}}function shQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function buildNativeEnvPreamble(t,n=[],S={}){let C=S.platform??process.platform,N=S.arch??process.arch,F=S.libc===void 0?detectHostLibc(C):S.libc,{name:I,separator:H}=libraryPathVar(C);if(C===`win32`){if(n.length===0)return``;let t=shQuote(n.join(H));return`GI_TYPELIB_PATH=${t}\${GI_TYPELIB_PATH:+"${H}$GI_TYPELIB_PATH"}\n${I}=${t}\${${I}:+"${H}$${I}"}\nexport GI_TYPELIB_PATH ${I}\n`}let W=`${t.replace(/\/+$/,``)}/node_modules/`,q=n.filter(t=>!t.startsWith(W)),Y=prebuildDirCandidates(C,N,void 0,F),X=[];for(let n of Y)X.push(`${shQuote(t)}/node_modules/@*/*/prebuilds/${n}`),X.push(`${shQuote(t)}/node_modules/*/prebuilds/${n}`);return`gjsify_np=${q.length>0?shQuote(q.join(H)):`''`}\nfor gjsify_d in ${X.join(` `)}; do\n [ -d "$gjsify_d" ] || continue\n for gjsify_t in "$gjsify_d"/*.typelib; do\n if [ -f "$gjsify_t" ]; then gjsify_np="\${gjsify_np:+$gjsify_np${H}}$gjsify_d"; break; fi\n done\ndone\nif [ -n "$gjsify_np" ]; then\n GI_TYPELIB_PATH="$gjsify_np\${GI_TYPELIB_PATH:+${H}$GI_TYPELIB_PATH}"\n ${I}="$gjsify_np\${${I}:+${H}$${I}}"\n export GI_TYPELIB_PATH ${I}\nfi\nunset gjsify_np gjsify_d gjsify_t\n`+dyldFallbackPreamble(C)}function dyldFallbackPreamble(t){return t===`darwin`?`DYLD_FALLBACK_LIBRARY_PATH="\${DYLD_FALLBACK_LIBRARY_PATH:+$DYLD_FALLBACK_LIBRARY_PATH:}${dyldDefaultFallbackDirs({HOME:`$HOME`}).join(`:`)}"\nexport DYLD_FALLBACK_LIBRARY_PATH\n`:``}function shQuoteArg(t){return shQuote(t)}function normalizeBinMap(t,n){let S=new Map;if(typeof n==`string`){let C=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t;return S.set(C,n),S}for(let[t,C]of Object.entries(n))S.set(t,C);return S}function pickBinMap(t,n){let S=n.gjsify?.bin,C=n.bin;return S===void 0?C===void 0?null:{map:normalizeBinMap(t,C),isGjsBin:!1,nodeFallback:null}:{map:normalizeBinMap(t,S),isGjsBin:!0,nodeFallback:C===void 0?null:normalizeBinMap(t,C)}}function buildShLauncher(t,n){let S=n.isGjsBundle?n.envPreamble??``:``,C=n.gjs===void 0||n.gjs===`gjs`?`gjs`:shQuote(n.gjs);return n.isGjsBundle&&n.nodeFallbackAbs!==void 0?`#!/bin/sh\nif command -v ${C} >/dev/null 2>&1; then\n${S}exec ${C} -m ${shQuote(t)} "$@"\nfi\nexec node ${shQuote(n.nodeFallbackAbs)} "$@"\n`:`#!/bin/sh\n${S}${n.isGjsBundle?`exec ${C} -m ${shQuote(t)} "$@"`:`exec ${shQuote(t)} "$@"`}\n`}function isGjsBundlePath(t){return t.endsWith(`.gjs.mjs`)||t.endsWith(`.mjs`)}var sI,cI,lI,uI,dI=__esmMin(()=>{$P(),zP(),sI=/^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?((?:[^ \t=]+=[^ \t=]+\s+)*))?([^ \t]+)(.*)$/,cI=`@ECHO off\r
|
|
859
859
|
GOTO start\r
|
|
860
860
|
:find_dp0\r
|
|
861
861
|
SET dp0=%~dp0\r
|
|
@@ -863,7 +863,7 @@ EXIT /b\r
|
|
|
863
863
|
:start\r
|
|
864
864
|
SETLOCAL\r
|
|
865
865
|
CALL :find_dp0\r
|
|
866
|
-
`,
|
|
866
|
+
`,lI=`basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")
|
|
867
867
|
basedir_win="$basedir"
|
|
868
868
|
|
|
869
869
|
case \`uname -a\` in
|
|
@@ -883,7 +883,7 @@ case \`uname -a\` in
|
|
|
883
883
|
;;
|
|
884
884
|
esac
|
|
885
885
|
|
|
886
|
-
`,
|
|
886
|
+
`,uI=`#!/usr/bin/env pwsh
|
|
887
887
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
|
888
888
|
|
|
889
889
|
$exe=""
|
|
@@ -892,37 +892,37 @@ if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
|
|
892
892
|
# are installed in the same directory
|
|
893
893
|
$exe=".exe"
|
|
894
894
|
}
|
|
895
|
-
`});function splitExecArgv(t,n=[]){let S={runtime:null,rebuild:!1,verbose:!1},setRuntime=t=>{if(t===void 0||!
|
|
896
|
-
`)||` (no node_modules found)`}\nInstall the package that provides it (\`gjsify install <pkg>\`), or use \`gjsify dlx\` for a one-off run.`),this.binName=t,this.searched=n,this.name=`ExecBinNotFoundError`}},ExecPlanError=class extends Error{constructor(t){super(t),this.name=`ExecPlanError`}},__name$1(readManifest$1,`readManifest`),
|
|
895
|
+
`});function splitExecArgv(t,n=[]){let S={runtime:null,rebuild:!1,verbose:!1},setRuntime=t=>{if(t===void 0||!fI.includes(t))throw new ExecPlanError(`gjsify exec: --runtime expects one of ${fI.join(`, `)}, got ${t===void 0?`nothing`:`"${t}"`}.`);S.runtime=t},C=0;for(;C<t.length;C++){let n=t[C];if(!n.startsWith(`-`))break;if(n===`--rebuild`)S.rebuild=!0;else if(n===`--verbose`)S.verbose=!0;else if(n===`--runtime`)setRuntime(t[++C]);else if(n.startsWith(`--runtime=`))setRuntime(n.slice(10));else throw new ExecPlanError(`gjsify exec: unknown option "${n}" before the bin name. Options for the bin go AFTER it (\`gjsify exec <bin> --flag\`); gjsify exec itself takes --runtime <gjs|node|bun|deno>, --rebuild, --verbose.`)}if(C<t.length)return{...S,bin:t[C],args:[...t.slice(C+1),...n.length?[`--`,...n]:[]]};if(n.length>0)return{...S,bin:n[0],args:n.slice(1)};throw new ExecPlanError(`gjsify exec: no bin given. Usage: gjsify exec [--runtime <r>] [--rebuild] <bin> [args…]`)}function readManifest$1(t){return readPackageJson$2(xn(t,`package.json`))}function realOrNull(t){try{return realpathSync(t)}catch{return null}}function isInsideNodeModules(t){return t.split(On).includes(`node_modules`)}function binFromPackage(t,n,S){let C=readManifest$1(t);if(!C?.name)return null;let N=C.bin===void 0?void 0:normalizeBinMap(C.name,C.bin).get(n),F=C.gjsify?.bin===void 0?void 0:normalizeBinMap(C.name,C.gjsify.bin).get(n);if(N===void 0&&F===void 0)return null;let I=realOrNull(t)??vn(t),H=N===void 0?null:realOrNull(xn(t,N)),W=F===void 0?null:realOrNull(xn(t,F));return H===null&&W===null?null:{binName:n,pkgName:C.name,pkgVersion:C.version??`0.0.0`,pkgDir:I,entry:H,gjsEntry:W,nodeModules:S,installed:isInsideNodeModules(I)}}function listPackages(t){let n=[],S;try{S=readdirSync(t)}catch{return n}for(let C of S)if(!C.startsWith(`.`))if(C.startsWith(`@`)){let S;try{S=readdirSync(xn(t,C))}catch{continue}for(let N of S)n.push(xn(t,C,N))}else n.push(xn(t,C));return n}function ownerOfLinkedBin(t,n,S){let C=wn(t);for(;;){if(existsSync(xn(C,`package.json`))){let N=binFromPackage(C,n,S);if(N&&(N.entry===t||N.gjsEntry===t))return N}let N=wn(C);if(N===C)return null;C=N}}function resolveExecBin(t,n){let S=[],C=vn(n);for(;;){if(existsSync(xn(C,`package.json`))){let n=binFromPackage(C,t,null);if(n)return n;break}let n=wn(C);if(n===C)break;C=n}for(C=vn(n);;){let n=xn(C,`node_modules`);if(existsSync(n)){S.push(n);let C=xn(n,`.bin`);if([t,`${t}.cmd`].some(t=>existsSync(xn(C,t)))){let S=xn(C,t),N=(()=>{try{return lstatSync(S).isSymbolicLink()}catch{return!1}})()?realOrNull(S):null,F=N?ownerOfLinkedBin(N,t,n):null;if(F)return F;let I=listPackages(n).sort((n,S)=>Number(Tn(S)===t)-Number(Tn(n)===t));for(let S of I){let C=binFromPackage(S,t,n);if(C)return C}}}let N=wn(C);if(N===C)break;C=N}throw new ExecBinNotFoundError(t,S)}function planExec(t,n){if(n===`gjs`){if(t.gjsEntry)return{kind:`gjs-bundle`,file:t.gjsEntry};if(t.entry)return{kind:`rebuild`,entry:t.entry}}else if(t.entry)return{kind:`direct`,runtime:n,file:t.entry};else throw new ExecPlanError(`gjsify exec: "${t.binName}" from ${t.pkgName} is declared only as a GJS bundle (\`gjsify.bin\`), which ${n} cannot run. Run it on GJS: \`gjsify exec --runtime gjs ${t.binName}\`.`);throw new ExecPlanError(`gjsify exec: "${t.binName}" from ${t.pkgName} names no file that exists.`)}function execCacheKey(t){let n=JSON.stringify([`gjsify-exec/v1`,t.pkgName,t.pkgVersion,t.entry.split(On).join(`/`),t.cliVersion,t.lockfileHash]);return createHash(`sha256`).update(n).digest(`hex`)}function findProjectLockfile(t){let n=vn(t);for(;;){for(let t of pI){let S=xn(n,t);if(existsSync(S))return S}let t=wn(n);if(t===n)return null;n=t}}function hashFile(t){return createHash(`sha256`).update(readFileSync(t)).digest(`hex`)}function execCacheRoot(t){return xn(t,`.cache`,`gjsify`,`exec`)}function execArtifactPath(t,n,S,C){return xn(t,`${`${n.pkgName}@${n.pkgVersion}`.replace(/[^a-zA-Z0-9._@-]/g,`_`)}-${C.slice(0,16)}`,artifactFileName(S))}function artifactFileName(t){return Tn(t).replace(/\.cjs$/i,`.mjs`)}function entryWithinPackage(t,n){return Sn(t.pkgDir,n)}var fI,ExecBinNotFoundError,ExecPlanError,pI,mI=__esmMin(()=>{Kc(),Md(),jn(),dI(),HF(),kP(),fI=[`gjs`,`node`,`bun`,`deno`],ExecBinNotFoundError=class extends Error{binName;searched;constructor(t,n){super(`gjsify exec: no bin named "${t}" in this project.\nLooked in the nearest package.json and in:\n${n.map(t=>` ${t}`).join(`
|
|
896
|
+
`)||` (no node_modules found)`}\nInstall the package that provides it (\`gjsify install <pkg>\`), or use \`gjsify dlx\` for a one-off run.`),this.binName=t,this.searched=n,this.name=`ExecBinNotFoundError`}},ExecPlanError=class extends Error{constructor(t){super(t),this.name=`ExecPlanError`}},__name$1(readManifest$1,`readManifest`),pI=[...VF,`bun.lock`,`bun.lockb`]});function hangGraceMs(t){let n=t.GJSIFY_HANG_GRACE_MS;if(n===void 0||n.trim()===``)return hI;let S=Number(n);return Number.isFinite(S)&&S>=0?S:hI}function heartbeatEnv(t,n){let S={...t};return n?S.GJSIFY_UNIT_HEARTBEAT=n:delete S.GJSIFY_UNIT_HEARTBEAT,S}function parseHeartbeat(t){if(!t)return null;let n=t.split(`
|
|
897
897
|
`,1)[0]??``,S=n.indexOf(` `);if(S<0)return null;let C=Number(n.slice(0,S));if(!Number.isFinite(C)||C<0)return null;let N=n.slice(S+1).trim();return N.length===0?null:{deadlineMs:C,label:N}}function formatHangReport(t){let n=[`⏱ hang: "${t.label}" is ${Math.round(t.overdueMs/1e3)}s past its own deadline`,` gjs pid ${t.pid} stopped turning its main loop, so @gjsify/unit's timeout cannot fire`,` (see packages/gjs/unit/src/heartbeat.ts). Killing it rather than holding the job open.`];if(t.backtrace){n.push(` native backtrace at the moment of the hang:`);for(let S of t.backtrace.split(`
|
|
898
898
|
`))n.push(` ${S}`)}else n.push(` no native backtrace: eu-stack (elfutils) absent, refused the attach, or found nothing`);return t.graceMs!==void 0&&(n.push(` a test that legitimately blocks the loop this long: raise GJSIFY_HANG_GRACE_MS`),n.push(` (now ${t.graceMs} ms, 0 disables this guard).`)),n.join(`
|
|
899
899
|
`)}function captureNativeBacktrace(t,n=40){try{let S=spawnSync(`eu-stack`,[`-p`,String(t)],{encoding:`utf8`,timeout:5e3,maxBuffer:4*1024*1024}),C=typeof S.stdout==`string`?S.stdout.trim():``;return C.length===0?void 0:C.split(`
|
|
900
900
|
`).slice(0,n).join(`
|
|
901
|
-
`)}catch{return}}function createHangWatchdog(t){let n=t.now??Date.now,S=t.graceMs??3e4,C,N=!1,tick=()=>{if(N)return;let C=parseHeartbeat(t.read());!C||C.deadlineMs<=0||n()-(C.deadlineMs+S)<0||(N=!0,stop(),t.onHang(C,n()-C.deadlineMs))},stop=()=>{C!==void 0&&clearInterval(C),C=void 0};return{tick,start:(t=
|
|
901
|
+
`)}catch{return}}function createHangWatchdog(t){let n=t.now??Date.now,S=t.graceMs??3e4,C,N=!1,tick=()=>{if(N)return;let C=parseHeartbeat(t.read());!C||C.deadlineMs<=0||n()-(C.deadlineMs+S)<0||(N=!0,stop(),t.onHang(C,n()-C.deadlineMs))},stop=()=>{C!==void 0&&clearInterval(C),C=void 0};return{tick,start:(t=gI)=>{C===void 0&&(C=setInterval(tick,t))},stop}}var hI,gI,_I=__esmMin(()=>{w_(),hI=3e4,gI=1e3}),vI=__exportAll$5({computeNativeEnvForBundle:()=>computeNativeEnvForBundle,runGjsBundle:()=>runGjsBundle});function computeNativeEnvForBundle(t,n=process.cwd(),S=process.env,C=[]){let N=vn(t),F=[],I=new Set;for(let t of[n,wn(N),...C])for(let n of detectNativePackages(t))I.has(n.name)||(I.add(n.name),F.push(n));let H=buildNativeEnv(F,{env:S});return{env:H,envPrefix:Object.entries(H).filter(([t,n])=>n!==void 0&&n!==``&&n!==S[t]).map(([t,n])=>`${t}=${n}`).join(` `)}}function safeMkdtemp(){try{return mkdtempSync(xn(tmpdir(),`gjsify-hb-`))}catch{return}}async function runGjsBundle(t,n=[],S){let{env:C,envPrefix:N}=computeNativeEnvForBundle(t,process.cwd(),process.env,S.nativeRoots),F=hangGraceMs(process.env),I=F>0?safeMkdtemp():void 0,H=I?xn(I,`unit.heartbeat`):void 0,W=heartbeatEnv({...process.env,...C},H),q=[`-m`,t,...n],Y=[`gjs`,...q.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);S.quiet||ge.error(`$ ${N?`${N} `:``}${Y}`);let failed=t=>(process.exitCode=t,process.exit(t)),X,Z=!1,te=H?createHangWatchdog({read:()=>{try{return readFileSync(H,`utf8`)}catch{return null}},graceMs:F,onHang:(t,n)=>{let S=X?.pid;S!==void 0&&(Z=!0,ge.error(formatHangReport({label:t.label,overdueMs:n,pid:S,graceMs:F,backtrace:captureNativeBacktrace(S)})),X?.kill(`SIGABRT`),setTimeout(()=>X?.kill(`SIGKILL`),2e3))}}):void 0,ne;try{ne=await spawnToCompletion(`gjs`,q,{completion:S.completion,env:W,onSpawn:t=>{X=t,te?.start()}})}catch(t){return ge.error(t.message),failed(1)}finally{te?.stop(),I&&rmSync(I,{recursive:!0,force:!0})}if(Z)return failed(ne.code??1);if(ne.code!==0)return S.quietExit||ge.error(`gjs exited with ${describeExit(ne)}`),failed(ne.code??1);if(S.exitOnSuccess)return process.exit(0)}var yI=__esmMin(()=>{_e(),Md(),Dg(),jn(),$P(),j_(),_I()}),bI=__exportAll$5({bundleRequiresNodeGi:()=>bundleRequiresNodeGi,nodeBinary:()=>nodeBinary,resolveNodeGi:()=>resolveNodeGi,resolveNodeGiForBundle:()=>resolveNodeGiForBundle,runNodeBundle:()=>runNodeBundle,runRuntimeBundle:()=>runRuntimeBundle});function resolveNodeGi(t){let n=vn(t);for(;;){if(existsSync(xn(n,`node_modules`,`@gjsify`,`node-gi`,`package.json`)))return xn(n,`node_modules`,`@gjsify`,`node-gi`);let t=vn(n,`..`);if(t===n)return null;n=t}}function resolveNodeGiForBundle(t,n){return resolveNodeGi(wn(vn(t)))??resolveNodeGi(n)}function nodeBinary(){return isNode()&&process.execPath?process.execPath:`node`}async function runNodeBundle(t,n=[],S){let C=process.cwd();if(!resolveNodeGiForBundle(t,C))throw Error(`Cannot run the storybook on Node: \`@gjsify/node-gi\` is not installed.
|
|
902
902
|
Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
|
|
903
903
|
"devDependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:N,envPrefix:F}=computeNativeEnvForBundle(t,C),I={...process.env,...N},H=nodeBinary(),W=[t,...n],q=[H,...W.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);ge.error(`$ ${F?`${F} `:``}${q}`);let Y;try{Y=await spawnToCompletion(H,W,{completion:S.completion,env:I})}catch(t){return ge.error(t.message),process.exit(1)}if(Y.code!==0)return ge.error(`node exited with ${describeExit(Y)}`),process.exit(Y.code??1);if(S.exitOnSuccess)return process.exit(0)}function bundleRequiresNodeGi(t){try{return readFileSync(t,`utf-8`).includes(`@gjsify/node-gi`)}catch{return!1}}async function runRuntimeBundle(t,n,S=[],C){let N=process.cwd(),F=vn(n);if(bundleRequiresNodeGi(F)&&!resolveNodeGiForBundle(F,N))throw Error(`Cannot run this bundle on ${t}: it uses gi:// via \`@gjsify/node-gi\`, which is not installed.\nAdd @gjsify/node-gi as a dependency to run gi:// code off GJS, e.g.:
|
|
904
|
-
"dependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:I,envPrefix:H}=computeNativeEnvForBundle(F,N),W={...process.env,...I},[,q]=N_[t].launch(F,S),Y=t===`node`?nodeBinary():N_[t].probe,X=[Y,...q.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);C.quiet||ge.error(`$ ${H?`${H} `:``}${X}`);let failed=t=>(process.exitCode=t,process.exit(t)),Z;try{Z=await spawnToCompletion(Y,q,{completion:C.completion,env:W})}catch(t){return ge.error(t.message),failed(1)}if(Z.code!==0)return C.quietExit||ge.error(`${t} exited with ${describeExit(Z)}`),failed(Z.code??1);if(C.exitOnSuccess)return process.exit(0)}var bI=__esmMin(()=>{_e(),Md(),jn(),t_(),vI(),P_(),j_()});function nearestNodeModules(t){let n=vn(t);for(;;){let t=xn(n,`node_modules`);if(existsSync(t))return t;let S=wn(n);if(S===n)return null;n=S}}async function rebuildForGjs(t,n,S){let C=t.nodeModules??nearestNodeModules(process.cwd())??xn(t.pkgDir,`node_modules`),N=findProjectLockfile(wn(C)),F=execCacheKey({pkgName:t.pkgName,pkgVersion:t.pkgVersion,entry:entryWithinPackage(t,n),cliVersion:cliVersion(),lockfileHash:N?hashFile(N):null}),I=execArtifactPath(execCacheRoot(C),t,n,t.installed?F:`local`),H=t.installed&&!S.rebuild;if(H&&existsSync(I))return S.verbose&&ge.error(`gjsify exec: reusing ${I}`),I;ge.error(`gjsify exec: rebuilding ${t.pkgName}@${t.pkgVersion} "${t.binName}" for GJS…`);let W=wn(I),q=`${W}.tmp-${process.pid.toString(16)}-${Date.now().toString(16)}`,Y=xn(q,Tn(I));try{let{BuildAction:C}=await Promise.resolve().then(()=>(GF(),HF));await C.bundleFileForGjs(n,Y,{verbose:S.verbose,preserveDefaultExport:!1,...t.installed?{}:{define:{"import.meta.url":JSON.stringify(pathToFileURL(n).href)}},toolchainAnchor:C.runningCliFile(),...S.verbose?{}:{logLevel:`silent`}})}catch(C){throw rmSync(q,{recursive:!0,force:!0}),new ExecRebuildError(t,n,C,S.verbose)}if(H&&existsSync(I))return rmSync(q,{recursive:!0,force:!0}),I;rmSync(W,{recursive:!0,force:!0});try{renameSync(q,W)}catch(t){if(rmSync(q,{recursive:!0,force:!0}),!existsSync(I))throw t}return pruneStaleArtifacts(wn(W),t,Tn(W)),I}function pruneStaleArtifacts(t,n,S){let C=`${n.pkgName}@${n.pkgVersion}`.replace(/[^a-zA-Z0-9._@-]/g,`_`),N;try{N=readdirSync(t)}catch{return}for(let n of N)n===S||!n.startsWith(`${C}-`)||n.includes(`.tmp-`)||rmSync(xn(t,n),{recursive:!0,force:!0})}var ExecRebuildError,xI,SI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),nI(),pI(),Xm(),vI(),bI(),ExecRebuildError=class extends Error{constructor(t,n,S,C){let N=S instanceof Error?S.message:String(S);super(`gjsify exec: rebuilding "${t.binName}" (${t.pkgName}@${t.pkgVersion}) for GJS failed.\n entry: ${n}\nNothing was run — gjsify exec never falls back to another runtime on its own. To run it on Node explicitly: \`gjsify exec --runtime node ${t.binName}\`.\n`+(C?``:`Re-run with \`gjsify exec --verbose ${t.binName}\` for the bundler's warnings.\n`)+`Bundler diagnostics:\n${N}`,{cause:S}),this.name=`ExecRebuildError`}},xI={command:`exec <entries..>`,description:"Run an installed npm bin on the runtime gjsify runs on: `gjsify exec [--runtime gjs|node|bun|deno] [--rebuild] [--verbose] <bin> [args…]`. On Node/Bun/Deno the bin runs unchanged; on GJS it is rebuilt `--app gjs` once, cached under node_modules/.cache/gjsify/exec/, and run with gjs. Options go BEFORE the bin; everything after it is the bin's own.",builder:t=>t.positional(`entries`,{description:`gjsify exec options, then the bin name and its arguments.`,type:`string`,array:!0}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n,S,C;try{n=splitExecArgv(t.entries??[],doubleDashArgs(t)),S=resolveExecBin(n.bin,process.cwd()),C=planExec(S,n.runtime??hostRuntime$1())}catch(t){if(t instanceof ExecBinNotFoundError)return ge.error(t.message),process.exit(127);if(t instanceof ExecPlanError)return ge.error(t.message),process.exit(1);throw t}let N={completion:`exit`,exitOnSuccess:!0,quiet:!n.verbose,quietExit:!0};if(C.kind===`direct`){await runRuntimeBundle(C.runtime,C.file,n.args,N);return}if(C.kind===`gjs-bundle`){await runGjsBundle(C.file,n.args,N);return}let F=await rebuildForGjs(S,C.entry,{rebuild:n.rebuild,verbose:n.verbose}),I=cliPackageDir();await runGjsBundle(F,n.args,{...N,nativeRoots:I?[I]:[]})}}});function bundleInputsPath(t){return`${t}.inputs.json`}function idToPath(t){if(t===``||t.startsWith(`\0`))return null;let n=t.search(/[?#]/);if(n===-1)return t;let S=t.slice(0,n);return isFile(S)?S:t}function isFile(t){try{return statSync(t).isFile()}catch{return!1}}function isToolchainScratch(t){return t.includes(`${On}node_modules${On}.cache${On}`)}function resolutionFilesFor(t){let n=[];for(let S=wn(t);;S=wn(S)){let t=xn(S,`package.json`);if(existsSync(t)){n.push(t);let C=xn(S,`tsconfig.json`);return existsSync(C)&&n.push(C),n}if(wn(S)===S)return n}}function createBundleInputsRecorder(t){let n=new Set,S=!0,record=t=>{let S=idToPath(t);S!==null&&n.add(S)},C={name:`gjsify:bundle-inputs`,transform(t,n){record(n)}},inputs=()=>{let t=[],S=new Set;for(let C of n){let n;try{n=statSync(C).isFile()}catch{continue}if(!n||isToolchainScratch(C))continue;t.push(C);let N=wn(C);if(!S.has(N)){S.add(N);for(let n of resolutionFilesFor(C))t.push(n)}}return[...new Set(t)].sort()};return{plugin:C,addWatchFiles(t){t.reportedByEngine||(S=!1);for(let n of t.files)record(n)},inputs,write(){let n=bundleInputsPath(t),C={version:2,inputs:inputs(),watchList:S},N=`${n}.tmp`;try{mkdirSync(wn(n),{recursive:!0}),writeFileSync(N,`${JSON.stringify(C,null,2)}\n`,`utf-8`),renameSync(N,n)}catch(t){try{rmSync(N,{force:!0})}catch{}ge.warn(`[gjsify test] could not record the build inputs beside ${n} (${t.message}) — the next run judges freshness by the package walk alone, which cannot see outside this package.`)}}}}function readBundleInputs(t){let n;try{n=JSON.parse(readFileSync(bundleInputsPath(t),`utf-8`))}catch{return null}return n?.version!==2||!Array.isArray(n.inputs)?null:{inputs:n.inputs.filter(t=>typeof t==`string`),watchList:n.watchList===!0}}function newestBundleInputMtimeMs(t){let n=0;for(let S of t)try{let{mtimeMs:t}=statSync(S);t>n&&(n=t)}catch{return 1/0}return n}var CI=__esmMin(()=>{_e(),Md(),jn()});async function buildTestBundle(t,n,S,C){let N=await new Config().forBuild({entryPoints:[t],outfile:n,app:S,verbose:C??!1,logLevel:`warning`,exclude:[]});N.library={...N.library};let F=createBundleInputsRecorder(n);N.bundler={...N.bundler,input:[t],output:{...N.bundler?.output,file:n},plugins:[...N.bundler?.plugins??[],F.plugin]},await new WF(N).start({app:S,library:!1,onWatchFiles:t=>F.addWatchFiles(t)}),F.write()}async function runTestBundle(t,n){if(n===`gjs`){await runGjsBundle(t,[],{completion:`exit`});return}let S=await spawnToCompletion(nodeBinary(),[t],{completion:`exit`});if(S.code!==0)throw Error(`node exited with ${describeExit(S)}`)}function isFresh(t,n,S,C){if(!existsSync(t))return!1;try{let N=statSync(t).mtimeMs,F=[],I=Sn(S,C).split(On).join(`/`);I!==``&&!I.startsWith(`../`)&&F.push(I);let H=readBundleInputs(t);return H!==null&&!H.watchList?!1:N>=Math.max(newestInputMtimeMs(packageBuildInputs(S,{extraOutputs:F})),H===null?0:newestBundleInputMtimeMs(H.inputs),statSync(n).mtimeMs,newestDepSignalMtimeMs(S))}catch{return!1}}var wI,TI=__esmMin(()=>{_e(),Md(),jn(),CI(),VF(),P_(),bI(),j_(),JF(),GF(),vI(),wI={command:`test`,description:"Build + run the package’s `src/test.mts` suite on GJS and Node and aggregate the results. Replaces the per-package `build:test:{gjs,node}` + `test:{gjs,node}` script boilerplate.",builder:t=>t.option(`runtime`,{description:`Target runtime. Default: both.`,type:`string`,choices:[`gjs`,`node`,`all`],default:`all`}).option(`entry`,{description:"Path to the test entry. Default: `src/test.mts` (or `gjsify.test.entry`).",type:`string`,normalize:!0}).option(`outdir`,{description:"Output directory for the built test bundles. Default: `dist/`.",type:`string`,normalize:!0}).option(`rebuild`,{description:`Always rebuild the test bundles, even when they look up-to-date.`,type:`boolean`,default:!1}).option(`build`,{description:`Build before running. Default: true (use --no-build to skip when bundles already exist).`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print resolved entry/outdir + per-step timing.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forBuild({}).catch(()=>({}))).test??{},C=vn(n,t.entry??S.entry??`src/test.mts`),N=vn(n,t.outdir??S.outdir??`dist`);if(!existsSync(C))return ge.error(`[gjsify test] no test entry at ${Sn(n,C)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1);let F=t.runtime===`gjs`||t.runtime===`node`,I=t.runtime===`gjs`?[`gjs`]:t.runtime===`node`?[`node`]:S.runtimes&&S.runtimes.length>0?S.runtimes:[`gjs`,`node`],H=F?I:I.filter(t=>isRuntimeAvailable(t));for(let t of I.filter(t=>!H.includes(t)))ge.log(`[gjsify test] skipping ${t} — no \`${N_[t].probe}\` on PATH (not requested explicitly)`);if(H.length===0)return ge.error(`[gjsify test] none of the default runtimes (${I.join(`, `)}) is available on this host.\n Install one, or pin the set: \`gjsify test --runtime <rt>\` / \`gjsify.test.runtimes\` in package.json.`),process.exit(1);let W=[];for(let S of H){let F=xn(N,`test.${S}.mjs`);if(t.build!==!1)if(t.rebuild||!isFresh(F,C,n,N)){let N=Date.now();t.verbose&&ge.log(`[gjsify test] building → ${Sn(n,F)} (—app ${S})`);try{await buildTestBundle(C,F,S,t.verbose),t.verbose&&ge.log(`[gjsify test] built ${S} in ${Date.now()-N}ms`)}catch(t){ge.error(`[gjsify test] build failed for ${S}:`,t.message),W.push({runtime:S,ok:!1,durationMs:0,error:`build failed`});continue}}else t.verbose&&ge.log(`[gjsify test] ${S}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(F)){ge.error(`[gjsify test] --no-build but ${Sn(n,F)} doesn't exist. Build first or drop --no-build.`),W.push({runtime:S,ok:!1,durationMs:0,error:`no bundle`});continue}let I=Date.now();try{await runTestBundle(F,S),W.push({runtime:S,ok:!0,durationMs:Date.now()-I})}catch(t){W.push({runtime:S,ok:!1,durationMs:Date.now()-I,error:t.message})}}let q=W.map(t=>`${t.ok?`✅`:`❌`} ${t.runtime} (${t.durationMs}ms)${t.error?` — ${t.error}`:``}`).join(` `);if(ge.log(`[gjsify test] ${q}`),W.some(t=>!t.ok))return process.exit(1);process.exit(0)}}});function readPackageJson$1(t){if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return JSON.parse(n)}catch(n){throw Error(`gjsify install: ${t} is not valid JSON: ${n.message}`)}}function writePackageJson(t,n){let S=sortKnownDepFields(n);writeFileSync(t,JSON.stringify(S,null,2)+`
|
|
905
|
-
`,`utf-8`)}function parseSpec$2(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return{name:t};let S=t.indexOf(`@`,n+1);return S===-1?{name:t}:{name:t.slice(0,S),range:t.slice(S+1)}}let n=t.indexOf(`@`);return n===-1?{name:t}:{name:t.slice(0,n),range:t.slice(n+1)}}function projectSpecsFromPackageJson(t){let n=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=t[S];if(C)for(let[t,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||n.push(`${t}@${S}`))}return n}function addDependencyEntry(t,n,S,C){t[C]===void 0&&(t[C]={}),t[C][n]=S}function defaultRangeFromVersion(t){return`^${t}`}function sortKnownDepFields(t){let n={...t};for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=n[t];S&&(n[t]=Object.fromEntries(Object.entries(S).sort(([t],[n])=>t<n?-1:+(t>n))))}return n}var EI=__esmMin(()=>{Md(),__name$1(readPackageJson$1,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function scriptCacheEnabled(){let t=process.env.GJSIFY_NODE_SCRIPT_CACHE;return t===`1`||t===`true`||t===`yes`}async function runNodeScript(t,n=[],S){let C=vn(t);if(!existsSync(C)||!statSync(C).isFile())return ge.error(`gjsify run --node-script: no such file: ${C}`),process.exit(1);let N=hostRuntime$1();if(N!==`gjs`){await runRuntimeBundle(N,C,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0});return}let{BuildAction:F}=await Promise.resolve().then(()=>(GF(),HF)),{globals:I,excludeGlobals:H}=await new Config().forNodeScript(C),W;try{W=await F.bundleFileForGjsCached(C,{cacheSubdir:`node-scripts`,label:Tn(C),cache:scriptCacheEnabled(),preserveDefaultExport:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(C).href)},globals:I,excludeGlobals:H,resolveFromToolchain:!0})}catch(t){throw Error(`gjsify run --node-script: failed to bundle ${C} for GJS. The script must import only what gjsify can provide under GJS (node: builtins, workspace packages, pure-JS npm deps). (${t.message})`)}await runGjsBundle(W,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0})}var DI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),JF(),vI(),bI()});function gjsifyCacheRoot(t,n){let S=process.env.XDG_CACHE_HOME;return xn(S&&S.length>0?S:xn(homedir(),`.cache`),`gjsify`,t,n)}function atomicWrite(t,n){try{atomicWriteStrict(t,n)}catch{}}function atomicWriteStrict(t,n){mkdirSync(xn(t,`..`),{recursive:!0});let S=`${t}.tmp.${process.pid}`;writeFileSync(S,n),renameSync(S,t)}function readCacheFile(t){if(!existsSync(t))return null;try{let n=readFileSync(t);return n.length===0?null:n}catch{return null}}var OI=__esmMin(()=>{Md(),Dg(),jn()});function makeProgressReporter(t={}){if(t.enabled===!1)return AI;let n=t.stream??process.stderr,S=!!n.isTTY;return t.enabled??!0?S?makeTtyReporter(n):makePlainReporter(n):AI}function makeTtyReporter(t){let n=0,S=``;function render(C,N=!1){let F=Date.now();!N&&F-n<33&&C===S||(n=F,S=C,t.write(`\r\x1B[2K`+C))}function clearLine(){t.write(`\r\x1B[2K`),S=``}return{beginPhase(n,S){render(formatBar(n,0,S,void 0,t.columns??80),!0)},update(n){render(formatBar(n.phase,n.current,n.total,n.name,t.columns??80))},endPhase(n){let S=kI[n];clearLine(),t.write(`gjsify install: ${S} done\n`)}}}function makePlainReporter(t){let n=0,S=0;return{beginPhase(C,N){n=Date.now(),S=0,t.write(`gjsify install: ${kI[C]} ${N} package(s)\n`)},update(C){let N=Date.now();if(N-n<jI||C.current<=S)return;n=N,S=C.current;let F=C.total>0?Math.round(C.current/C.total*100):0;t.write(`gjsify install: ${kI[C.phase]} ${C.current}/${C.total} (${F}%)\n`)},endPhase(n){t.write(`gjsify install: ${kI[n]} done\n`)}}}function formatBar(t,n,S,C,N){let F=kI[t],I=S>0?Math.min(1,n/S):0,H=`${n}/${S}`,W=`gjsify install: ${F} `,q=` ${H}`+(C?` ${C}`:``),Y=Math.max(8,Math.min(40,N-W.length-q.length-4)),X=Math.round(I*Y),Z=`█`.repeat(X)+`░`.repeat(Y-X),te=`${W}[${Z}]${q}`;if(te.length>N){let t=te.length-N+1,n=C&&C.length>t?C.slice(0,C.length-t-1)+`…`:``;te=`${W}[${Z}] ${H}${n?` `+n:``}`}return te}var kI,AI,jI,MI=__esmMin(()=>{kI={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},AI={update(){},beginPhase(){},endPhase(){}},jI=5e3});function parseTar(t){let n=[],S=null,C=null,N=null,F=0;for(;F+512<=t.length;){let I=t.subarray(F,F+512);if(allZeros(I)){let n=t.subarray(F+512,F+2*512);if(n.length===512&&allZeros(n))break;F+=512;continue}if(!validateChecksum(I))throw new TarParseError(`Bad header checksum at offset ${F} — file is not a valid tar archive`);let H=readString(I,0,100),W=parseOctal(I,100,8),q=parseOctal(I,124,12),Y=parseOctal(I,136,12),X=String.fromCharCode(I[156]||0),Z=readString(I,157,100),te=readString(I,257,6),ne=readString(I,345,155),re=readString(I,265,32),ie=readString(I,297,32);F+=512;let ae=t.subarray(F,F+q);if(F+=alignToBlock(q),X===`x`){S=parsePaxRecords(ae);continue}if(X===`g`)continue;if(X===`L`){C=bytesToString(ae).replace(/\0+$/,``);continue}if(X===`K`){N=bytesToString(ae).replace(/\0+$/,``);continue}let oe=H;te===`ustar`&&ne!==``&&(oe=`${ne}/${H}`),C!==null&&(oe=C,C=null);let Q=Z;if(N!==null&&(Q=N,N=null),S!==null){let C=S.get(`path`);C!==void 0&&(oe=C);let N=S.get(`linkpath`);N!==void 0&&(Q=N);let I=S.get(`size`);if(I!==void 0){let C=Number(I);if(Number.isFinite(C)){let N=F-alignToBlock(q),I=t.subarray(N,N+C);F=N+alignToBlock(C),S=null,n.push(buildEntry(oe,Q,X,W,Y,re,ie,I));continue}}S=null}n.push(buildEntry(oe,Q,X,W,Y,re,ie,ae))}return n}function buildEntry(t,n,S,C,N,F,I,H){return{name:t,linkname:n,type:typeflagToType(S,t),mode:C,mtime:N,body:H,uname:F,gname:I}}function typeflagToType(t,n){switch(t){case`0`:case`\0`:case``:return n.endsWith(`/`)?`directory`:`file`;case`1`:return`hardlink`;case`2`:return`symlink`;case`5`:return`directory`;case`x`:return`pax-header`;case`g`:return`pax-global`;case`L`:return`gnu-longname`;case`K`:return`gnu-longlink`;default:return`unknown`}}function parsePaxRecords(t){let n=new Map,S=0;for(;S<t.length;){let C=S;for(;C<t.length&&t[C]!==32;)C++;if(C>=t.length)break;let N=bytesToString(t.subarray(S,C)),F=Number(N);if(!Number.isFinite(F)||F<=0)break;let I=S+F;if(I>t.length)break;let H=bytesToString(t.subarray(C+1,I-1)),W=H.indexOf(`=`);if(W>0){let t=H.slice(0,W),S=H.slice(W+1);n.set(t,S)}S=I}return n}function readString(t,n,S){let C=n,N=n+S;for(;C<N&&t[C]!==0;)C++;return bytesToString(t.subarray(n,C))}function bytesToString(t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(t)}function parseOctal(t,n,S){if(S>0&&t[n]&128){let C=t[n]&127;for(let N=1;N<S;N++)C=C*256+t[n+N];return C}let C=``;for(let N=0;N<S;N++){let S=t[n+N];S===0||S===32||(C+=String.fromCharCode(S))}return C===``?0:parseInt(C,8)}function alignToBlock(t){return Math.ceil(t/512)*512}function allZeros(t){for(let n=0;n<t.length;n++)if(t[n]!==0)return!1;return!0}function validateChecksum(t){let n=parseOctal(t,148,8),S=0,C=0;for(let n=0;n<512;n++){let N=n>=148&&n<156?32:t[n];S+=N,C+=N>127?N-256:N}return n===S||n===C}var TarParseError,NI=__esmMin(()=>{TarParseError=class extends Error{constructor(t){super(t),this.name=`TarParseError`}}});function createTarball(t){let n=[];for(let S of t){if(`directory`in S&&S.directory===!0){n.push(buildHeader$1(ensureTrailingSlash(S.name),0,`5`,S.mode??493,S.mtime??0));continue}let t=S,C=typeof t.body==`string`?new TextEncoder().encode(t.body):t.body,N=t.mode??defaultFileMode(C);n.push(buildHeader$1(t.name,C.byteLength,`0`,N,t.mtime??0)),n.push(C);let F=padTo512(C.byteLength);F>0&&n.push(new Uint8Array(F))}return n.push(new Uint8Array(512*2)),concatChunks(n)}function buildHeader$1(t,n,S,C,N){let{prefix:F,basename:I}=splitPathForUstar(t),H=new Uint8Array(512);writeAscii(H,I,0,100),writeOctal(H,C&4095,100,7),H[107]=0,writeOctal(H,0,108,7),H[115]=0,writeOctal(H,0,116,7),H[123]=0,writeOctal(H,n,124,11),H[135]=0,writeOctal(H,N,136,11),H[147]=0;for(let t=148;t<156;t++)H[t]=32;H[156]=S.charCodeAt(0),writeAscii(H,`ustar\0`,257,6),writeAscii(H,`00`,263,2),F&&writeAscii(H,F,345,155);let W=0;for(let t=0;t<512;t++)W+=H[t];return writeAscii(H,W.toString(8).padStart(6,`0`),148,6),H[154]=0,H[155]=32,H}function splitPathForUstar(t){if(t.length<=100)return{prefix:``,basename:t};if(t.length>255)throw Error(`createTarball: path too long (${t.length} > 255 chars): ${t}`);for(let n=Math.min(t.length-1,155);n>0;n--)if(t[n]===`/`&&t.length-n-1<=100)return{prefix:t.slice(0,n),basename:t.slice(n+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${t}`)}function writeAscii(t,n,S,C){let N=new TextEncoder().encode(n);if(N.length>C)throw Error(`createTarball: field too long (${N.length} > ${C}): "${n}"`);t.set(N,S)}function writeOctal(t,n,S,C){writeAscii(t,n.toString(8).padStart(C,`0`),S,C)}function padTo512(t){let n=t%512;return n===0?0:512-n}function ensureTrailingSlash(t){return t.endsWith(`/`)?t:`${t}/`}function defaultFileMode(t){return t.length>=2&&t[0]===35&&t[1]===33?493:420}function concatChunks(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}var PI=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(t,n,S={}){let C=t instanceof Uint8Array?t:new Uint8Array(t),N=parseTar(S.gzip??(C.length>=2&&C[0]===31&&C[1]===139)?await gunzip(C):C);mkdirSync(n,{recursive:!0});let F=S.strip??1,I=S.preventEscape??!0,H={files:[],directories:[],symlinks:[],skipped:0};for(let t of N){let C=stripComponents(t.name,F);if(C===null||C===``){H.skipped++;continue}let N=vn(n,C);if(I&&!isInside$2(N,n))throw Error(`tar: refusing to extract ${t.name} outside ${n} (resolved=${N})`);if(S.filter&&!S.filter(t,N)){H.skipped++;continue}if(t.type===`directory`){mkdirSync(N,{recursive:!0}),H.directories.push(N);continue}if(t.type===`file`){mkdirSync(wn(N),{recursive:!0}),writeFileSync(N,t.body);let n=S.chmod?.(t,N)??t.mode&511;if(n>0)try{chmodSync(N,n)}catch{}H.files.push(N);continue}if(t.type===`symlink`){mkdirSync(wn(N),{recursive:!0});try{symlinkSync(t.linkname,N),H.symlinks.push(N)}catch{writeFileSync(N,t.linkname),H.files.push(N)}continue}H.skipped++}return H}async function gunzip(t){let n=globalThis.DecompressionStream;if(typeof n!=`function`)throw Error(`@gjsify/tar: globalThis.DecompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(t)]).stream().pipeThrough(new n(`gzip`)))}async function gzip(t,n){if(n?.level!==void 0){let{gzipSync:S}=await Promise.resolve().then(()=>(ia(),ea));return new Uint8Array(S(t,{level:n.level}))}let S=globalThis.CompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.CompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(t)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(t){let n=[],S=0,C=t.getReader();for(;;){let{value:t,done:N}=await C.read();if(N)break;let F=t instanceof Uint8Array?t:new Uint8Array(t);n.push(F),S+=F.length}let N=new Uint8Array(S),F=0;for(let t of n)N.set(t,F),F+=t.length;return N}function stripComponents(t,n){if(n<=0)return t;let S=t.split(`/`).filter(t=>t!==``);return S.length<=n?null:S.slice(n).join(`/`)}function isInside$2(t,n){let S=Sn(n,t);return S!==``&&!S.startsWith(`..`)&&!bn(S)}var FI=__esmMin(()=>{NI(),Md(),jn(),__name$1(isInside$2,`isInside`)}),II=__exportAll$5({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),LI=__esmMin(()=>{NI(),PI(),FI()});function isPidAlive(t){if(existsSync(`/proc/self`))return existsSync(`/proc/${t}`);try{return process.kill(t,0),!0}catch(t){return t.code!==`ESRCH`}}function parsePsPidPpid(t){let n=new Map;for(let S of t.split(`
|
|
906
|
-
`)){let t=/^\s*(\d+)\s+(\d+)\s*$/.exec(S);if(!t)continue;let C=Number(t[1]),N=Number(t[2]);if(C<=0||N<=0||C===N)continue;let F=n.get(N);F?F.push(C):n.set(N,[C])}return n}function readProcChildren(t){let n;try{n=readdirSync(`/proc/${t}/task`)}catch{return null}let S=[],C=!1;for(let N of n)try{let n=readFileSync(`/proc/${t}/task/${N}/children`,`utf-8`);C=!0;for(let t of n.trim().split(/\s+/)){let n=Number(t);Number.isInteger(n)&&n>0&&S.push(n)}}catch{}return C?S:null}function procPpidMap(){let t=new Map,n=[];try{n=readdirSync(`/proc`)}catch{return t}for(let S of n){let n=Number(S);if(!(!Number.isInteger(n)||n<=0))try{let S=readFileSync(`/proc/${n}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=t.get(N);F?F.push(n):t.set(N,[n])}catch{}}return t}function osPpidMap(){let[t,n]=process.platform===`win32`?[`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }`]]:[`ps`,[`-A`,`-o`,`pid=,ppid=`]];try{let S=spawnSync(t,n,{encoding:`utf-8`});return S.status!==0||typeof S.stdout!=`string`?new Map:parsePsPidPpid(S.stdout)}catch{return new Map}}function collectDescendants(t){let n=[],S=new Set([t]),C=[t],N=null;for(;C.length>0;){let t=C.shift(),F=N?null:readProcChildren(t);F===null&&(N||(N=procPpidMap(),N.size===0&&(N=osPpidMap())),F=N.get(t)??[]);for(let t of F)S.has(t)||(S.add(t),n.push(t),C.push(t))}return n}var
|
|
907
|
-
`)}var
|
|
908
|
-
`);let N=n.verbose?S.entries:S.entries.slice(0,
|
|
909
|
-
`)}function automaticPruneRefusal(t,n){return Object.keys(readPlatformOverrides(t)).length>0?`the platform target was overridden on the command line`:n?`--immutable`:null}function pruneAfterInstall(t,n,S={}){try{if(automaticPruneRefusal(S.env??process.env,S.immutable??!1))return;let C=planPrune({prefix:t,target:n});if(C.entries.length===0)return;let N=executePrune(C);if(N.removed.length===0)return;let F=S.hint?` (${S.hint} to review)`:``;ge.log(`gjsify: pruned ${N.removed.length} package(s) this host cannot use, freeing ${humanBytes(N.bytes)}${F}`)}catch(t){process.env.GJSIFY_DEBUG&&ge.error(`gjsify: prune skipped — ${t.message}`)}}var
|
|
904
|
+
"dependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:I,envPrefix:H}=computeNativeEnvForBundle(F,N),W={...process.env,...I},[,q]=N_[t].launch(F,S),Y=t===`node`?nodeBinary():N_[t].probe,X=[Y,...q.map(t=>t.includes(` `)?`"${t}"`:t)].join(` `);C.quiet||ge.error(`$ ${H?`${H} `:``}${X}`);let failed=t=>(process.exitCode=t,process.exit(t)),Z;try{Z=await spawnToCompletion(Y,q,{completion:C.completion,env:W})}catch(t){return ge.error(t.message),failed(1)}if(Z.code!==0)return C.quietExit||ge.error(`${t} exited with ${describeExit(Z)}`),failed(Z.code??1);if(C.exitOnSuccess)return process.exit(0)}var xI=__esmMin(()=>{_e(),Md(),jn(),t_(),yI(),P_(),j_()});function nearestNodeModules(t){let n=vn(t);for(;;){let t=xn(n,`node_modules`);if(existsSync(t))return t;let S=wn(n);if(S===n)return null;n=S}}async function rebuildForGjs(t,n,S){let C=t.nodeModules??nearestNodeModules(process.cwd())??xn(t.pkgDir,`node_modules`),N=findProjectLockfile(wn(C)),F=execCacheKey({pkgName:t.pkgName,pkgVersion:t.pkgVersion,entry:entryWithinPackage(t,n),cliVersion:cliVersion(),lockfileHash:N?hashFile(N):null}),I=execArtifactPath(execCacheRoot(C),t,n,t.installed?F:`local`),H=t.installed&&!S.rebuild;if(H&&existsSync(I))return S.verbose&&ge.error(`gjsify exec: reusing ${I}`),I;ge.error(`gjsify exec: rebuilding ${t.pkgName}@${t.pkgVersion} "${t.binName}" for GJS…`);let W=wn(I),q=`${W}.tmp-${process.pid.toString(16)}-${Date.now().toString(16)}`,Y=xn(q,Tn(I));try{let{BuildAction:C}=await Promise.resolve().then(()=>(KF(),UF));await C.bundleFileForGjs(n,Y,{verbose:S.verbose,preserveDefaultExport:!1,...t.installed?{}:{define:{"import.meta.url":JSON.stringify(pathToFileURL(n).href)}},toolchainAnchor:C.runningCliFile(),...S.verbose?{}:{logLevel:`silent`}})}catch(C){throw rmSync(q,{recursive:!0,force:!0}),new ExecRebuildError(t,n,C,S.verbose)}if(H&&existsSync(I))return rmSync(q,{recursive:!0,force:!0}),I;rmSync(W,{recursive:!0,force:!0});try{renameSync(q,W)}catch(t){if(rmSync(q,{recursive:!0,force:!0}),!existsSync(I))throw t}return pruneStaleArtifacts(wn(W),t,Tn(W)),I}function pruneStaleArtifacts(t,n,S){let C=`${n.pkgName}@${n.pkgVersion}`.replace(/[^a-zA-Z0-9._@-]/g,`_`),N;try{N=readdirSync(t)}catch{return}for(let n of N)n===S||!n.startsWith(`${C}-`)||n.includes(`.tmp-`)||rmSync(xn(t,n),{recursive:!0,force:!0})}var ExecRebuildError,SI,CI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),rI(),mI(),Xm(),yI(),xI(),ExecRebuildError=class extends Error{constructor(t,n,S,C){let N=S instanceof Error?S.message:String(S);super(`gjsify exec: rebuilding "${t.binName}" (${t.pkgName}@${t.pkgVersion}) for GJS failed.\n entry: ${n}\nNothing was run — gjsify exec never falls back to another runtime on its own. To run it on Node explicitly: \`gjsify exec --runtime node ${t.binName}\`.\n`+(C?``:`Re-run with \`gjsify exec --verbose ${t.binName}\` for the bundler's warnings.\n`)+`Bundler diagnostics:\n${N}`,{cause:S}),this.name=`ExecRebuildError`}},SI={command:`exec <entries..>`,description:"Run an installed npm bin on the runtime gjsify runs on: `gjsify exec [--runtime gjs|node|bun|deno] [--rebuild] [--verbose] <bin> [args…]`. On Node/Bun/Deno the bin runs unchanged; on GJS it is rebuilt `--app gjs` once, cached under node_modules/.cache/gjsify/exec/, and run with gjs. Options go BEFORE the bin; everything after it is the bin's own.",builder:t=>t.positional(`entries`,{description:`gjsify exec options, then the bin name and its arguments.`,type:`string`,array:!0}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n,S,C;try{n=splitExecArgv(t.entries??[],doubleDashArgs(t)),S=resolveExecBin(n.bin,process.cwd()),C=planExec(S,n.runtime??hostRuntime$1())}catch(t){if(t instanceof ExecBinNotFoundError)return ge.error(t.message),process.exit(127);if(t instanceof ExecPlanError)return ge.error(t.message),process.exit(1);throw t}let N={completion:`exit`,exitOnSuccess:!0,quiet:!n.verbose,quietExit:!0};if(C.kind===`direct`){await runRuntimeBundle(C.runtime,C.file,n.args,N);return}if(C.kind===`gjs-bundle`){await runGjsBundle(C.file,n.args,N);return}let F=await rebuildForGjs(S,C.entry,{rebuild:n.rebuild,verbose:n.verbose}),I=cliPackageDir();await runGjsBundle(F,n.args,{...N,nativeRoots:I?[I]:[]})}}});function bundleInputsPath(t){return`${t}.inputs.json`}function idToPath(t){if(t===``||t.startsWith(`\0`))return null;let n=t.search(/[?#]/);if(n===-1)return t;let S=t.slice(0,n);return isFile(S)?S:t}function isFile(t){try{return statSync(t).isFile()}catch{return!1}}function isToolchainScratch(t){return t.includes(`${On}node_modules${On}.cache${On}`)}function resolutionFilesFor(t){let n=[];for(let S=wn(t);;S=wn(S)){let t=xn(S,`package.json`);if(existsSync(t)){n.push(t);let C=xn(S,`tsconfig.json`);return existsSync(C)&&n.push(C),n}if(wn(S)===S)return n}}function createBundleInputsRecorder(t){let n=new Set,S=!0,record=t=>{let S=idToPath(t);S!==null&&n.add(S)},C={name:`gjsify:bundle-inputs`,transform(t,n){record(n)}},inputs=()=>{let t=[],S=new Set;for(let C of n){let n;try{n=statSync(C).isFile()}catch{continue}if(!n||isToolchainScratch(C))continue;t.push(C);let N=wn(C);if(!S.has(N)){S.add(N);for(let n of resolutionFilesFor(C))t.push(n)}}return[...new Set(t)].sort()};return{plugin:C,addWatchFiles(t){t.reportedByEngine||(S=!1);for(let n of t.files)record(n)},inputs,write(){let n=bundleInputsPath(t),C={version:2,inputs:inputs(),watchList:S},N=`${n}.tmp`;try{mkdirSync(wn(n),{recursive:!0}),writeFileSync(N,`${JSON.stringify(C,null,2)}\n`,`utf-8`),renameSync(N,n)}catch(t){try{rmSync(N,{force:!0})}catch{}ge.warn(`[gjsify test] could not record the build inputs beside ${n} (${t.message}) — the next run judges freshness by the package walk alone, which cannot see outside this package.`)}}}}function readBundleInputs(t){let n;try{n=JSON.parse(readFileSync(bundleInputsPath(t),`utf-8`))}catch{return null}return n?.version!==2||!Array.isArray(n.inputs)?null:{inputs:n.inputs.filter(t=>typeof t==`string`),watchList:n.watchList===!0}}function newestBundleInputMtimeMs(t){let n=0;for(let S of t)try{let{mtimeMs:t}=statSync(S);t>n&&(n=t)}catch{return 1/0}return n}var wI=__esmMin(()=>{_e(),Md(),jn()});async function buildTestBundle(t,n,S,C){let N=await new Config().forBuild({entryPoints:[t],outfile:n,app:S,verbose:C??!1,logLevel:`warning`,exclude:[]});N.library={...N.library};let F=createBundleInputsRecorder(n);N.bundler={...N.bundler,input:[t],output:{...N.bundler?.output,file:n},plugins:[...N.bundler?.plugins??[],F.plugin]},await new GF(N).start({app:S,library:!1,onWatchFiles:t=>F.addWatchFiles(t)}),F.write()}async function runTestBundle(t,n){if(n===`gjs`){await runGjsBundle(t,[],{completion:`exit`});return}let S=await spawnToCompletion(nodeBinary(),[t],{completion:`exit`});if(S.code!==0)throw Error(`node exited with ${describeExit(S)}`)}function isFresh(t,n,S,C){if(!existsSync(t))return!1;try{let N=statSync(t).mtimeMs,F=[],I=Sn(S,C).split(On).join(`/`);I!==``&&!I.startsWith(`../`)&&F.push(I);let H=readBundleInputs(t);return H!==null&&!H.watchList?!1:N>=Math.max(newestInputMtimeMs(packageBuildInputs(S,{extraOutputs:F})),H===null?0:newestBundleInputMtimeMs(H.inputs),statSync(n).mtimeMs,newestDepSignalMtimeMs(S))}catch{return!1}}var TI,EI=__esmMin(()=>{_e(),Md(),jn(),wI(),HF(),P_(),xI(),j_(),YF(),KF(),yI(),TI={command:`test`,description:"Build + run the package’s `src/test.mts` suite on GJS and Node and aggregate the results. Replaces the per-package `build:test:{gjs,node}` + `test:{gjs,node}` script boilerplate.",builder:t=>t.option(`runtime`,{description:`Target runtime. Default: both.`,type:`string`,choices:[`gjs`,`node`,`all`],default:`all`}).option(`entry`,{description:"Path to the test entry. Default: `src/test.mts` (or `gjsify.test.entry`).",type:`string`,normalize:!0}).option(`outdir`,{description:"Output directory for the built test bundles. Default: `dist/`.",type:`string`,normalize:!0}).option(`rebuild`,{description:`Always rebuild the test bundles, even when they look up-to-date.`,type:`boolean`,default:!1}).option(`build`,{description:`Build before running. Default: true (use --no-build to skip when bundles already exist).`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print resolved entry/outdir + per-step timing.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forBuild({}).catch(()=>({}))).test??{},C=vn(n,t.entry??S.entry??`src/test.mts`),N=vn(n,t.outdir??S.outdir??`dist`);if(!existsSync(C))return ge.error(`[gjsify test] no test entry at ${Sn(n,C)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1);let F=t.runtime===`gjs`||t.runtime===`node`,I=t.runtime===`gjs`?[`gjs`]:t.runtime===`node`?[`node`]:S.runtimes&&S.runtimes.length>0?S.runtimes:[`gjs`,`node`],H=F?I:I.filter(t=>isRuntimeAvailable(t));for(let t of I.filter(t=>!H.includes(t)))ge.log(`[gjsify test] skipping ${t} — no \`${N_[t].probe}\` on PATH (not requested explicitly)`);if(H.length===0)return ge.error(`[gjsify test] none of the default runtimes (${I.join(`, `)}) is available on this host.\n Install one, or pin the set: \`gjsify test --runtime <rt>\` / \`gjsify.test.runtimes\` in package.json.`),process.exit(1);let W=[];for(let S of H){let F=xn(N,`test.${S}.mjs`);if(t.build!==!1)if(t.rebuild||!isFresh(F,C,n,N)){let N=Date.now();t.verbose&&ge.log(`[gjsify test] building → ${Sn(n,F)} (—app ${S})`);try{await buildTestBundle(C,F,S,t.verbose),t.verbose&&ge.log(`[gjsify test] built ${S} in ${Date.now()-N}ms`)}catch(t){ge.error(`[gjsify test] build failed for ${S}:`,t.message),W.push({runtime:S,ok:!1,durationMs:0,error:`build failed`});continue}}else t.verbose&&ge.log(`[gjsify test] ${S}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(F)){ge.error(`[gjsify test] --no-build but ${Sn(n,F)} doesn't exist. Build first or drop --no-build.`),W.push({runtime:S,ok:!1,durationMs:0,error:`no bundle`});continue}let I=Date.now();try{await runTestBundle(F,S),W.push({runtime:S,ok:!0,durationMs:Date.now()-I})}catch(t){W.push({runtime:S,ok:!1,durationMs:Date.now()-I,error:t.message})}}let q=W.map(t=>`${t.ok?`✅`:`❌`} ${t.runtime} (${t.durationMs}ms)${t.error?` — ${t.error}`:``}`).join(` `);if(ge.log(`[gjsify test] ${q}`),W.some(t=>!t.ok))return process.exit(1);process.exit(0)}}});function readPackageJson$1(t){if(!existsSync(t))return null;let n=readFileSync(t,`utf-8`);try{return JSON.parse(n)}catch(n){throw Error(`gjsify install: ${t} is not valid JSON: ${n.message}`)}}function writePackageJson(t,n){let S=sortKnownDepFields(n);writeFileSync(t,JSON.stringify(S,null,2)+`
|
|
905
|
+
`,`utf-8`)}function parseSpec$2(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return{name:t};let S=t.indexOf(`@`,n+1);return S===-1?{name:t}:{name:t.slice(0,S),range:t.slice(S+1)}}let n=t.indexOf(`@`);return n===-1?{name:t}:{name:t.slice(0,n),range:t.slice(n+1)}}function projectSpecsFromPackageJson(t){let n=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=t[S];if(C)for(let[t,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||n.push(`${t}@${S}`))}return n}function addDependencyEntry(t,n,S,C){t[C]===void 0&&(t[C]={}),t[C][n]=S}function defaultRangeFromVersion(t){return`^${t}`}function sortKnownDepFields(t){let n={...t};for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=n[t];S&&(n[t]=Object.fromEntries(Object.entries(S).sort(([t],[n])=>t<n?-1:+(t>n))))}return n}var DI=__esmMin(()=>{Md(),__name$1(readPackageJson$1,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function scriptCacheEnabled(){let t=process.env.GJSIFY_NODE_SCRIPT_CACHE;return t===`1`||t===`true`||t===`yes`}async function runNodeScript(t,n=[],S){let C=vn(t);if(!existsSync(C)||!statSync(C).isFile())return ge.error(`gjsify run --node-script: no such file: ${C}`),process.exit(1);let N=hostRuntime$1();if(N!==`gjs`){await runRuntimeBundle(N,C,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0});return}let{BuildAction:F}=await Promise.resolve().then(()=>(KF(),UF)),{globals:I,excludeGlobals:H}=await new Config().forNodeScript(C),W;try{W=await F.bundleFileForGjsCached(C,{cacheSubdir:`node-scripts`,label:Tn(C),cache:scriptCacheEnabled(),preserveDefaultExport:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(C).href)},globals:I,excludeGlobals:H,resolveFromToolchain:!0})}catch(t){throw Error(`gjsify run --node-script: failed to bundle ${C} for GJS. The script must import only what gjsify can provide under GJS (node: builtins, workspace packages, pure-JS npm deps). (${t.message})`)}await runGjsBundle(W,n,{completion:S.completion,exitOnSuccess:S.exitOnSuccess,quiet:!0})}var OI=__esmMin(()=>{_e(),Md(),jn(),Hn(),t_(),YF(),yI(),xI()});function gjsifyCacheRoot(t,n){let S=process.env.XDG_CACHE_HOME;return xn(S&&S.length>0?S:xn(homedir(),`.cache`),`gjsify`,t,n)}function atomicWrite(t,n){try{atomicWriteStrict(t,n)}catch{}}function atomicWriteStrict(t,n){mkdirSync(xn(t,`..`),{recursive:!0});let S=`${t}.tmp.${process.pid}`;writeFileSync(S,n),renameSync(S,t)}function readCacheFile(t){if(!existsSync(t))return null;try{let n=readFileSync(t);return n.length===0?null:n}catch{return null}}var kI=__esmMin(()=>{Md(),Dg(),jn()});function makeProgressReporter(t={}){if(t.enabled===!1)return jI;let n=t.stream??process.stderr,S=!!n.isTTY;return t.enabled??!0?S?makeTtyReporter(n):makePlainReporter(n):jI}function makeTtyReporter(t){let n=0,S=``;function render(C,N=!1){let F=Date.now();!N&&F-n<33&&C===S||(n=F,S=C,t.write(`\r\x1B[2K`+C))}function clearLine(){t.write(`\r\x1B[2K`),S=``}return{beginPhase(n,S){render(formatBar(n,0,S,void 0,t.columns??80),!0)},update(n){render(formatBar(n.phase,n.current,n.total,n.name,t.columns??80))},endPhase(n){let S=AI[n];clearLine(),t.write(`gjsify install: ${S} done\n`)}}}function makePlainReporter(t){let n=0,S=0;return{beginPhase(C,N){n=Date.now(),S=0,t.write(`gjsify install: ${AI[C]} ${N} package(s)\n`)},update(C){let N=Date.now();if(N-n<MI||C.current<=S)return;n=N,S=C.current;let F=C.total>0?Math.round(C.current/C.total*100):0;t.write(`gjsify install: ${AI[C.phase]} ${C.current}/${C.total} (${F}%)\n`)},endPhase(n){t.write(`gjsify install: ${AI[n]} done\n`)}}}function formatBar(t,n,S,C,N){let F=AI[t],I=S>0?Math.min(1,n/S):0,H=`${n}/${S}`,W=`gjsify install: ${F} `,q=` ${H}`+(C?` ${C}`:``),Y=Math.max(8,Math.min(40,N-W.length-q.length-4)),X=Math.round(I*Y),Z=`█`.repeat(X)+`░`.repeat(Y-X),te=`${W}[${Z}]${q}`;if(te.length>N){let t=te.length-N+1,n=C&&C.length>t?C.slice(0,C.length-t-1)+`…`:``;te=`${W}[${Z}] ${H}${n?` `+n:``}`}return te}var AI,jI,MI,NI=__esmMin(()=>{AI={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},jI={update(){},beginPhase(){},endPhase(){}},MI=5e3});function parseTar(t){let n=[],S=null,C=null,N=null,F=0;for(;F+512<=t.length;){let I=t.subarray(F,F+512);if(allZeros(I)){let n=t.subarray(F+512,F+2*512);if(n.length===512&&allZeros(n))break;F+=512;continue}if(!validateChecksum(I))throw new TarParseError(`Bad header checksum at offset ${F} — file is not a valid tar archive`);let H=readString(I,0,100),W=parseOctal(I,100,8),q=parseOctal(I,124,12),Y=parseOctal(I,136,12),X=String.fromCharCode(I[156]||0),Z=readString(I,157,100),te=readString(I,257,6),ne=readString(I,345,155),re=readString(I,265,32),ie=readString(I,297,32);F+=512;let ae=t.subarray(F,F+q);if(F+=alignToBlock(q),X===`x`){S=parsePaxRecords(ae);continue}if(X===`g`)continue;if(X===`L`){C=bytesToString(ae).replace(/\0+$/,``);continue}if(X===`K`){N=bytesToString(ae).replace(/\0+$/,``);continue}let oe=H;te===`ustar`&&ne!==``&&(oe=`${ne}/${H}`),C!==null&&(oe=C,C=null);let Q=Z;if(N!==null&&(Q=N,N=null),S!==null){let C=S.get(`path`);C!==void 0&&(oe=C);let N=S.get(`linkpath`);N!==void 0&&(Q=N);let I=S.get(`size`);if(I!==void 0){let C=Number(I);if(Number.isFinite(C)){let N=F-alignToBlock(q),I=t.subarray(N,N+C);F=N+alignToBlock(C),S=null,n.push(buildEntry(oe,Q,X,W,Y,re,ie,I));continue}}S=null}n.push(buildEntry(oe,Q,X,W,Y,re,ie,ae))}return n}function buildEntry(t,n,S,C,N,F,I,H){return{name:t,linkname:n,type:typeflagToType(S,t),mode:C,mtime:N,body:H,uname:F,gname:I}}function typeflagToType(t,n){switch(t){case`0`:case`\0`:case``:return n.endsWith(`/`)?`directory`:`file`;case`1`:return`hardlink`;case`2`:return`symlink`;case`5`:return`directory`;case`x`:return`pax-header`;case`g`:return`pax-global`;case`L`:return`gnu-longname`;case`K`:return`gnu-longlink`;default:return`unknown`}}function parsePaxRecords(t){let n=new Map,S=0;for(;S<t.length;){let C=S;for(;C<t.length&&t[C]!==32;)C++;if(C>=t.length)break;let N=bytesToString(t.subarray(S,C)),F=Number(N);if(!Number.isFinite(F)||F<=0)break;let I=S+F;if(I>t.length)break;let H=bytesToString(t.subarray(C+1,I-1)),W=H.indexOf(`=`);if(W>0){let t=H.slice(0,W),S=H.slice(W+1);n.set(t,S)}S=I}return n}function readString(t,n,S){let C=n,N=n+S;for(;C<N&&t[C]!==0;)C++;return bytesToString(t.subarray(n,C))}function bytesToString(t){return new TextDecoder(`utf-8`,{fatal:!1}).decode(t)}function parseOctal(t,n,S){if(S>0&&t[n]&128){let C=t[n]&127;for(let N=1;N<S;N++)C=C*256+t[n+N];return C}let C=``;for(let N=0;N<S;N++){let S=t[n+N];S===0||S===32||(C+=String.fromCharCode(S))}return C===``?0:parseInt(C,8)}function alignToBlock(t){return Math.ceil(t/512)*512}function allZeros(t){for(let n=0;n<t.length;n++)if(t[n]!==0)return!1;return!0}function validateChecksum(t){let n=parseOctal(t,148,8),S=0,C=0;for(let n=0;n<512;n++){let N=n>=148&&n<156?32:t[n];S+=N,C+=N>127?N-256:N}return n===S||n===C}var TarParseError,PI=__esmMin(()=>{TarParseError=class extends Error{constructor(t){super(t),this.name=`TarParseError`}}});function createTarball(t){let n=[];for(let S of t){if(`directory`in S&&S.directory===!0){n.push(buildHeader$1(ensureTrailingSlash(S.name),0,`5`,S.mode??493,S.mtime??0));continue}let t=S,C=typeof t.body==`string`?new TextEncoder().encode(t.body):t.body,N=t.mode??defaultFileMode(C);n.push(buildHeader$1(t.name,C.byteLength,`0`,N,t.mtime??0)),n.push(C);let F=padTo512(C.byteLength);F>0&&n.push(new Uint8Array(F))}return n.push(new Uint8Array(512*2)),concatChunks(n)}function buildHeader$1(t,n,S,C,N){let{prefix:F,basename:I}=splitPathForUstar(t),H=new Uint8Array(512);writeAscii(H,I,0,100),writeOctal(H,C&4095,100,7),H[107]=0,writeOctal(H,0,108,7),H[115]=0,writeOctal(H,0,116,7),H[123]=0,writeOctal(H,n,124,11),H[135]=0,writeOctal(H,N,136,11),H[147]=0;for(let t=148;t<156;t++)H[t]=32;H[156]=S.charCodeAt(0),writeAscii(H,`ustar\0`,257,6),writeAscii(H,`00`,263,2),F&&writeAscii(H,F,345,155);let W=0;for(let t=0;t<512;t++)W+=H[t];return writeAscii(H,W.toString(8).padStart(6,`0`),148,6),H[154]=0,H[155]=32,H}function splitPathForUstar(t){if(t.length<=100)return{prefix:``,basename:t};if(t.length>255)throw Error(`createTarball: path too long (${t.length} > 255 chars): ${t}`);for(let n=Math.min(t.length-1,155);n>0;n--)if(t[n]===`/`&&t.length-n-1<=100)return{prefix:t.slice(0,n),basename:t.slice(n+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${t}`)}function writeAscii(t,n,S,C){let N=new TextEncoder().encode(n);if(N.length>C)throw Error(`createTarball: field too long (${N.length} > ${C}): "${n}"`);t.set(N,S)}function writeOctal(t,n,S,C){writeAscii(t,n.toString(8).padStart(C,`0`),S,C)}function padTo512(t){let n=t%512;return n===0?0:512-n}function ensureTrailingSlash(t){return t.endsWith(`/`)?t:`${t}/`}function defaultFileMode(t){return t.length>=2&&t[0]===35&&t[1]===33?493:420}function concatChunks(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}var FI=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(t,n,S={}){let C=t instanceof Uint8Array?t:new Uint8Array(t),N=parseTar(S.gzip??(C.length>=2&&C[0]===31&&C[1]===139)?await gunzip(C):C);mkdirSync(n,{recursive:!0});let F=S.strip??1,I=S.preventEscape??!0,H={files:[],directories:[],symlinks:[],skipped:0};for(let t of N){let C=stripComponents(t.name,F);if(C===null||C===``){H.skipped++;continue}let N=vn(n,C);if(I&&!isInside$2(N,n))throw Error(`tar: refusing to extract ${t.name} outside ${n} (resolved=${N})`);if(S.filter&&!S.filter(t,N)){H.skipped++;continue}if(t.type===`directory`){mkdirSync(N,{recursive:!0}),H.directories.push(N);continue}if(t.type===`file`){mkdirSync(wn(N),{recursive:!0}),writeFileSync(N,t.body);let n=S.chmod?.(t,N)??t.mode&511;if(n>0)try{chmodSync(N,n)}catch{}H.files.push(N);continue}if(t.type===`symlink`){mkdirSync(wn(N),{recursive:!0});try{symlinkSync(t.linkname,N),H.symlinks.push(N)}catch{writeFileSync(N,t.linkname),H.files.push(N)}continue}H.skipped++}return H}async function gunzip(t){let n=globalThis.DecompressionStream;if(typeof n!=`function`)throw Error(`@gjsify/tar: globalThis.DecompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(t)]).stream().pipeThrough(new n(`gzip`)))}async function gzip(t,n){if(n?.level!==void 0){let{gzipSync:S}=await Promise.resolve().then(()=>(ia(),ea));return new Uint8Array(S(t,{level:n.level}))}let S=globalThis.CompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.CompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(t)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(t){let n=[],S=0,C=t.getReader();for(;;){let{value:t,done:N}=await C.read();if(N)break;let F=t instanceof Uint8Array?t:new Uint8Array(t);n.push(F),S+=F.length}let N=new Uint8Array(S),F=0;for(let t of n)N.set(t,F),F+=t.length;return N}function stripComponents(t,n){if(n<=0)return t;let S=t.split(`/`).filter(t=>t!==``);return S.length<=n?null:S.slice(n).join(`/`)}function isInside$2(t,n){let S=Sn(n,t);return S!==``&&!S.startsWith(`..`)&&!bn(S)}var II=__esmMin(()=>{PI(),Md(),jn(),__name$1(isInside$2,`isInside`)}),LI=__exportAll$5({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),RI=__esmMin(()=>{PI(),FI(),II()});function isPidAlive(t){if(existsSync(`/proc/self`))return existsSync(`/proc/${t}`);try{return process.kill(t,0),!0}catch(t){return t.code!==`ESRCH`}}function parsePsPidPpid(t){let n=new Map;for(let S of t.split(`
|
|
906
|
+
`)){let t=/^\s*(\d+)\s+(\d+)\s*$/.exec(S);if(!t)continue;let C=Number(t[1]),N=Number(t[2]);if(C<=0||N<=0||C===N)continue;let F=n.get(N);F?F.push(C):n.set(N,[C])}return n}function readProcChildren(t){let n;try{n=readdirSync(`/proc/${t}/task`)}catch{return null}let S=[],C=!1;for(let N of n)try{let n=readFileSync(`/proc/${t}/task/${N}/children`,`utf-8`);C=!0;for(let t of n.trim().split(/\s+/)){let n=Number(t);Number.isInteger(n)&&n>0&&S.push(n)}}catch{}return C?S:null}function procPpidMap(){let t=new Map,n=[];try{n=readdirSync(`/proc`)}catch{return t}for(let S of n){let n=Number(S);if(!(!Number.isInteger(n)||n<=0))try{let S=readFileSync(`/proc/${n}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=t.get(N);F?F.push(n):t.set(N,[n])}catch{}}return t}function osPpidMap(){let[t,n]=process.platform===`win32`?[`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }`]]:[`ps`,[`-A`,`-o`,`pid=,ppid=`]];try{let S=spawnSync(t,n,{encoding:`utf-8`});return S.status!==0||typeof S.stdout!=`string`?new Map:parsePsPidPpid(S.stdout)}catch{return new Map}}function collectDescendants(t){let n=[],S=new Set([t]),C=[t],N=null;for(;C.length>0;){let t=C.shift(),F=N?null:readProcChildren(t);F===null&&(N||(N=procPpidMap(),N.size===0&&(N=osPpidMap())),F=N.get(t)??[]);for(let t of F)S.has(t)||(S.add(t),n.push(t),C.push(t))}return n}var zI=__esmMin(()=>{w_(),Md()});function staleMs(){let t=process.env.GJSIFY_INSTALL_LOCK_STALE_MS;if(t!==void 0){let n=Number(t);if(Number.isFinite(n)&&n>0)return n}return HI}function lockingDisabled(){let t=process.env.GJSIFY_INSTALL_LOCK;if(t===void 0)return!1;let n=t.trim();return n===`0`||n===`false`}function mtimeMs(t){try{return statSync(t).mtimeMs}catch{return null}}function assessLock(t){let n=xn(t,VI),S=null;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch{S=null}let C=Date.now();if(S&&typeof S.pid==`number`){if(!isPidAlive(S.pid))return{stale:!0,reason:`owner pid ${S.pid} is gone`,ownerPid:S.pid};let t=typeof S.startedAt==`number`?S.startedAt:mtimeMs(n);return t!==null&&C-t>staleMs()?{stale:!0,reason:`owner pid ${S.pid} exceeded the ${staleMs()}ms staleness budget`,ownerPid:S.pid}:{stale:!1,ownerPid:S.pid}}let N=mtimeMs(t);return N===null?{stale:!1}:C-N>WI?{stale:!0,reason:`no owner recorded within the acquire grace period`}:{stale:!1}}function stealStaleLock(t){let n=`${t}.stale-${process.pid}-${++JI}`;try{renameSync(t,n)}catch{return!1}try{rmSync(n,{recursive:!0,force:!0})}catch{}return!0}function abortErr(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}function delay(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let onAbort=()=>{clearTimeout(N),C(abortErr(n))},N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t);if(n?.aborted){clearTimeout(N),C(abortErr(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function makeHandle(t){let n=!1;return{release(){if(n)return;n=!0;let S=qI.get(t);if(S&&(S.count--,!(S.count>0))){qI.delete(t);try{let n=JSON.parse(readFileSync(xn(t,VI),`utf-8`));if(n.nonce!==void 0&&n.nonce!==S.nonce)return}catch{}try{rmSync(t,{recursive:!0,force:!0})}catch{}}}}}async function acquireInstallLock(t,n={}){if(lockingDisabled())return{release(){}};let S;try{S=realpathSync(t)}catch{S=vn(t)}let C=xn(S,`node_modules`,BI),N=qI.get(C);if(N)return N.count++,makeHandle(C);mkdirSync(wn(C),{recursive:!0});let F=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,I=GI,H=!1;for(;;){if(n.signal?.aborted)throw abortErr(n.signal);try{return mkdirSync(C),writeFileSync(xn(C,VI),JSON.stringify({pid:process.pid,nonce:F,startedAt:Date.now()})),qI.set(C,{count:1,nonce:F}),makeHandle(C)}catch(t){if(t.code!==`EEXIST`)throw t}let t=assessLock(C);if(t.stale){stealStaleLock(C)&&ge.warn(`gjsify install: removed stale install lock (${t.reason}) — ${C}`);continue}if(!H){H=!0;let n=t.ownerPid===void 0?``:` (pid ${t.ownerPid})`;ge.warn(`gjsify install: waiting for a concurrent install${n} to release ${C} …`)}await delay(I,n.signal),I=Math.min(Math.round(I*1.6),KI)}}var BI,VI,HI,WI,GI,KI,qI,JI,YI=__esmMin(()=>{_e(),Md(),jn(),zI(),BI=`.gjsify-install-lock`,VI=`owner.json`,HI=35*6e4,WI=15e3,GI=150,KI=1e3,qI=new Map,JI=0});function cacheRoot$1(){return gjsifyCacheRoot(`tarballs`,XI)}function parseSri$1(t){if(!t)return null;let n=t.indexOf(`-`);if(n<=0||n===t.length-1)return null;let S=t.slice(0,n),C=t.slice(n+1).replace(/=+$/,``),N=Xe.from(C,`base64`).toString(`hex`);return N.length<4?null:{algorithm:S,hex:N}}function pathFor$3(t){let n=parseSri$1(t);if(!n)return null;let S=n.hex.slice(0,2);return xn(cacheRoot$1(),n.algorithm,S,`${n.hex}.tgz`)}async function getCachedTarball(t){let n=pathFor$3(t);if(!n||!t)return null;let S=readCacheFile(n);if(!S)return null;if(await verifyIntegrity(S,t))return S;try{unlinkSync(n)}catch{}return null}function putCachedTarball(t,n){let S=pathFor$3(t);S&&(existsSync(S)||atomicWrite(S,n))}function npmCacacheContentDir(){let t=process.env.GJSIFY_NPM_CACHE;if(t!==void 0){let n=t.trim();return n===``||n===`0`||n===`false`?null:xn(n.endsWith(`_cacache`)?n:xn(n,`_cacache`),`content-v2`)}let n=process.env.npm_config_cache;return xn(n&&n.length>0?n:xn(homedir(),`.npm`),`_cacache`,`content-v2`)}function npmCachePathFor(t){let n=npmCacacheContentDir();if(!n)return null;let S=parseSri$1(t);return S?xn(n,S.algorithm,S.hex.slice(0,2),S.hex.slice(2,4),S.hex.slice(4)):null}async function getForeignCachedTarball(t){let n=npmCachePathFor(t);if(!n||!t)return null;let S=readCacheFile(n);return S&&await verifyIntegrity(S,t)?S:null}var XI,ZI=__esmMin(()=>{ot(),Md(),Dg(),jn(),Jm(),kI(),XI=`v1`,__name$1(cacheRoot$1,`cacheRoot`),__name$1(parseSri$1,`parseSri`),__name$1(pathFor$3,`pathFor`)});function isEnabled(){let t=process.env.GJSIFY_PACKUMENT_CACHE;if(t===void 0)return!0;let n=t.trim();return!(n===`0`||n===`false`||n===``)}function cacheRoot(){return gjsifyCacheRoot(`metadata`,QI)}function shardFor(t){let n=2166136261;for(let S=0;S<t.length;S++)n^=t.charCodeAt(S),n=Math.imul(n,16777619);return(n>>>0&255).toString(16).padStart(2,`0`)}function encodePart(t){return encodeURIComponent(t).replace(/\*/g,`%2A`)}function packumentCacheKey(t,n,S){return`${S},${encodePart(t)},${encodePart(n)}`}function pathFor$2(t,n,S){if(!isEnabled())return null;let C=packumentCacheKey(t,n,S);return xn(cacheRoot(),shardFor(C),`${C}.json`)}function getCachedPackument(t,n,S=`corgi`){let C=pathFor$2(t,n,S);if(!C)return null;let N=readCacheFile(C);if(!N)return null;try{let t=JSON.parse(N.toString(`utf-8`));return typeof t.etag!=`string`||!t.etag||!t.packument||typeof t.packument!=`object`?null:{etag:t.etag,packument:t.packument}}catch{return null}}function putCachedPackument(t,n,S,C,N=`corgi`){if(!S)return;let F=pathFor$2(t,n,N);F&&atomicWrite(F,JSON.stringify({etag:S,packument:C}))}var QI,$I=__esmMin(()=>{jn(),kI(),QI=`v3`,__name$1(pathFor$2,`pathFor`)});function parseNodeMajor(t){return Number.parseInt(String(t).split(`.`,1)[0]??``,10)}function nativeBackendNodeError(t,n){if(!n)return null;let S=parseNodeMajor(t);return!Number.isFinite(S)||S>=24?null:`gjsify install (native backend) requires Node ≥ 24, but this is Node ${t}. Its prebuilt native modules are ABI-locked to Node 24 and crash on older majors. Use Node 24 (nvm/asdf locally, actions/setup-node in CI), or run with --backend npm.`}function onRealNode(){return gjsSystemVersion()===void 0?isNode():!1}function assertNativeBackendNodeVersion(){let t=nativeBackendNodeError(process.versions.node,onRealNode());if(t)throw Error(t)}var eL=__esmMin(()=>{t_()});function normalizePath(t){let n=On===`/`?t:t.split(On).join(`/`);return n.endsWith(`/`)?n.slice(0,-1):n}function findExtraneous(t){let n=new Set(t.expected.map(t=>normalizePath(t.installPath))),S=t.installed.filter(t=>t.bundles&&!t.linked).map(n=>`${normalizePath(Sn(t.prefix,n.dir))}/node_modules/`),C=[];for(let N of t.installed){if(N.linked)continue;let F=normalizePath(Sn(t.prefix,N.dir));F===``||F.startsWith(`..`)||n.has(F)||S.some(t=>F.startsWith(t))||C.push({installPath:F,name:N.name,version:N.version})}C.sort((t,n)=>t.installPath<n.installPath?-1:+(t.installPath>n.installPath));let N=[];for(let t of C){let n=N[N.length-1];n&&t.installPath.startsWith(`${n.installPath}/`)||N.push(t)}return N}function formatExtraneousError(t,n){let S=t.slice(0,20),C=S.map(t=>` ${t.installPath} (${t.name}@${t.version})`);return t.length>S.length&&C.push(` … and ${t.length-S.length} more`),[`install: --immutable, but ${n}/node_modules holds ${t.length} package(s) that gjsify-lock.json does not describe.`,`--immutable installs the lockfile and removes nothing, so each of these would survive the install and be resolved, bundled and type-checked as if it belonged (gjsify#1683: a nested copy of an already-hoisted package → TS2883, one type with two identities).`,...C,"Fix: delete those directories — or the whole node_modules — and re-run. A plain `gjsify install` does NOT clear them: it only ever adds, and its prune pass judges foreign-PLATFORM packages alone (prune-prefix.ts), so an undescribed package survives both. Deleting is currently the only thing that removes one. In CI this usually means a cache entry was restored from a DIFFERENT lockfile."].join(`
|
|
907
|
+
`)}var tL=__esmMin(()=>{jn()});function dirLinkTarget(t,n,S=nL){return S===`junction`?vn(n):Sn(wn(t),n)}function linkDirSync(t,n){assertAbsolute(n),symlinkSync(dirLinkTarget(t,n),t,rL)}function replicateLinkSync(t,n){let S=readlinkSync(t);if(!dirLinksAreJunctions()){symlinkSync(S,n);return}let C=vn(wn(t),S),N;try{N=statSync(C).isDirectory()}catch{symlinkSync(S,n);return}N?symlinkSync(C,n,`junction`):symlinkSync(S,n,`file`)}function assertAbsolute(t){if(vn(t)!==t)throw TypeError(`linkDir: target must be an absolute path, got ${JSON.stringify(t)}. Node resolves a Windows junction target against the process CWD rather than the link's own directory, so a relative target silently points somewhere else there.`)}var nL,rL,dirLinksAreJunctions,iL=__esmMin(()=>{Md(),hd(),jn(),nL=process.platform===`win32`?`junction`:`symlink`,rL=nL===`junction`?`junction`:void 0,dirLinksAreJunctions=()=>nL===`junction`});function checkList(t,n){let S=typeof n==`string`?[n]:n;if(S.length===1&&S[0]===`any`)return!0;let C=0,N=!1;for(let n of S){let S=n.charAt(0)===`!`,F=S?n.slice(1):n;if(S){if(C++,t===F)return!1}else N||=t===F}return N||C===S.length}function checkPlatform(t,n){let S=t.os?checkList(n.os,t.os):!0,C=t.cpu?checkList(n.cpu,t.cpu):!0,N=t.libc?checkList(n.libc,t.libc):!0;return t.libc&&!n.libc&&(N=!1),{ok:S&&C&&N,current:{os:n.os,cpu:n.cpu,libc:n.libc},required:{os:t.os,cpu:t.cpu,libc:t.libc}}}function declaresPlatform(t){return!!(t.os||t.cpu||t.libc)}function badPlatformError(t,n){let S=Error(`Unsupported platform for ${t}: wanted ${JSON.stringify(n.required)} (current: ${JSON.stringify(n.current)})`);return S.code=`EBADPLATFORM`,S.pkgid=t,S.current=n.current,S.required=n.required,S}function isMuslSharedObject(t){return t.includes(`libc.musl-`)||t.includes(`ld-musl-`)}function libcFromLddFile(t){let n=t.readTextFile(aL);if(n!==null)return n.includes(`musl`)?`musl`:n.includes(`GNU C Library`)?`glibc`:null}function libcFromReportData(t){return t.glibcVersionRuntime?`glibc`:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(t=>isMuslSharedObject(String(t)))?`musl`:null}function libcFromLoaderScan(t,n=oL){let S=!1;for(let C of n){let n=t.listDir(C);if(n)for(let t of n){if(t.startsWith(`ld-linux`))return`glibc`;t.startsWith(`ld-musl-`)&&(S=!0)}}return S?`musl`:null}function detectLibc(t,n){if(t!==`linux`)return;let S=libcFromLddFile(n);if(S!==void 0)return S??void 0;let C=n.diagnosticReport();return C===null?libcFromLoaderScan(n)??void 0:libcFromReportData(C)??void 0}function defaultLibcProbeHost(){return{readTextFile(t){try{return readFileSync(t,`utf-8`)}catch{return null}},listDir(t){try{return readdirSync(t)}catch{return null}},diagnosticReport(){let t=process.report;if(!t||typeof t.getReport!=`function`)return null;let n=t.excludeNetwork;t.excludeNetwork=!0;try{let n=t.getReport();return{glibcVersionRuntime:n.header?.glibcVersionRuntime,sharedObjects:n.sharedObjects}}finally{t.excludeNetwork=n}}}}function hostLibc(t,n=defaultLibcProbeHost()){return cL||=(sL=detectLibc(t,n),!0),sL}function readPlatformOverrides(t){let pick=n=>{let S=t[n];if(typeof S!=`string`)return;let C=S.trim();return C===``?void 0:C},n={},S=pick(`npm_config_os`),C=pick(`npm_config_cpu`),N=pick(`npm_config_libc`);return S!==void 0&&(n.os=S),C!==void 0&&(n.cpu=C),N!==void 0&&(n.libc=N),n}function readPlatformForce(t){let n=t.npm_config_force;if(typeof n!=`string`)return!1;let S=n.trim().toLowerCase();return S===`true`||S===`1`}function resolveHostPlatform(t={}){let n=readPlatformOverrides(t.env??process.env),S=n.os??t.platform??process.platform;return{os:S,cpu:n.cpu??t.arch??process.arch,libc:n.libc??(S===`linux`?hostLibc(S,t.probe??defaultLibcProbeHost()):void 0)}}function describePlatformTarget(t){return`${t.os}-${t.cpu}${t.libc?`-${t.libc}`:``}`}var aL,oL,sL,cL,lL=__esmMin(()=>{Md(),aL=`/usr/bin/ldd`,oL=[`/lib`,`/lib64`,`/usr/lib`],cL=!1});function isReservedEntry(t){return t.startsWith(`.`)}function readManifest(t){try{let n=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`)),S={os:n.os,cpu:n.cpu,libc:n.libc};return{name:typeof n.name==`string`?n.name:void 0,version:typeof n.version==`string`?n.version:void 0,platform:declaresPlatform(S)?S:void 0,bundles:[n.bundleDependencies,n.bundledDependencies].some(t=>t===!0||Array.isArray(t)&&t.length>0)}}catch{return null}}function collect(t,n){let S;try{S=readdirSync(t,{withFileTypes:!0})}catch{return}for(let C of S){if(isReservedEntry(C.name))continue;let S=xn(t,C.name);if(C.name.startsWith(`@`)){let t;try{t=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let C of t)isReservedEntry(C.name)||addPackage(xn(S,C.name),n);continue}addPackage(S,n)}}function addPackage(t,n){let S=!1;try{S=lstatSync(t).isSymbolicLink()}catch{return}let C=readManifest(t);n.push({name:C?.name??t,version:C?.version??`0.0.0`,dir:t,linked:S,platform:C?.platform,bundles:C?.bundles}),S||collect(xn(t,`node_modules`),n)}function scanPrefix(t){let n=[];return collect(xn(t,`node_modules`),n),n}function planPlatformPrune(t,n){let S=[];for(let C of t){if(C.linked||!C.platform)continue;let t=checkPlatform(C.platform,n);t.ok||S.push({pkg:C,bytes:0,verdict:t})}return S}function dirBytes(t){let n=0,S=[t];for(;S.length>0;){let t=S.pop(),C;try{C=readdirSync(t,{withFileTypes:!0})}catch{continue}for(let N of C){let C=xn(t,N.name);if(N.isDirectory())S.push(C);else if(N.isFile())try{n+=statSync(C).size}catch{}}}return n}function planPrune(t){let n=scanPrefix(t.prefix),S=planPlatformPrune(n,t.target);for(let t of S)t.bytes=dirBytes(t.pkg.dir);return{prefix:t.prefix,target:t.target,scanned:n.length,entries:S,bytes:S.reduce((t,n)=>t+n.bytes,0)}}function executePrune(t,n={}){let S=[],C=[],N=[],F=n.remove??(t=>rmSync(t,{recursive:!0,force:!0,maxRetries:10}));if(!n.dryRun){for(let n of t.entries)try{F(n.pkg.dir),S.push(n)}catch(t){C.push({entry:n,error:t.message})}N.push(...pruneDeadBinLinks(t.prefix))}return{plan:t,removed:S,failed:C,bytes:S.reduce((t,n)=>t+n.bytes,0),binLinks:N}}function pruneDeadBinLinks(t){let n=xn(t,`node_modules`,`.bin`),S=[],C;try{C=readdirSync(n,{withFileTypes:!0})}catch{return S}for(let t of C){let C=xn(n,t.name);try{if(!lstatSync(C).isSymbolicLink()||existsSync(C))continue;unlinkSync(C),S.push(t.name)}catch{}}return S}function humanBytes(t){if(t<1024)return`${t} B`;let n=[`KB`,`MB`,`GB`],S=t/1024,C=0;for(;S>=1024&&C<n.length-1;)S/=1024,C+=1;return`${S.toFixed(1)} ${n[C]}`}function formatPruneReport(t,n){let{plan:S}=t,C=[`${S.prefix} · target ${describePlatformTarget(S.target)} · scanned ${S.scanned} package(s)`];if(S.entries.length===0)return C.push(`nothing to prune — no installed package declares a platform this target cannot use.`),C.join(`
|
|
908
|
+
`);let N=n.verbose?S.entries:S.entries.slice(0,uL);for(let t of N){let n=JSON.stringify(t.verdict.required);C.push(` ${t.pkg.name}@${t.pkg.version} ${humanBytes(t.bytes)} requires ${n}`)}N.length<S.entries.length&&C.push(` … and ${S.entries.length-N.length} more (--verbose to list them)`),C.push(n.dryRun?`would free ${humanBytes(S.bytes)} across ${S.entries.length} package(s) (apparent size)`:`freed ${humanBytes(t.bytes)} across ${t.removed.length} package(s) (apparent size)`),t.binLinks.length>0&&C.push(`removed ${t.binLinks.length} dangling .bin link(s): ${t.binLinks.join(`, `)}`);for(let n of t.failed)C.push(`FAILED ${n.entry.pkg.name}: ${n.error}`);return C.join(`
|
|
909
|
+
`)}function automaticPruneRefusal(t,n){return Object.keys(readPlatformOverrides(t)).length>0?`the platform target was overridden on the command line`:n?`--immutable`:null}function pruneAfterInstall(t,n,S={}){try{if(automaticPruneRefusal(S.env??process.env,S.immutable??!1))return;let C=planPrune({prefix:t,target:n});if(C.entries.length===0)return;let N=executePrune(C);if(N.removed.length===0)return;let F=S.hint?` (${S.hint} to review)`:``;ge.log(`gjsify: pruned ${N.removed.length} package(s) this host cannot use, freeing ${humanBytes(N.bytes)}${F}`)}catch(t){process.env.GJSIFY_DEBUG&&ge.error(`gjsify: prune skipped — ${t.message}`)}}var uL,dL=__esmMin(()=>{_e(),Md(),jn(),lL(),uL=10});function devLinkPath(t){return xn(t,fL)}function readDevLinkOverride(t){let n=devLinkPath(t);if(!existsSync(n))return null;let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify link: ${n} is not valid JSON (${t instanceof Error?t.message:String(t)}). Fix it or run \`gjsify unlink\`.`)}if(!S||typeof S!=`object`)throw Error(`gjsify link: ${n} must contain a JSON object.`);let C=S;if(C.version!==1)throw Error(`gjsify link: ${n} declares version ${JSON.stringify(C.version)}; this CLI understands version 1 only.`);if(typeof C.checkout!=`string`||C.checkout.trim()===``)throw Error(`gjsify link: ${n} has no "checkout" path.`);return{version:1,checkout:bn(C.checkout)?C.checkout:vn(t,C.checkout),packages:Array.isArray(C.packages)?C.packages.filter(t=>typeof t==`string`):[]}}function writeDevLinkOverride(t,n){let S=devLinkPath(t);return writeFileSync(S,JSON.stringify(n,null,2)+`
|
|
910
910
|
`),S}function removeDevLinkOverride(t){let n=devLinkPath(t);return existsSync(n)?(rmSync(n),n):null}function devLinkRoot(t){if(existsSync(devLinkPath(t)))return t;let n=findWorkspaceRoot(t);return n&&existsSync(devLinkPath(n))?n:t}function resolveCheckoutWorkspaces(t,n){if(!existsSync(t))throw Error(`gjsify link: the linked checkout ${t} does not exist (named by ${n}). Point it at a gjsify checkout, or run \`gjsify unlink\`.`);let S=readPackageJson$2(xn(t,`package.json`));if(!S||S.workspaces===void 0)throw Error(`gjsify link: ${t} is not a gjsify workspace — ${xn(t,`package.json`)} ${S?`declares no "workspaces" field`:`is missing or unreadable`} (named by ${n}).`);let C;try{C=discoverWorkspaces(t)}catch(S){throw Error(`gjsify link: ${t} declares "workspaces" but they could not be discovered (${S instanceof Error?S.message:String(S)}); named by ${n}.`)}if(C.length===0)throw Error(`gjsify link: ${t} declares "workspaces" but none were found (named by ${n}).`);return C}function consumerKnownNames(t){let n=new Set,S=[readPackageJson$2(xn(t,`package.json`))];try{for(let n of discoverWorkspaces(t))S.push(n.manifest)}catch{}for(let t of S)if(t)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`]){let C=t[S];if(!(!C||typeof C!=`object`))for(let t of Object.keys(C))n.add(t)}for(let S of scanPrefix(t))n.add(S.name);return n}function planDevLinks(t){let n=t.patterns.length>0?filterWorkspaces(t.workspaces,{include:[...t.patterns]}):[...t.workspaces],S=[];for(let C of n)C.name&&t.knownNames.has(C.name)&&S.push({name:C.name,target:C.location,linkPath:xn(t.consumerRoot,`node_modules`,C.name)});return S.sort((t,n)=>t.name<n.name?-1:+(t.name>n.name)),S}function prepareDevLinks(t){let n=readDevLinkOverride(t);if(!n)return null;let S=devLinkPath(t),C=planDevLinks({consumerRoot:t,workspaces:resolveCheckoutWorkspaces(n.checkout,S),patterns:n.packages,knownNames:consumerKnownNames(t)});return{overridePath:S,consumerRoot:t,checkout:n.checkout,links:C,names:new Set(C.map(t=>t.name))}}function applyDevLinks(t){assertDevLinksBuilt(t);let n=[];for(let S of t)linkAlreadyPointsAt(S.linkPath,S.target)||(mkdirSync(wn(S.linkPath),{recursive:!0}),rmSync(S.linkPath,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}),linkDirSync(S.linkPath,S.target),n.push(S));return n}function removeDevLinks(t){let n=[];for(let S of t){let t=!1;try{t=lstatSync(S.linkPath).isSymbolicLink()}catch{continue}t&&linkAlreadyPointsAt(S.linkPath,S.target)&&(rmSync(S.linkPath,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}),n.push(S))}return n}function linkAlreadyPointsAt(t,n){try{return lstatSync(t).isSymbolicLink()?realpathSync(t)===realpathSync(n):!1}catch{return!1}}function scanDevLinks(t,n){let S=[];for(let t of n)try{S.push(realpathSync(t))}catch{}if(S.length===0)return[];let C=xn(t,`node_modules`),N=[],consider=t=>{let n=xn(C,t),F;try{if(!lstatSync(n).isSymbolicLink())return;F=realpathSync(n)}catch{return}S.some(t=>F===t||F.startsWith(t+On))&&N.push({name:t,target:F,linkPath:n})},F;try{F=readdirSync(C)}catch{return[]}for(let t of F)if(!t.startsWith(`.`)){if(t.startsWith(`@`)){let n;try{n=readdirSync(xn(C,t))}catch{continue}for(let S of n)consider(`${t}/${S}`);continue}consider(t)}return N.sort((t,n)=>t.name<n.name?-1:+(t.name>n.name)),N}function retireDevLinks(t,n,S){return removeDevLinks(scanDevLinks(t,n).filter(t=>!S.has(t.name)))}function unbuiltDevLinks(t){let n=[];for(let S of t){let t;try{t=JSON.parse(readFileSync(xn(S.target,`package.json`),`utf-8`))}catch(t){n.push({link:S,reason:`its package.json is missing or unreadable (${t instanceof Error?t.message:String(t)})`});continue}let C=[];for(let n of[`main`,`module`]){let S=t[n];typeof S==`string`&&C.push(S)}let N=t.exports;typeof N==`string`?C.push(N):N&&typeof N==`object`&&collectStringLeaves(N[`.`],C),C.length!==0&&(C.some(t=>existsSync(xn(S.target,t)))||n.push({link:S,reason:`none of its declared entry points exist yet (${C.join(`, `)})`}))}return n}function formatUnbuiltDevLinks(t){let n=t.map(t=>` ${t.link.name} ${t.link.target}\n ${t.reason}`).join(`
|
|
911
911
|
`);return`gjsify link: ${t.length} linked package(s) are not built, so linking them would hand the consumer a tree whose first import fails with MODULE_NOT_FOUND:\n${n}\n Build them in the checkout (\`gjsify run build\` there) and re-run, or narrow the selection with \`gjsify link <checkout> --packages <glob>\`. A link does not build.`}function assertDevLinksBuilt(t){let n=unbuiltDevLinks(t);if(n.length!==0)throw Error(formatUnbuiltDevLinks(n))}function collectStringLeaves(t,n){if(typeof t==`string`){n.push(t);return}if(!(!t||typeof t!=`object`))for(let S of Object.values(t))collectStringLeaves(S,n)}function ensureLocallyIgnored(t){let n=resolveGitDir(t);if(!n.commonDir)return n.why;let S=xn(t,`.gitignore`);if(existsSync(S)&&fileMentionsPattern(S,`.gjsify-link.json`))return`already-ignored`;let C=xn(n.commonDir,`info`,`exclude`);if(existsSync(C)&&fileMentionsPattern(C,`.gjsify-link.json`))return`already-ignored`;mkdirSync(wn(C),{recursive:!0});let N=existsSync(C)?readFileSync(C,`utf-8`):``;return writeFileSync(C,`${N}${N===``||N.endsWith(`
|
|
912
912
|
`)?``:`
|
|
913
|
-
`}${
|
|
914
|
-
`)),`removed`):`absent`}function fileMentionsPattern(t,n){let S;try{S=readFileSync(t,`utf-8`)}catch{return!1}return S.split(/\r?\n/).some(t=>{let S=t.trim();return S===n||S===`/${n}`})}function resolveGitDir(t){let n=xn(t,`.git`),S;try{S=statSync(n)}catch{return{commonDir:null,why:`no-git`}}if(S.isDirectory())return{commonDir:n,why:`no-git`};let C;try{C=readFileSync(n,`utf-8`).trim()}catch{return{commonDir:null,why:`unreadable-git`}}let N=/^gitdir:\s*(.+)$/.exec(C)?.[1]?.trim();return N?followCommondir(bn(N)?N:vn(t,N)):{commonDir:null,why:`unreadable-git`}}function followCommondir(t){let n=xn(t,`commondir`);if(!existsSync(n))return{commonDir:t,why:`no-git`};let S;try{S=readFileSync(n,`utf-8`)}catch{return{commonDir:null,why:`unreadable-git`}}let C=S.trim();if(!C)return{commonDir:null,why:`unreadable-git`};let N=bn(C)?C:vn(t,C);return existsSync(N)?{commonDir:N,why:`no-git`}:{commonDir:null,why:`unreadable-git`}}function assertNoDevLinkUnderImmutable(t){let n=devLinkRoot(t),S=devLinkPath(n);if(!existsSync(S))return;let C=`(unreadable)`;try{C=readDevLinkOverride(n)?.checkout??C}catch{}throw Error(`gjsify install --immutable: a development link override is active — ${S}\nIt points at ${C}, so this install would build from a local checkout instead of what ${xn(n,`gjsify-lock.json`)} pins. --immutable builds only what is committed.\nRun \`gjsify unlink\` (in ${n}) or delete ${dL}, then re-run.`)}var dL,fL,pL=__esmMin(()=>{Md(),jn(),DP(),rL(),OP(),uL(),kP(),dL=`.gjsify-link.json`,fL=`# gjsify link — local development override, never commit`}),mL=__exportAll$5({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,parseSpecName:()=>parseSpecName,pickVersion:()=>pickVersion,reachableInstallPaths:()=>reachableInstallPaths,readLockfileNodes:()=>readLockfileNodes,requiredDepEntries:()=>requiredDepEntries,requiredPeerEntries:()=>requiredPeerEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(t){if(assertNativeBackendNodeVersion(),t.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(t.prefix,{recursive:!0});let n=await loadNpmrc$1(t),S=makeLogger(t.verbose??!1),C=await acquireInstallLock(t.prefix,{signal:t.signal});try{return await installPackagesNativeLocked(t,n,S)}finally{C.release()}}async function installPackagesNativeLocked(t,n,S){let C=t.progress,N=xn(t.prefix,gL),F=readLockfile(N),I=resolveHostPlatform(),H=readPlatformForce(process.env);S(`install: platform target %s%s`,describePlatformTarget(I),H?` (--force: checks bypassed)`:``);let W,q=!1,Y=new Set;if(t.frozen||t.focusSpecs){let n=t.frozen?`--immutable`:`--focus`,C=t.frozen?`(without --immutable)`:`(without --focus)`;if(!F)throw Error(`install: ${n} requires ${gL} at ${t.prefix} — none found. Run \`gjsify install\` ${C} to generate one and commit it.`);let I=describeLockfileDrift(F,t.specs);if(I)throw Error(`install: ${n} but ${N} is stale.\n${I}\nRe-run \`gjsify install\` ${C} to refresh the lockfile.`);if(S(`install: %s, using lockfile (%d package(s))`,n,Object.keys(F.packages).length),W=lockfileToNodes(F),t.frozen&&assertNoExtraneous(t.prefix,W),t.focusSpecs){let n=reachableInstallPaths(W,t.focusSpecs.map(parseSpecName));S(`install: --focus keeps %d of %d lockfile package(s)`,n.size,W.length),W=W.filter(t=>n.has(t.installPath))}}else if(!t.refreshLockfile&&F&&F.lockfileVersion===_L&&F.peersResolved===!0&&lockfileMatchesRequest(F,t.specs))S(`install: using lockfile (%d package(s))`,Object.keys(F.packages).length),W=lockfileToNodes(F);else{let N=!t.refreshLockfile&&F?buildPreferredVersions(F):void 0;S(`install: resolving %d top-level spec(s) → %s%s`,t.specs.length,t.prefix,N?` (preserving ${N.size} locked name(s))`:``);let I=await resolveDeps(t.specs,n,S,t.overrides,t.skipDeps,t.signal,C,N,t.workspaceNames,t.specOrigins,t.optionalSpecs);W=I.nodes,Y=I.skippedEdges,q=!0}computeOptionalFlags(W,requiredTopLevelNames(t.focusSpecs??t.specs,t.optionalSpecs),S),assertRequiredEdgesResolved(W,Y),q&&t.lockfile&&(writeLockfile(N,t.specs,W),S(`install: wrote %s (%d entries)`,gL,W.length));let X=W;if(t.workspaceNames&&t.workspaceNames.size>0){let n=X.length;X=X.filter(n=>!t.workspaceNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d workspace-provided package(s) symlinked, not fetched`,C)}if(t.linkedNames&&t.linkedNames.size>0){let n=X.length;X=X.filter(n=>!t.linkedNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d dev-linked package(s) provided by a local checkout, not fetched`,C)}let Z=applyPlatformFilter(X,I,H,S);return S(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,t.prefix,n,S,t.signal,C),await linkBins(Z,t.prefix,S),warnMissingNativeBuilds(Z,t.prefix,S),S(`install: done`),topLevelResolutions(t.specs,W)}function assertNoExtraneous(t,n){let S=findExtraneous({prefix:t,installed:scanPrefix(t),expected:n});if(S.length!==0)throw Error(formatExtraneousError(S,t))}function errMsg(t){return t instanceof Error?t.message:String(t)}function applyPlatformFilter(t,n,S,C){let N=[],F=0;for(let I of t){let t=I.platform;if(!t||!declaresPlatform(t)){N.push(I);continue}let H=checkPlatform(t,n);if(H.ok){N.push(I);continue}let W=`${I.name}@${I.version}`;if(!I.optional){if(S){C(`platform-forced: %s (required, incompatible, installed anyway via --force)`,W),N.push(I);continue}throw badPlatformError(W,H)}I.inert=!0,F++,C(`platform-skip: %s (%s) current=%s required=%s`,W,I.installPath,JSON.stringify(H.current),JSON.stringify(H.required))}return F>0&&C(`install: %d optional package(s) inert — not installable on %s`,F,describePlatformTarget(n)),N}function warnMissingNativeBuilds(t,n,S){let C=process.platform,N=process.arch,F=[`preinstall`,`install`,`postinstall`];for(let I of t){let t=xn(n,I.installPath),H;try{H=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))?.scripts}catch{continue}if(!H||typeof H!=`object`)continue;let W=F.find(t=>typeof H[t]==`string`);if(W===void 0)continue;let q=!1;try{let n=xn(t,`prebuilds`);for(let t of readdirSync(n))if(t.startsWith(`${C}-`)&&readdirSync(xn(n,t)).length>0){q=!0;break}}catch{}if(!q)try{q=readdirSync(xn(t,`build`,`Release`)).some(t=>t.endsWith(`.node`)||t.endsWith(`.so`))}catch{}q||S("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",I.name,W,C,N,I.installPath,C,N)}}function topLevelResolutions(t,n){let S=new Map;for(let t of n)t.installPath===`node_modules/${t.name}`&&S.set(t.name,t);let C=[];for(let n of t){let t=parseSpecName(n),N=S.get(t);N&&C.push({name:N.name,version:N.version})}return C}function parseSpecName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return t;let S=t.indexOf(`@`,n+1);return S===-1?t:t.slice(0,S)}let n=t.indexOf(`@`);return n===-1?t:t.slice(0,n)}async function resolveDeps(t,n,S,C,N,F,I,H,W,q,Y){I?.beginPhase(`resolve`,t.length);let applyOverride=(t,n)=>{if(!C)return n;let N=C[t];return typeof N!=`string`||N.length===0||N===n?n:(S(`install: override %s %s → %s`,t,n,N),N)},X=new Map,fetchPkg=t=>{let C=X.get(t);if(C)return C;let N=fetchPackumentWithDiskCache(t,n,S,F,`full`);return X.set(t,N),N},Z=new Map,te=new Map,ne=new Set,re=new Map,ie=t.map(parseSpec$1).map(t=>{let n=applyOverride(t.name,t.range),S=re.get(t.name);S||(S=new Map,re.set(t.name,S));let C=S.get(n);C||(C=new Set,S.set(n,C));for(let n of q?.get(`${t.name}@${t.range}`)??[])C.add(n);return{from:null,name:t.name,range:n,required:!Y?.has(t.name)}});for(;ie.length>0;){let t=ie.splice(0,ie.length),n=[],C=new Set;for(let S of t)X.has(S.name)||C.has(S.name)||(C.add(S.name),n.push(S.name));await prefetchPackuments(n,fetchPkg,F);for(let n=0;n<t.length;n++){let C=t[n];if(W?.has(C.name))continue;let F=findVisible(C.from,C.name,Z);if(F&&satisfiesRange(F.version,C.range))continue;if(C.peerOf){let t=C.from===null?`node_modules/${C.name}`:`${C.from}/node_modules/${C.name}`,n=Z.get(t);if(n){ge.warn(`[gjsify] warning: peer dependency conflict: ${C.peerOf.name}@${C.peerOf.version} wants ${C.name}@${C.range}, but ${n.version} is installed at ${n.installPath} — keeping it (npm's non-strict behaviour).`);continue}}let q=null;try{let F=await fetchPkg(C.name),W=preferredVersionFor(H?.get(C.name),C.range);if(q=pickVersion(F,C.range,W),!q)throw Error(`No version of ${C.name} satisfies ${C.range}`);let Y=F.versions[q];if(!Y)throw Error(`Packument for ${C.name} promised ${q} but no entry exists`);let X=decidePlacement(C.from,C.name,q,te),ne={name:C.name,version:q,tarballUrl:Y.dist.tarball,integrity:Y.dist.integrity,installPath:X,dependencies:Y.dependencies??{},optionalDependencies:Y.optionalDependencies??{},peerDependencies:nonEmpty(Y.peerDependencies),peerDependenciesMeta:nonEmpty(Y.peerDependenciesMeta),bin:Y.bin,platform:platformDeclarationOf(Y),optional:!C.required};if(Z.set(X,ne),X===`node_modules/${C.name}`&&te.set(C.name,ne),S(`resolve: %s@%s ← %s (at %s)`,C.name,q,C.range,X),I?.update({phase:`resolve`,current:Z.size,total:Z.size+(t.length-n-1)+ie.length,name:`${C.name}@${q}`}),!N){let t=parentInstallPath(X);for(let[n,S]of requiredPeerEntries(ne))ie.push({from:t,name:n,range:applyOverride(n,S),required:!ne.optional,peerOf:ne});for(let[t,n]of requiredDepEntries(ne))ie.push({from:X,name:t,range:applyOverride(t,n),required:!ne.optional});for(let[t,n]of Object.entries(ne.optionalDependencies))ie.push({from:X,name:t,range:applyOverride(t,n),required:!1})}}catch(t){if(!C.required){ne.add(edgeKey(C.peerOf?.installPath??C.from,C.name)),S(`resolve: optional dep %s@%s skipped (%s)`,C.name,C.range,errMsg(t));continue}throw t}}}return I?.endPhase(`resolve`),emitTopLevelConflictWarnings(re,te),{nodes:Array.from(Z.values()),skippedEdges:ne}}function platformDeclarationOf(t){let n={os:t.os,cpu:t.cpu,libc:t.libc};return declaresPlatform(n)?n:void 0}function edgeKey(t,n){return`${t??``}\n${n}`}function parseEdgeKey(t){let n=t.indexOf(`
|
|
915
|
-
`),S=t.slice(0,n);return{from:S===``?null:S,name:t.slice(n+1)}}function requiredTopLevelNames(t,n){let S=new Set;for(let C of t){let t=parseSpecName(C);n?.has(t)||S.add(t)}return S}function requiredDepEntries(t){let n=[];for(let[S,C]of Object.entries(t.dependencies))S in t.optionalDependencies||n.push([S,C]);return n}function requiredPeerEntries(t){let n=[];for(let[S,C]of Object.entries(t.peerDependencies??{}))t.peerDependenciesMeta?.[S]?.optional!==!0&&(S in t.dependencies||S in t.optionalDependencies||n.push([S,C]));return n}function computeOptionalFlags(t,n,S){let C=new Map;for(let n of t)C.set(n.installPath,n);let N=new Set,F=[],enter=t=>{N.has(t.installPath)||(N.add(t.installPath),F.push(t.installPath))};for(let t of n){let n=C.get(`node_modules/${t}`);n&&enter(n)}for(;F.length>0;){let t=F.pop();if(t===void 0)break;let n=C.get(t);if(n)for(let[S]of[...requiredDepEntries(n),...requiredPeerEntries(n)]){let n=findVisible(t,S,C);n&&enter(n)}}let I=0;for(let n of t){let t=!N.has(n.installPath);(n.optional??!1)!==t&&I++,n.optional=t}S(`install: optionality fixpoint — %d of %d node(s) reachable only via optional edges%s`,t.length-N.size,t.length,I>0?`; corrected ${I} incoming flag(s)`:``)}function reachableInstallPaths(t,n){let S=new Map;for(let n of t)S.set(n.installPath,n);let C=new Set,N=[],enter=t=>{!t||C.has(t.installPath)||(C.add(t.installPath),N.push(t))};for(let t of n)enter(S.get(`node_modules/${t}`));for(let t=N.pop();t;t=N.pop()){let n=[...Object.keys(t.dependencies),...Object.keys(t.optionalDependencies),...requiredPeerEntries(t).map(([t])=>t)];for(let C of n)enter(findVisible(t.installPath,C,S))}return C}function readLockfileNodes(t){let n=readLockfile(t);return n?lockfileToNodes(n):null}function assertRequiredEdgesResolved(t,n){if(n.size===0)return;let S=new Map;for(let n of t)S.set(n.installPath,n);for(let t of n){let{from:n,name:C}=parseEdgeKey(t);if(n===null)continue;let N=S.get(n);if(N&&!N.optional&&!(C in N.optionalDependencies))throw Error(`install: required dependency ${C} of ${N.name}@${N.version} (${N.installPath}) could not be resolved.\nThe failure was tolerated during the walk because ${N.name} looked optional at that point, but the final dependency graph makes it required — so ${C} is required too and the tree would be incomplete.\nRe-run with --verbose and look for the "resolve: optional dep ${C}@… skipped (…)" line for the underlying cause.`)}}function emitTopLevelConflictWarnings(t,n){for(let[S,C]of t){if(C.size<2)continue;let t=n.get(S);if(!t)continue;let describe=(t,n)=>n.size>0?`${t} (requested by ${[...n].join(`, `)})`:t,N=[],F=[];for(let[n,S]of C){let C;try{C=satisfies(t.version,new
|
|
913
|
+
`}${pL}\n${fL}\n`),`added`}function removeLocalIgnore(t){let n=resolveGitDir(t);if(!n.commonDir)return n.why;let S=xn(n.commonDir,`info`,`exclude`),C;try{C=readFileSync(S,`utf-8`)}catch{return`absent`}let N=C.split(/\r?\n/),F=[],I=!1;for(let t=0;t<N.length;t++){if(!I&&N[t]?.trim()===pL&&(N[t+1]?.trim()===`.gjsify-link.json`||N[t+1]?.trim()===`/.gjsify-link.json`)){t++,I=!0;continue}F.push(N[t]??``)}return I?(writeFileSync(S,F.join(`
|
|
914
|
+
`)),`removed`):`absent`}function fileMentionsPattern(t,n){let S;try{S=readFileSync(t,`utf-8`)}catch{return!1}return S.split(/\r?\n/).some(t=>{let S=t.trim();return S===n||S===`/${n}`})}function resolveGitDir(t){let n=xn(t,`.git`),S;try{S=statSync(n)}catch{return{commonDir:null,why:`no-git`}}if(S.isDirectory())return{commonDir:n,why:`no-git`};let C;try{C=readFileSync(n,`utf-8`).trim()}catch{return{commonDir:null,why:`unreadable-git`}}let N=/^gitdir:\s*(.+)$/.exec(C)?.[1]?.trim();return N?followCommondir(bn(N)?N:vn(t,N)):{commonDir:null,why:`unreadable-git`}}function followCommondir(t){let n=xn(t,`commondir`);if(!existsSync(n))return{commonDir:t,why:`no-git`};let S;try{S=readFileSync(n,`utf-8`)}catch{return{commonDir:null,why:`unreadable-git`}}let C=S.trim();if(!C)return{commonDir:null,why:`unreadable-git`};let N=bn(C)?C:vn(t,C);return existsSync(N)?{commonDir:N,why:`no-git`}:{commonDir:null,why:`unreadable-git`}}function assertNoDevLinkUnderImmutable(t){let n=devLinkRoot(t),S=devLinkPath(n);if(!existsSync(S))return;let C=`(unreadable)`;try{C=readDevLinkOverride(n)?.checkout??C}catch{}throw Error(`gjsify install --immutable: a development link override is active — ${S}\nIt points at ${C}, so this install would build from a local checkout instead of what ${xn(n,`gjsify-lock.json`)} pins. --immutable builds only what is committed.\nRun \`gjsify unlink\` (in ${n}) or delete ${fL}, then re-run.`)}var fL,pL,mL=__esmMin(()=>{Md(),jn(),OP(),iL(),kP(),dL(),AP(),fL=`.gjsify-link.json`,pL=`# gjsify link — local development override, never commit`}),hL=__exportAll$5({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,parseSpecName:()=>parseSpecName,pickVersion:()=>pickVersion,reachableInstallPaths:()=>reachableInstallPaths,readLockfileNodes:()=>readLockfileNodes,requiredDepEntries:()=>requiredDepEntries,requiredPeerEntries:()=>requiredPeerEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(t){if(assertNativeBackendNodeVersion(),t.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(t.prefix,{recursive:!0});let n=await loadNpmrc$1(t),S=makeLogger(t.verbose??!1),C=await acquireInstallLock(t.prefix,{signal:t.signal});try{return await installPackagesNativeLocked(t,n,S)}finally{C.release()}}async function installPackagesNativeLocked(t,n,S){let C=t.progress,N=xn(t.prefix,_L),F=readLockfile(N),I=resolveHostPlatform(),H=readPlatformForce(process.env);S(`install: platform target %s%s`,describePlatformTarget(I),H?` (--force: checks bypassed)`:``);let W,q=!1,Y=new Set;if(t.frozen||t.focusSpecs){let n=t.frozen?`--immutable`:`--focus`,C=t.frozen?`(without --immutable)`:`(without --focus)`;if(!F)throw Error(`install: ${n} requires ${_L} at ${t.prefix} — none found. Run \`gjsify install\` ${C} to generate one and commit it.`);let I=describeLockfileDrift(F,t.specs);if(I)throw Error(`install: ${n} but ${N} is stale.\n${I}\nRe-run \`gjsify install\` ${C} to refresh the lockfile.`);if(S(`install: %s, using lockfile (%d package(s))`,n,Object.keys(F.packages).length),W=lockfileToNodes(F),t.frozen&&assertNoExtraneous(t.prefix,W),t.focusSpecs){let n=reachableInstallPaths(W,t.focusSpecs.map(parseSpecName));S(`install: --focus keeps %d of %d lockfile package(s)`,n.size,W.length),W=W.filter(t=>n.has(t.installPath))}}else if(!t.refreshLockfile&&F&&F.lockfileVersion===vL&&F.peersResolved===!0&&lockfileMatchesRequest(F,t.specs))S(`install: using lockfile (%d package(s))`,Object.keys(F.packages).length),W=lockfileToNodes(F);else{let N=!t.refreshLockfile&&F?buildPreferredVersions(F):void 0;S(`install: resolving %d top-level spec(s) → %s%s`,t.specs.length,t.prefix,N?` (preserving ${N.size} locked name(s))`:``);let I=await resolveDeps(t.specs,n,S,t.overrides,t.skipDeps,t.signal,C,N,t.workspaceNames,t.specOrigins,t.optionalSpecs);W=I.nodes,Y=I.skippedEdges,q=!0}computeOptionalFlags(W,requiredTopLevelNames(t.focusSpecs??t.specs,t.optionalSpecs),S),assertRequiredEdgesResolved(W,Y),q&&t.lockfile&&(writeLockfile(N,t.specs,W),S(`install: wrote %s (%d entries)`,_L,W.length));let X=W;if(t.workspaceNames&&t.workspaceNames.size>0){let n=X.length;X=X.filter(n=>!t.workspaceNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d workspace-provided package(s) symlinked, not fetched`,C)}if(t.linkedNames&&t.linkedNames.size>0){let n=X.length;X=X.filter(n=>!t.linkedNames.has(n.name));let C=n-X.length;C>0&&S(`install: %d dev-linked package(s) provided by a local checkout, not fetched`,C)}let Z=applyPlatformFilter(X,I,H,S);return S(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,t.prefix,n,S,t.signal,C),await linkBins(Z,t.prefix,S),warnMissingNativeBuilds(Z,t.prefix,S),S(`install: done`),topLevelResolutions(t.specs,W)}function assertNoExtraneous(t,n){let S=findExtraneous({prefix:t,installed:scanPrefix(t),expected:n});if(S.length!==0)throw Error(formatExtraneousError(S,t))}function errMsg(t){return t instanceof Error?t.message:String(t)}function applyPlatformFilter(t,n,S,C){let N=[],F=0;for(let I of t){let t=I.platform;if(!t||!declaresPlatform(t)){N.push(I);continue}let H=checkPlatform(t,n);if(H.ok){N.push(I);continue}let W=`${I.name}@${I.version}`;if(!I.optional){if(S){C(`platform-forced: %s (required, incompatible, installed anyway via --force)`,W),N.push(I);continue}throw badPlatformError(W,H)}I.inert=!0,F++,C(`platform-skip: %s (%s) current=%s required=%s`,W,I.installPath,JSON.stringify(H.current),JSON.stringify(H.required))}return F>0&&C(`install: %d optional package(s) inert — not installable on %s`,F,describePlatformTarget(n)),N}function warnMissingNativeBuilds(t,n,S){let C=process.platform,N=process.arch,F=[`preinstall`,`install`,`postinstall`];for(let I of t){let t=xn(n,I.installPath),H;try{H=JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))?.scripts}catch{continue}if(!H||typeof H!=`object`)continue;let W=F.find(t=>typeof H[t]==`string`);if(W===void 0)continue;let q=!1;try{let n=xn(t,`prebuilds`);for(let t of readdirSync(n))if(t.startsWith(`${C}-`)&&readdirSync(xn(n,t)).length>0){q=!0;break}}catch{}if(!q)try{q=readdirSync(xn(t,`build`,`Release`)).some(t=>t.endsWith(`.node`)||t.endsWith(`.so`))}catch{}q||S("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",I.name,W,C,N,I.installPath,C,N)}}function topLevelResolutions(t,n){let S=new Map;for(let t of n)t.installPath===`node_modules/${t.name}`&&S.set(t.name,t);let C=[];for(let n of t){let t=parseSpecName(n),N=S.get(t);N&&C.push({name:N.name,version:N.version})}return C}function parseSpecName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n===-1)return t;let S=t.indexOf(`@`,n+1);return S===-1?t:t.slice(0,S)}let n=t.indexOf(`@`);return n===-1?t:t.slice(0,n)}async function resolveDeps(t,n,S,C,N,F,I,H,W,q,Y){I?.beginPhase(`resolve`,t.length);let applyOverride=(t,n)=>{if(!C)return n;let N=C[t];return typeof N!=`string`||N.length===0||N===n?n:(S(`install: override %s %s → %s`,t,n,N),N)},X=new Map,fetchPkg=t=>{let C=X.get(t);if(C)return C;let N=fetchPackumentWithDiskCache(t,n,S,F,`full`);return X.set(t,N),N},Z=new Map,te=new Map,ne=new Set,re=new Map,ie=t.map(parseSpec$1).map(t=>{let n=applyOverride(t.name,t.range),S=re.get(t.name);S||(S=new Map,re.set(t.name,S));let C=S.get(n);C||(C=new Set,S.set(n,C));for(let n of q?.get(`${t.name}@${t.range}`)??[])C.add(n);return{from:null,name:t.name,range:n,required:!Y?.has(t.name)}});for(;ie.length>0;){let t=ie.splice(0,ie.length),n=[],C=new Set;for(let S of t)X.has(S.name)||C.has(S.name)||(C.add(S.name),n.push(S.name));await prefetchPackuments(n,fetchPkg,F);for(let n=0;n<t.length;n++){let C=t[n];if(W?.has(C.name))continue;let F=findVisible(C.from,C.name,Z);if(F&&satisfiesRange(F.version,C.range))continue;if(C.peerOf){let t=C.from===null?`node_modules/${C.name}`:`${C.from}/node_modules/${C.name}`,n=Z.get(t);if(n){ge.warn(`[gjsify] warning: peer dependency conflict: ${C.peerOf.name}@${C.peerOf.version} wants ${C.name}@${C.range}, but ${n.version} is installed at ${n.installPath} — keeping it (npm's non-strict behaviour).`);continue}}let q=null;try{let F=await fetchPkg(C.name),W=preferredVersionFor(H?.get(C.name),C.range);if(q=pickVersion(F,C.range,W),!q)throw Error(`No version of ${C.name} satisfies ${C.range}`);let Y=F.versions[q];if(!Y)throw Error(`Packument for ${C.name} promised ${q} but no entry exists`);let X=decidePlacement(C.from,C.name,q,te),ne={name:C.name,version:q,tarballUrl:Y.dist.tarball,integrity:Y.dist.integrity,installPath:X,dependencies:Y.dependencies??{},optionalDependencies:Y.optionalDependencies??{},peerDependencies:nonEmpty(Y.peerDependencies),peerDependenciesMeta:nonEmpty(Y.peerDependenciesMeta),bin:Y.bin,platform:platformDeclarationOf(Y),optional:!C.required};if(Z.set(X,ne),X===`node_modules/${C.name}`&&te.set(C.name,ne),S(`resolve: %s@%s ← %s (at %s)`,C.name,q,C.range,X),I?.update({phase:`resolve`,current:Z.size,total:Z.size+(t.length-n-1)+ie.length,name:`${C.name}@${q}`}),!N){let t=parentInstallPath(X);for(let[n,S]of requiredPeerEntries(ne))ie.push({from:t,name:n,range:applyOverride(n,S),required:!ne.optional,peerOf:ne});for(let[t,n]of requiredDepEntries(ne))ie.push({from:X,name:t,range:applyOverride(t,n),required:!ne.optional});for(let[t,n]of Object.entries(ne.optionalDependencies))ie.push({from:X,name:t,range:applyOverride(t,n),required:!1})}}catch(t){if(!C.required){ne.add(edgeKey(C.peerOf?.installPath??C.from,C.name)),S(`resolve: optional dep %s@%s skipped (%s)`,C.name,C.range,errMsg(t));continue}throw t}}}return I?.endPhase(`resolve`),emitTopLevelConflictWarnings(re,te),{nodes:Array.from(Z.values()),skippedEdges:ne}}function platformDeclarationOf(t){let n={os:t.os,cpu:t.cpu,libc:t.libc};return declaresPlatform(n)?n:void 0}function edgeKey(t,n){return`${t??``}\n${n}`}function parseEdgeKey(t){let n=t.indexOf(`
|
|
915
|
+
`),S=t.slice(0,n);return{from:S===``?null:S,name:t.slice(n+1)}}function requiredTopLevelNames(t,n){let S=new Set;for(let C of t){let t=parseSpecName(C);n?.has(t)||S.add(t)}return S}function requiredDepEntries(t){let n=[];for(let[S,C]of Object.entries(t.dependencies))S in t.optionalDependencies||n.push([S,C]);return n}function requiredPeerEntries(t){let n=[];for(let[S,C]of Object.entries(t.peerDependencies??{}))t.peerDependenciesMeta?.[S]?.optional!==!0&&(S in t.dependencies||S in t.optionalDependencies||n.push([S,C]));return n}function computeOptionalFlags(t,n,S){let C=new Map;for(let n of t)C.set(n.installPath,n);let N=new Set,F=[],enter=t=>{N.has(t.installPath)||(N.add(t.installPath),F.push(t.installPath))};for(let t of n){let n=C.get(`node_modules/${t}`);n&&enter(n)}for(;F.length>0;){let t=F.pop();if(t===void 0)break;let n=C.get(t);if(n)for(let[S]of[...requiredDepEntries(n),...requiredPeerEntries(n)]){let n=findVisible(t,S,C);n&&enter(n)}}let I=0;for(let n of t){let t=!N.has(n.installPath);(n.optional??!1)!==t&&I++,n.optional=t}S(`install: optionality fixpoint — %d of %d node(s) reachable only via optional edges%s`,t.length-N.size,t.length,I>0?`; corrected ${I} incoming flag(s)`:``)}function reachableInstallPaths(t,n){let S=new Map;for(let n of t)S.set(n.installPath,n);let C=new Set,N=[],enter=t=>{!t||C.has(t.installPath)||(C.add(t.installPath),N.push(t))};for(let t of n)enter(S.get(`node_modules/${t}`));for(let t=N.pop();t;t=N.pop()){let n=[...Object.keys(t.dependencies),...Object.keys(t.optionalDependencies),...requiredPeerEntries(t).map(([t])=>t)];for(let C of n)enter(findVisible(t.installPath,C,S))}return C}function readLockfileNodes(t){let n=readLockfile(t);return n?lockfileToNodes(n):null}function assertRequiredEdgesResolved(t,n){if(n.size===0)return;let S=new Map;for(let n of t)S.set(n.installPath,n);for(let t of n){let{from:n,name:C}=parseEdgeKey(t);if(n===null)continue;let N=S.get(n);if(N&&!N.optional&&!(C in N.optionalDependencies))throw Error(`install: required dependency ${C} of ${N.name}@${N.version} (${N.installPath}) could not be resolved.\nThe failure was tolerated during the walk because ${N.name} looked optional at that point, but the final dependency graph makes it required — so ${C} is required too and the tree would be incomplete.\nRe-run with --verbose and look for the "resolve: optional dep ${C}@… skipped (…)" line for the underlying cause.`)}}function emitTopLevelConflictWarnings(t,n){for(let[S,C]of t){if(C.size<2)continue;let t=n.get(S);if(!t)continue;let describe=(t,n)=>n.size>0?`${t} (requested by ${[...n].join(`, `)})`:t,N=[],F=[];for(let[n,S]of C){let C;try{C=satisfies(t.version,new TP(n))}catch{continue}(C?N:F).push(describe(n,S))}F.length!==0&&ge.warn(`[gjsify] warning: version conflict for ${S}: installed ${t.version} at ${t.installPath} — does NOT satisfy ${F.join(`, `)}`+(N.length>0?`; satisfies ${N.join(`, `)}`:``)+`. One hoisted copy serves all requesters until the per-workspace dedup pass lands (Phase D.8).`)}}async function fetchPackumentWithDiskCache(t,n,S,C,N=`corgi`){let F=registryFor(t,n),I=N===`full`,H=getCachedPackument(F,t,N),onRetry=({attempt:n,error:C,delayMs:F})=>{S(`packument %s (%s): retry %d after %dms (%s)`,t,N,n,F,errMsg(C))},W=await fetchPackumentConditional(t,{npmrc:n,signal:C,ifNoneMatch:H?.etag,fullMetadata:I,onRetry});return W.status===`not-modified`&&H?(S(`packument-cache-hit: %s (%s, 304, etag %s)`,t,N,H.etag),H.packument):W.status===`fresh`&&W.packument?(W.etag&&putCachedPackument(F,t,W.etag,W.packument,N),W.packument):fetchPackument(t,{npmrc:n,signal:C,fullMetadata:I,onRetry})}async function prefetchPackuments(t,n,S){if(t.length===0)return;let C=0,N=Math.max(1,Math.min(gL,t.length)),worker=async()=>{for(;C<t.length;){if(S?.aborted)return;let N=t[C++];try{await n(N)}catch{}}};await Promise.all(Array.from({length:N},()=>worker()))}function findVisible(t,n,S){let C=[];if(t!==null){C.push(`${t}/node_modules/${n}`);let S=t;for(;;){let t=S.lastIndexOf(`/node_modules/`);if(t<0||(S=S.slice(0,t),C.push(`${S}/node_modules/${n}`),S===``))break}}C.push(`node_modules/${n}`);for(let t of C){let n=S.get(t);if(n)return n}return null}function parentInstallPath(t){let n=t.lastIndexOf(`/node_modules/`);return n<0?null:t.slice(0,n)}function decidePlacement(t,n,S,C){let N=C.get(n);return!N||N.version===S||t===null?`node_modules/${n}`:`${t}/node_modules/${n}`}function satisfiesRange(t,n){try{return satisfies(t,new TP(n))}catch{return!1}}function readLockfile(t){if(!existsSync(t))return null;try{let n=JSON.parse(readFileSync(t,`utf-8`));return!yL.has(n.lockfileVersion)||!n.packages||typeof n.packages!=`object`?null:n}catch{return null}}function writeLockfile(t,n,S){let C={},N=[...S].sort((t,n)=>t.installPath<n.installPath?-1:+(t.installPath>n.installPath));for(let t of N)C[t.installPath]={version:t.version,resolved:t.tarballUrl,integrity:t.integrity,dependencies:Object.keys(t.dependencies).length>0?t.dependencies:void 0,optionalDependencies:Object.keys(t.optionalDependencies).length>0?t.optionalDependencies:void 0,peerDependencies:nonEmpty(t.peerDependencies),peerDependenciesMeta:nonEmpty(t.peerDependenciesMeta),bin:t.bin,os:t.platform?.os,cpu:t.platform?.cpu,libc:t.platform?.libc,optional:t.optional?!0:void 0};let F={lockfileVersion:vL,requested:[...n],packages:C,peersResolved:!0};atomicWriteStrict(t,JSON.stringify(F,null,2)+`
|
|
916
916
|
`)}function nonEmpty(t){return t&&Object.keys(t).length>0?t:void 0}function buildPreferredVersions(t){let n=new Map;for(let[S,C]of Object.entries(t.packages)){let t=nameFromInstallPath(S),N=n.get(t);N||(N=new Set,n.set(t,N)),N.add(C.version)}return n}function preferredVersionFor(t,n){if(!t||t.size===0)return;let S;for(let C of t)satisfiesRange(C,n)&&(S===void 0||new SemVer(C).compare(new SemVer(S))>0)&&(S=C);return S}function lockfileToNodes(t){return Object.entries(t.packages).map(([t,n])=>{let S={os:n.os,cpu:n.cpu,libc:n.libc};return{name:nameFromInstallPath(t),version:n.version,tarballUrl:n.resolved,integrity:n.integrity,installPath:t,dependencies:n.dependencies??{},optionalDependencies:n.optionalDependencies??{},peerDependencies:n.peerDependencies,peerDependenciesMeta:n.peerDependenciesMeta,bin:n.bin,platform:declaresPlatform(S)?S:void 0,optional:n.optional===!0}})}function nameFromInstallPath(t){let n=t.lastIndexOf(`/node_modules/`);return n<0?t.replace(/^node_modules\//,``):t.slice(n+14)}function lockfileMatchesRequest(t,n){if(t.requested.length!==n.length)return!1;let S=[...t.requested].sort(),C=[...n].sort();return S.every((t,n)=>t===C[n])}function describeLockfileDrift(t,n){let S=new Set(t.requested),C=new Set(n),N=[],F=[];for(let t of C)S.has(t)||N.push(t);for(let t of S)C.has(t)||F.push(t);if(N.length===0&&F.length===0)return null;let I=[];return N.length>0&&I.push(` + ${N.sort().join(`
|
|
917
917
|
+ `)}`),F.length>0&&I.push(` - ${F.sort().join(`
|
|
918
918
|
- `)}`),I.join(`
|
|
919
|
-
`)}function parseSpec$1(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw Error(`Invalid spec (scoped name without slash): ${t}`);let S=t.indexOf(`@`,n);return S<0?{name:t,range:`latest`}:{name:t.slice(0,S),range:t.slice(S+1)||`latest`}}let n=t.indexOf(`@`);return n<0?{name:t,range:`latest`}:{name:t.slice(0,n),range:t.slice(n+1)||`latest`}}function pickVersion(t,n,S){if(S&&t.versions[S]&&satisfiesRange(S,n))return S;if(t[`dist-tags`][n])return t[`dist-tags`][n];let C;try{C=new wP(n)}catch{throw Error(`Invalid version range for ${t.name}: ${n}`)}return maxSatisfying(Object.keys(t.versions).filter(t=>{try{return new SemVer(t),!0}catch{return!1}}),C)}async function downloadAndExtractAll(t,n,S,C,N,F){let I=[...t].sort((t,n)=>depth$1(t.installPath)-depth$1(n.installPath)||(t.installPath<n.installPath?-1:1)),H=[],W=Math.max(1,Math.min(hL,I.length));F?.beginPhase(`download`,I.length);let q=0,Y=0,tickProgress=(t,n)=>{q++,n&&Y++,F?.update({phase:`download`,current:q,total:I.length,name:`${t.name}@${t.version}`})},X=0,Z=I.findIndex(t=>depth$1(t.installPath)>1),te=Z<0?I.length:Z;for(;X<te;){if(N?.aborted)throw abortError(N);let t=I[X++];if(!t)break;tickProgress(t,await extractOne(t,n,S,C,N))}for(let t=0;t<W;t++)H.push((async()=>{for(;;){if(N?.aborted)throw abortError(N);let t=X++;if(t>=I.length)return;let F=I[t];if(!F)return;let H=await extractOne(F,n,S,C,N);tickProgress(F,H)}})());await Promise.all(H),F?.endPhase(`download`),Y>0&&C(`install: %d/%d package(s) already up to date — extracted %d`,Y,I.length,I.length-Y)}function isAlreadyExtracted(t,n){let S=xn(t,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{return!1}try{let t=JSON.parse(C);return!(t.version!==n.version||typeof t.name==`string`&&t.name!==n.name)}catch{return!1}}async function extractOne(t,n,S,C,N){let F=xn(n,t.installPath);if(assertNodeModulesDest(F,t,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(F,t))return C(`up-to-date: %s@%s (already extracted at %s)`,t.name,t.version,t.installPath),!0;let I=await getCachedTarball(t.integrity);return I?C(`cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity):(I=await getForeignCachedTarball(t.integrity))?(C(`npm-cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity),putCachedTarball(t.integrity,I)):(C(`fetch: %s@%s ← %s (→ %s)`,t.name,t.version,t.tarballUrl,t.installPath),I=await fetchTarball(t.tarballUrl,{npmrc:S,signal:N,integrity:t.integrity,onRetry:({attempt:n,error:S,delayMs:N})=>{C(`tarball %s@%s: retry %d after %dms (%s)`,t.name,t.version,n,N,errMsg(S))}}),putCachedTarball(t.integrity,I)),rmWithRetry(F),mkdirSync(F,{recursive:!0}),await extractWithStallGuard(I,F,t,N),!1}async function extractWithStallGuard(t,n,S,C){if(yL===0&&!C){await extractTarball(t,n);return}let N,onAbort;try{await new Promise((F,I)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(t,n).then(()=>F(),I),yL>0&&(N=setTimeout(()=>{I(Error(`gjsify install: extract of ${S.name}@${S.version} stalled for ${Math.round(yL/1e3)}s (${S.installPath}) — the tarball decompress/write never completed. This is usually a dropped Gio stream event under GJS; re-run the install. Override the cap with GJSIFY_EXTRACT_STALL_MS=<ms> (0 disables it).`))},yL),N.unref?.()),C){if(C.aborted){I(abortError(C));return}onAbort=()=>I(abortError(C)),C.addEventListener(`abort`,onAbort,{once:!0})}})}finally{N&&clearTimeout(N),C&&onAbort&&C.removeEventListener(`abort`,onAbort)}}function abortError(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}function assertNodeModulesDest(t,n,S){if(!t.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} into ${t} — target is not inside a node_modules/ directory. This would overwrite working-tree files. A workspace package likely leaked into the fetch queue (it must be symlinked, not fetched).`);let C;try{C=realpathSync(t)}catch{return}if(!C.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} — ${t} resolves to ${C}, which is outside any node_modules/ directory (likely a symlink to a workspace source tree). Extracting here would delete working-tree source files.${devLinkRemedy(S,t)}`)}function devLinkRemedy(t,n){let S=devLinkRoot(t),C=devLinkPath(S);return`\n If a \`gjsify link\` development link put it there${existsSync(C)?` — ${C} is present`:``}: run \`gjsify unlink\` in ${S} to remove the links and restore the registry copies, or \`gjsify link <checkout> --packages …\` to re-select. If no override is left, delete ${n} by hand and re-run.`}function depth$1(t){return t.split(`/node_modules/`).length}function readShebang$1(t){let n;try{n=readFileSync(t,`utf-8`)}catch{return null}return parseShebang(n.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(t){let{binDir:n,binName:S,targetAbs:C,gjs:N,nodeFallbackAbs:F}=t,I=t.platform??process.platform,H=xn(n,S);if(N){let t=isGjsBundlePath(C);for(let t of[H,`${H}.cmd`,`${H}.ps1`])rmWithRetry(t);writeFileSync(H,buildShLauncher(C,{envPreamble:N.envPreamble,isGjsBundle:t,nodeFallbackAbs:F}));try{chmodSync(H,493)}catch{}if(I===`win32`&&t){let t=N.prebuildDirs.join(`;`),n=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:C,prependEnv:N.prebuildDirs.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},fallback:F===void 0?void 0:{interpreter:`node`,target:F}});writeFileSync(`${H}.cmd`,n.cmd),writeFileSync(`${H}.ps1`,n.ps1)}return}if(I===`win32`){let{sh:t,cmd:S,ps1:N}=buildCmdShim(Sn(n,C).split(`\\`).join(`/`),readShebang$1(C));for(let[n,C]of[[H,t],[`${H}.cmd`,S],[`${H}.ps1`,N]]){rmWithRetry(n),writeFileSync(n,C);try{chmodSync(n,493)}catch{}}return}rmWithRetry(H);let W=Sn(n,C);try{symlinkSync(W,H)}catch{copyFileSync(C,H),chmodSync(H,493)}}async function linkBins(t,n,S){let C=xn(n,`node_modules`,`.bin`),N=0,F,gjsEnvForPrefix=()=>{if(F===void 0){let t=detectNativePackages(n).map(t=>t.prebuildsDir);F={envPreamble:buildNativeEnvPreamble(n,t),prebuildDirs:t}}return F};for(let S of t){if(depth$1(S.installPath)!==1)continue;let t=xn(n,S.installPath),F=readInstalledManifest(t)??(S.bin===void 0?null:{bin:S.bin});if(F===null)continue;let I=pickBinMap(S.name,F);if(!(I===null||I.map.size===0)){mkdirSync(C,{recursive:!0});for(let[n,S]of I.map){let F=xn(t,S);if(!existsSync(F))continue;try{chmodSync(F,493)}catch{}let H=I.nodeFallback?.get(n),W=H===void 0?void 0:xn(t,H);writeBinEntry({binDir:C,binName:n,targetAbs:F,gjs:I.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:W!==void 0&&existsSync(W)?W:void 0}),N++}}}N>0&&S(`bin: linked %d entry(ies) under .bin/`,N)}function readInstalledManifest(t){try{let n=readFileSync(xn(t,`package.json`),`utf-8`);return JSON.parse(n)}catch{return null}}function rmWithRetry(t){rmSync(t,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(t){let n=homedir(),S={registry:t.registry??Vm,scopes:{},authTokens:{},basicAuth:{}};for(let C of[xn(n,`.npmrc`),xn(t.prefix,`.npmrc`)])if(existsSync(C))try{let t=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...t,scopes:{...S.scopes,...t.scopes}}}catch(t){ge.warn(`gjsify install: ignoring malformed ${C}: ${t.message}`)}let C=process.env.npm_config_registry;return C&&(S.registry=C),t.registry&&(S.registry=t.registry),S}function makeLogger(t){return t?(t,...n)=>{let S=t.replace(/%s|%d/g,()=>String(n.shift()));process.stderr.write(`gjsify install: ${S}\n`)}:()=>{}}var hL,gL,_L,vL,yL,bL=__esmMin(()=>{_e(),Md(),jn(),Dg(),TP(),Jm(),LI(),OI(),JI(),XI(),QI(),$I(),uI(),QP(),eL(),pL(),uL(),cL(),hL=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,gL=`gjsify-lock.json`,_L=4,vL=new Set([2,3,_L]),__name$1(parseSpec$1,`parseSpec`),yL=(()=>{let t=process.env.GJSIFY_EXTRACT_STALL_MS;if(t===void 0)return 12e4;let n=Number(t);return Number.isFinite(n)&&n>=0?n:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),xL=__exportAll$5({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(t){if(SL===`npm`)return await installViaNpm(t),{installed:[]};let{installPackagesNative:n}=await Promise.resolve().then(()=>(bL(),mL));return{installed:await n(t)}}async function installViaNpm({prefix:t,specs:n,verbose:S,registry:C}){if(n.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(xn(t,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),C&&writeFileSync(xn(t,`.npmrc`),`registry=${C}\n`);let{code:N}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,t,...S?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...n],{completion:`return`,notFound:t=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${t.message})`)});if(N!==0)throw Error(`npm install exited with code ${N}`)}var SL,CL=__esmMin(()=>{Md(),jn(),j_(),MI(),SL=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let t=process.env.GJSIFY_GLOBAL_PREFIX,n=process.env.GJSIFY_GLOBAL_BIN_DIR,S=homedir(),C=process.env.XDG_DATA_HOME??xn(S,`.local`,`share`);return{prefix:t??xn(C,`gjsify`,`global`),binDir:n??xn(S,`.local`,`bin`)}}function hasBundlerEngineInstalled(t){let n=new Set(detectNativePackages(t).map(t=>t.name));if(n.has(`@gjsify/rolldown-native`))return!0;let S=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,S).some(t=>n.has(platformPackageName(TL,t)))}async function installGjsEnginePackages(t,n,S={}){let C=S.verbose??!1,N=S.installFn??(async n=>{let{installPackages:S}=await Promise.resolve().then(()=>(CL(),xL));await S({prefix:t,specs:[n],verbose:C})});for(let t of wL){let S=n?`${t}@${n}`:t;try{await N(S)}catch(S){let N=S instanceof Error?S.message:String(S);t===`@gjsify/rolldown-native`?ge.warn(`\nWarning: could not install the GJS bundler engine ${t}@${n} — ${N}\n \`gjsify build\` (and storybook / flatpak) will fail under GJS until it is present.\n This usually means no prebuild is published for this platform (${process.platform}/${process.arch}).`):C&&ge.warn(`gjsify install: optional GJS engine ${t}@${n} not installed — ${N}`)}}}function linkGlobalBins(t,n){mkdirSync(n.binDir,{recursive:!0});let S=[],C=detectNativePackages(n.prefix).map(t=>t.prebuildsDir),N=buildNativeEnvPreamble(n.prefix,C);for(let F of t){let t=xn(n.prefix,`node_modules`,F),I=xn(t,`package.json`);if(!existsSync(I))continue;let H=pickBinMap(F,readJson(I));if(!(H===null||H.map.size===0))for(let[F,I]of H.map){let W=xn(t,I);if(!existsSync(W))continue;try{chmodSync(W,493)}catch{}let q=xn(n.binDir,F);for(let t of[q,`${q}.cmd`,`${q}.ps1`])rmSync(t,{force:!0,maxRetries:10,retryDelay:100});let Y=isGjsBundlePath(W),X=H.nodeFallback?.get(F),Z=X===void 0?void 0:xn(t,X),te=Z!==void 0&&existsSync(Z)?Z:void 0;if(writeFileSync(q,buildShLauncher(W,{envPreamble:N,isGjsBundle:Y,nodeFallbackAbs:te})),chmodSync(q,493),process.platform===`win32`){let t=C.join(`;`),n=Y&&C.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},S=Y?null:readShebangOf(W),N=buildLauncherShims(Y?{interpreter:`gjs`,interpreterArgs:[`-m`],target:W,prependEnv:n,fallback:te===void 0?void 0:{interpreter:`node`,target:te}}:{interpreter:S?.prog||`node`,interpreterArgs:S?.args.trim()?S.args.trim().split(/\s+/):[],target:W});writeFileSync(`${q}.cmd`,N.cmd),writeFileSync(`${q}.ps1`,N.ps1)}S.push({name:F,target:W,link:q})}}return S}function readShebangOf(t){try{return parseShebang(readFileSync(t,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(t){return JSON.parse(readFileSync(t,`utf-8`))}function globalLayoutIsDefault(t=process.env){return!t.GJSIFY_GLOBAL_PREFIX&&!t.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(t){return t===`win32`?fn:un}function searchPathEntries(t,n){let S=pathFor$1(n),C=n===`win32`?`;`:`:`;return t.split(C).filter(Boolean).map(t=>S.resolve(t))}function binDirOnPath(t){let n=pathFor$1(process.platform).resolve(t);return searchPathEntries(process.env.PATH??``,process.platform).includes(n)}function resolveBinOnPath(t,n={}){let S=n.platform??process.platform,C=n.pathValue??process.env.PATH??``,N=n.exists??existsSync,F=S===`win32`?[...(n.pathExt??process.env.PATHEXT??EL).split(`;`).filter(Boolean).map(t=>t.startsWith(`.`)?t:`.${t}`),``]:[``],I=pathFor$1(S);for(let n of searchPathEntries(C,S))for(let S of F){let C=I.join(n,`${t}${S}`);if(N(C))return C}return null}function specToPackageName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)return t;let S=t.indexOf(`@`,n);return S<0?t:t.slice(0,S)}let n=t.indexOf(`@`);return n<0?t:t.slice(0,n)}var wL,TL,EL,DL=__esmMin(()=>{_e(),Md(),Dg(),jn(),QP(),uI(),wL=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],TL=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),EL=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return kL}function pathWithoutSelfShim(t=process.env.PATH??``,n=process.env.GJSIFY_SHIM_DIR,S=kn){return n?t.split(S).filter(t=>t!==n).join(S):t}function needsSelfShim(t){if(t.gjs)return!0;let n=Sn(t.workspaceRoot,t.selfEntry);return n===``||n.startsWith(`..`)||bn(n)}function ensureGjsifyShimOnPath(){if(OL)return;OL=!0;let t=process.env.GJSIFY_SHIM_DIR;if(t&&existsSync(xn(t,`gjsify`))){kL=!0,(process.env.PATH??``).split(kn).includes(t)||(process.env.PATH=t+kn+(process.env.PATH??``));return}let n=isGjs(),S=fileURLToPath(n?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:n,selfEntry:S,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let C=n?process.env.GJS_CONSOLE||`gjs`:`node`,N=n?selfShimPreamble(S):``,F={gjsify:n?buildShLauncher(S,{isGjsBundle:!0,envPreamble:N,gjs:C}):`#!/bin/sh\nexec "${C}" "${S}" "$@"\n`};if(!n&&process.platform===`win32`){let{cmd:t,ps1:n}=buildLauncherShims({interpreter:C,interpreterArgs:[],target:S});F[`gjsify.cmd`]=t,F[`gjsify.ps1`]=n}let I=buildNodeShim(n,S,N);I&&(F[`${AL}/node`]=I);let H=materializeShimDir(F);kL=!0,process.env.GJSIFY_SHIM_DIR=H,process.env.PATH=H+kn+(process.env.PATH??``)}function materializeShimDir(t,n=gjsifyCacheRoot(`shim`,`v1`)){let S=Object.keys(t).sort(),C=createHash(`sha256`);for(let n of S)C.update(`${n}\0${t[n]}\0`);let N=C.digest(`hex`).slice(0,16);try{return writeShimDir(xn(n,N),t,S)}catch{return writeShimDir(mkdtempSync(xn(tmpdir(),`gjsify-shim-`)),t,S)}}function writeShimDir(t,n,S){for(let C of S){let S=xn(t,C);if(existsSync(S)&&readFileSync(S,`utf8`)===n[C])continue;mkdirSync(wn(S),{recursive:!0});let N=`${S}.tmp.${process.pid}`;try{writeFileSync(N,n[C],{mode:493}),chmodSync(N,493),renameSync(N,S)}catch(t){throw rmSync(N,{force:!0}),t}}return t}function selfShimScanRoot(t){let n=t.search(/[\\/]node_modules[\\/]/);return n>0?t.slice(0,n):findWorkspaceRoot(wn(t))??wn(t)}function selfShimPreamble(t){let n=[];try{n=detectNativePackages(wn(t)).map(t=>t.prebuildsDir)}catch{}return buildNativeEnvPreamble(selfShimScanRoot(t),n)}function dyldCarryPreamble(t,n){return t===`darwin`?Object.keys(n).filter(t=>/^DYLD_[A-Z_]+$/.test(t)&&n[t]).sort().map(t=>`${t}=${shQuoteArg(n[t])}\nexport ${t}\n`).join(``):``}function nodeShimDir(){let t=process.env.GJSIFY_SHIM_DIR;if(!t)return null;let n=xn(t,AL);return existsSync(xn(n,`node`))?n:null}function buildNodeShim(t,n,S){if(!t||resolveBinOnPath(`node`))return null;let C=process.env.GJS_CONSOLE||`gjs`;return`#!/bin/sh
|
|
919
|
+
`)}function parseSpec$1(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw Error(`Invalid spec (scoped name without slash): ${t}`);let S=t.indexOf(`@`,n);return S<0?{name:t,range:`latest`}:{name:t.slice(0,S),range:t.slice(S+1)||`latest`}}let n=t.indexOf(`@`);return n<0?{name:t,range:`latest`}:{name:t.slice(0,n),range:t.slice(n+1)||`latest`}}function pickVersion(t,n,S){if(S&&t.versions[S]&&satisfiesRange(S,n))return S;if(t[`dist-tags`][n])return t[`dist-tags`][n];let C;try{C=new TP(n)}catch{throw Error(`Invalid version range for ${t.name}: ${n}`)}return maxSatisfying(Object.keys(t.versions).filter(t=>{try{return new SemVer(t),!0}catch{return!1}}),C)}async function downloadAndExtractAll(t,n,S,C,N,F){let I=[...t].sort((t,n)=>depth$1(t.installPath)-depth$1(n.installPath)||(t.installPath<n.installPath?-1:1)),H=[],W=Math.max(1,Math.min(gL,I.length));F?.beginPhase(`download`,I.length);let q=0,Y=0,tickProgress=(t,n)=>{q++,n&&Y++,F?.update({phase:`download`,current:q,total:I.length,name:`${t.name}@${t.version}`})},X=0,Z=I.findIndex(t=>depth$1(t.installPath)>1),te=Z<0?I.length:Z;for(;X<te;){if(N?.aborted)throw abortError(N);let t=I[X++];if(!t)break;tickProgress(t,await extractOne(t,n,S,C,N))}for(let t=0;t<W;t++)H.push((async()=>{for(;;){if(N?.aborted)throw abortError(N);let t=X++;if(t>=I.length)return;let F=I[t];if(!F)return;let H=await extractOne(F,n,S,C,N);tickProgress(F,H)}})());await Promise.all(H),F?.endPhase(`download`),Y>0&&C(`install: %d/%d package(s) already up to date — extracted %d`,Y,I.length,I.length-Y)}function isAlreadyExtracted(t,n){let S=xn(t,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{return!1}try{let t=JSON.parse(C);return!(t.version!==n.version||typeof t.name==`string`&&t.name!==n.name)}catch{return!1}}async function extractOne(t,n,S,C,N){let F=xn(n,t.installPath);if(assertNodeModulesDest(F,t,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(F,t))return C(`up-to-date: %s@%s (already extracted at %s)`,t.name,t.version,t.installPath),!0;let I=await getCachedTarball(t.integrity);return I?C(`cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity):(I=await getForeignCachedTarball(t.integrity))?(C(`npm-cache-hit: %s@%s ← %s`,t.name,t.version,t.integrity),putCachedTarball(t.integrity,I)):(C(`fetch: %s@%s ← %s (→ %s)`,t.name,t.version,t.tarballUrl,t.installPath),I=await fetchTarball(t.tarballUrl,{npmrc:S,signal:N,integrity:t.integrity,onRetry:({attempt:n,error:S,delayMs:N})=>{C(`tarball %s@%s: retry %d after %dms (%s)`,t.name,t.version,n,N,errMsg(S))}}),putCachedTarball(t.integrity,I)),rmWithRetry(F),mkdirSync(F,{recursive:!0}),await extractWithStallGuard(I,F,t,N),!1}async function extractWithStallGuard(t,n,S,C){if(bL===0&&!C){await extractTarball(t,n);return}let N,onAbort;try{await new Promise((F,I)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(t,n).then(()=>F(),I),bL>0&&(N=setTimeout(()=>{I(Error(`gjsify install: extract of ${S.name}@${S.version} stalled for ${Math.round(bL/1e3)}s (${S.installPath}) — the tarball decompress/write never completed. This is usually a dropped Gio stream event under GJS; re-run the install. Override the cap with GJSIFY_EXTRACT_STALL_MS=<ms> (0 disables it).`))},bL),N.unref?.()),C){if(C.aborted){I(abortError(C));return}onAbort=()=>I(abortError(C)),C.addEventListener(`abort`,onAbort,{once:!0})}})}finally{N&&clearTimeout(N),C&&onAbort&&C.removeEventListener(`abort`,onAbort)}}function abortError(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}function assertNodeModulesDest(t,n,S){if(!t.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} into ${t} — target is not inside a node_modules/ directory. This would overwrite working-tree files. A workspace package likely leaked into the fetch queue (it must be symlinked, not fetched).`);let C;try{C=realpathSync(t)}catch{return}if(!C.split(On).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${n.name}@${n.version} — ${t} resolves to ${C}, which is outside any node_modules/ directory (likely a symlink to a workspace source tree). Extracting here would delete working-tree source files.${devLinkRemedy(S,t)}`)}function devLinkRemedy(t,n){let S=devLinkRoot(t),C=devLinkPath(S);return`\n If a \`gjsify link\` development link put it there${existsSync(C)?` — ${C} is present`:``}: run \`gjsify unlink\` in ${S} to remove the links and restore the registry copies, or \`gjsify link <checkout> --packages …\` to re-select. If no override is left, delete ${n} by hand and re-run.`}function depth$1(t){return t.split(`/node_modules/`).length}function readShebang$1(t){let n;try{n=readFileSync(t,`utf-8`)}catch{return null}return parseShebang(n.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(t){let{binDir:n,binName:S,targetAbs:C,gjs:N,nodeFallbackAbs:F}=t,I=t.platform??process.platform,H=xn(n,S);if(N){let t=isGjsBundlePath(C);for(let t of[H,`${H}.cmd`,`${H}.ps1`])rmWithRetry(t);writeFileSync(H,buildShLauncher(C,{envPreamble:N.envPreamble,isGjsBundle:t,nodeFallbackAbs:F}));try{chmodSync(H,493)}catch{}if(I===`win32`&&t){let t=N.prebuildDirs.join(`;`),n=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:C,prependEnv:N.prebuildDirs.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},fallback:F===void 0?void 0:{interpreter:`node`,target:F}});writeFileSync(`${H}.cmd`,n.cmd),writeFileSync(`${H}.ps1`,n.ps1)}return}if(I===`win32`){let{sh:t,cmd:S,ps1:N}=buildCmdShim(Sn(n,C).split(`\\`).join(`/`),readShebang$1(C));for(let[n,C]of[[H,t],[`${H}.cmd`,S],[`${H}.ps1`,N]]){rmWithRetry(n),writeFileSync(n,C);try{chmodSync(n,493)}catch{}}return}rmWithRetry(H);let W=Sn(n,C);try{symlinkSync(W,H)}catch{copyFileSync(C,H),chmodSync(H,493)}}async function linkBins(t,n,S){let C=xn(n,`node_modules`,`.bin`),N=0,F,gjsEnvForPrefix=()=>{if(F===void 0){let t=detectNativePackages(n).map(t=>t.prebuildsDir);F={envPreamble:buildNativeEnvPreamble(n,t),prebuildDirs:t}}return F};for(let S of t){if(depth$1(S.installPath)!==1)continue;let t=xn(n,S.installPath),F=readInstalledManifest(t)??(S.bin===void 0?null:{bin:S.bin});if(F===null)continue;let I=pickBinMap(S.name,F);if(!(I===null||I.map.size===0)){mkdirSync(C,{recursive:!0});for(let[n,S]of I.map){let F=xn(t,S);if(!existsSync(F))continue;try{chmodSync(F,493)}catch{}let H=I.nodeFallback?.get(n),W=H===void 0?void 0:xn(t,H);writeBinEntry({binDir:C,binName:n,targetAbs:F,gjs:I.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:W!==void 0&&existsSync(W)?W:void 0}),N++}}}N>0&&S(`bin: linked %d entry(ies) under .bin/`,N)}function readInstalledManifest(t){try{let n=readFileSync(xn(t,`package.json`),`utf-8`);return JSON.parse(n)}catch{return null}}function rmWithRetry(t){rmSync(t,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(t){let n=homedir(),S={registry:t.registry??Vm,scopes:{},authTokens:{},basicAuth:{}};for(let C of[xn(n,`.npmrc`),xn(t.prefix,`.npmrc`)])if(existsSync(C))try{let t=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...t,scopes:{...S.scopes,...t.scopes}}}catch(t){ge.warn(`gjsify install: ignoring malformed ${C}: ${t.message}`)}let C=process.env.npm_config_registry;return C&&(S.registry=C),t.registry&&(S.registry=t.registry),S}function makeLogger(t){return t?(t,...n)=>{let S=t.replace(/%s|%d/g,()=>String(n.shift()));process.stderr.write(`gjsify install: ${S}\n`)}:()=>{}}var gL,_L,vL,yL,bL,xL=__esmMin(()=>{_e(),Md(),jn(),Dg(),EP(),Jm(),RI(),kI(),YI(),ZI(),$I(),eL(),dI(),$P(),tL(),mL(),dL(),lL(),gL=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,_L=`gjsify-lock.json`,vL=4,yL=new Set([2,3,vL]),__name$1(parseSpec$1,`parseSpec`),bL=(()=>{let t=process.env.GJSIFY_EXTRACT_STALL_MS;if(t===void 0)return 12e4;let n=Number(t);return Number.isFinite(n)&&n>=0?n:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),SL=__exportAll$5({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(t){if(CL===`npm`)return await installViaNpm(t),{installed:[]};let{installPackagesNative:n}=await Promise.resolve().then(()=>(xL(),hL));return{installed:await n(t)}}async function installViaNpm({prefix:t,specs:n,verbose:S,registry:C}){if(n.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(xn(t,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),C&&writeFileSync(xn(t,`.npmrc`),`registry=${C}\n`);let{code:N}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,t,...S?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...n],{completion:`return`,notFound:t=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${t.message})`)});if(N!==0)throw Error(`npm install exited with code ${N}`)}var CL,wL=__esmMin(()=>{Md(),jn(),j_(),NI(),CL=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let t=process.env.GJSIFY_GLOBAL_PREFIX,n=process.env.GJSIFY_GLOBAL_BIN_DIR,S=homedir(),C=process.env.XDG_DATA_HOME??xn(S,`.local`,`share`);return{prefix:t??xn(C,`gjsify`,`global`),binDir:n??xn(S,`.local`,`bin`)}}function hasBundlerEngineInstalled(t){let n=new Set(detectNativePackages(t).map(t=>t.name));if(n.has(`@gjsify/rolldown-native`))return!0;let S=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,S).some(t=>n.has(platformPackageName(EL,t)))}async function installGjsEnginePackages(t,n,S={}){let C=S.verbose??!1,N=S.installFn??(async n=>{let{installPackages:S}=await Promise.resolve().then(()=>(wL(),SL));await S({prefix:t,specs:[n],verbose:C})});for(let t of TL){let S=n?`${t}@${n}`:t;try{await N(S)}catch(S){let N=S instanceof Error?S.message:String(S);t===`@gjsify/rolldown-native`?ge.warn(`\nWarning: could not install the GJS bundler engine ${t}@${n} — ${N}\n \`gjsify build\` (and storybook / flatpak) will fail under GJS until it is present.\n This usually means no prebuild is published for this platform (${process.platform}/${process.arch}).`):C&&ge.warn(`gjsify install: optional GJS engine ${t}@${n} not installed — ${N}`)}}}function linkGlobalBins(t,n){mkdirSync(n.binDir,{recursive:!0});let S=[],C=detectNativePackages(n.prefix).map(t=>t.prebuildsDir),N=buildNativeEnvPreamble(n.prefix,C);for(let F of t){let t=xn(n.prefix,`node_modules`,F),I=xn(t,`package.json`);if(!existsSync(I))continue;let H=pickBinMap(F,readJson(I));if(!(H===null||H.map.size===0))for(let[F,I]of H.map){let W=xn(t,I);if(!existsSync(W))continue;try{chmodSync(W,493)}catch{}let q=xn(n.binDir,F);for(let t of[q,`${q}.cmd`,`${q}.ps1`])rmSync(t,{force:!0,maxRetries:10,retryDelay:100});let Y=isGjsBundlePath(W),X=H.nodeFallback?.get(F),Z=X===void 0?void 0:xn(t,X),te=Z!==void 0&&existsSync(Z)?Z:void 0;if(writeFileSync(q,buildShLauncher(W,{envPreamble:N,isGjsBundle:Y,nodeFallbackAbs:te})),chmodSync(q,493),process.platform===`win32`){let t=C.join(`;`),n=Y&&C.length>0?{GI_TYPELIB_PATH:t,PATH:t}:{},S=Y?null:readShebangOf(W),N=buildLauncherShims(Y?{interpreter:`gjs`,interpreterArgs:[`-m`],target:W,prependEnv:n,fallback:te===void 0?void 0:{interpreter:`node`,target:te}}:{interpreter:S?.prog||`node`,interpreterArgs:S?.args.trim()?S.args.trim().split(/\s+/):[],target:W});writeFileSync(`${q}.cmd`,N.cmd),writeFileSync(`${q}.ps1`,N.ps1)}S.push({name:F,target:W,link:q})}}return S}function readShebangOf(t){try{return parseShebang(readFileSync(t,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(t){return JSON.parse(readFileSync(t,`utf-8`))}function globalLayoutIsDefault(t=process.env){return!t.GJSIFY_GLOBAL_PREFIX&&!t.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(t){return t===`win32`?fn:un}function searchPathEntries(t,n){let S=pathFor$1(n),C=n===`win32`?`;`:`:`;return t.split(C).filter(Boolean).map(t=>S.resolve(t))}function binDirOnPath(t){let n=pathFor$1(process.platform).resolve(t);return searchPathEntries(process.env.PATH??``,process.platform).includes(n)}function resolveBinOnPath(t,n={}){let S=n.platform??process.platform,C=n.pathValue??process.env.PATH??``,N=n.exists??existsSync,F=S===`win32`?[...(n.pathExt??process.env.PATHEXT??DL).split(`;`).filter(Boolean).map(t=>t.startsWith(`.`)?t:`.${t}`),``]:[``],I=pathFor$1(S);for(let n of searchPathEntries(C,S))for(let S of F){let C=I.join(n,`${t}${S}`);if(N(C))return C}return null}function specToPackageName(t){if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)return t;let S=t.indexOf(`@`,n);return S<0?t:t.slice(0,S)}let n=t.indexOf(`@`);return n<0?t:t.slice(0,n)}var TL,EL,DL,OL=__esmMin(()=>{_e(),Md(),Dg(),jn(),$P(),dI(),TL=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],EL=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),DL=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return AL}function pathWithoutSelfShim(t=process.env.PATH??``,n=process.env.GJSIFY_SHIM_DIR,S=kn){return n?t.split(S).filter(t=>t!==n).join(S):t}function needsSelfShim(t){if(t.gjs)return!0;let n=Sn(t.workspaceRoot,t.selfEntry);return n===``||n.startsWith(`..`)||bn(n)}function ensureGjsifyShimOnPath(){if(kL)return;kL=!0;let t=process.env.GJSIFY_SHIM_DIR;if(t&&existsSync(xn(t,`gjsify`))){AL=!0,(process.env.PATH??``).split(kn).includes(t)||(process.env.PATH=t+kn+(process.env.PATH??``));return}let n=isGjs(),S=fileURLToPath(n?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:n,selfEntry:S,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let C=n?process.env.GJS_CONSOLE||`gjs`:`node`,N=n?selfShimPreamble(S):``,F={gjsify:n?buildShLauncher(S,{isGjsBundle:!0,envPreamble:N,gjs:C}):`#!/bin/sh\nexec "${C}" "${S}" "$@"\n`};if(!n&&process.platform===`win32`){let{cmd:t,ps1:n}=buildLauncherShims({interpreter:C,interpreterArgs:[],target:S});F[`gjsify.cmd`]=t,F[`gjsify.ps1`]=n}let I=buildNodeShim(n,S,N);I&&(F[`${jL}/node`]=I);let H=materializeShimDir(F);AL=!0,process.env.GJSIFY_SHIM_DIR=H,process.env.PATH=H+kn+(process.env.PATH??``)}function materializeShimDir(t,n=gjsifyCacheRoot(`shim`,`v1`)){let S=Object.keys(t).sort(),C=createHash(`sha256`);for(let n of S)C.update(`${n}\0${t[n]}\0`);let N=C.digest(`hex`).slice(0,16);try{return writeShimDir(xn(n,N),t,S)}catch{return writeShimDir(mkdtempSync(xn(tmpdir(),`gjsify-shim-`)),t,S)}}function writeShimDir(t,n,S){for(let C of S){let S=xn(t,C);if(existsSync(S)&&readFileSync(S,`utf8`)===n[C])continue;mkdirSync(wn(S),{recursive:!0});let N=`${S}.tmp.${process.pid}`;try{writeFileSync(N,n[C],{mode:493}),chmodSync(N,493),renameSync(N,S)}catch(t){throw rmSync(N,{force:!0}),t}}return t}function selfShimScanRoot(t){let n=t.search(/[\\/]node_modules[\\/]/);return n>0?t.slice(0,n):findWorkspaceRoot(wn(t))??wn(t)}function selfShimPreamble(t){let n=[];try{n=detectNativePackages(wn(t)).map(t=>t.prebuildsDir)}catch{}return buildNativeEnvPreamble(selfShimScanRoot(t),n)}function dyldCarryPreamble(t,n){return t===`darwin`?Object.keys(n).filter(t=>/^DYLD_[A-Z_]+$/.test(t)&&n[t]).sort().map(t=>`${t}=${shQuoteArg(n[t])}\nexport ${t}\n`).join(``):``}function nodeShimDir(){let t=process.env.GJSIFY_SHIM_DIR;if(!t)return null;let n=xn(t,jL);return existsSync(xn(n,`node`))?n:null}function buildNodeShim(t,n,S){if(!t||resolveBinOnPath(`node`))return null;let C=process.env.GJS_CONSOLE||`gjs`;return`#!/bin/sh
|
|
920
920
|
`+dyldCarryPreamble(process.platform,process.env)+`case "$1" in
|
|
921
921
|
-*) echo "gjsify: this host has no node; the gjsify shim runs a SCRIPT FILE only" >&2
|
|
922
922
|
echo "gjsify: got: node $*" >&2
|
|
923
923
|
exit 127 ;;
|
|
924
924
|
esac
|
|
925
|
-
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var
|
|
925
|
+
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var kL,AL,jL,ML=__esmMin(()=>{Kc(),Md(),Dg(),jn(),Hn(),t_(),dI(),$P(),kI(),OL(),AP(),kL=!1,AL=!1,jL=`node-shim`});function markDaemonCommand(){NL=!0}function isDaemonCommand(){return NL}var NL,PL=__esmMin(()=>{NL=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(xn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=vn(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Tn(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=xn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[xn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(xn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>($G(),QG));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 FL,IL=__esmMin(()=>{_e(),Md(),jn(),rI(),j_(),yI(),xI(),DI(),OI(),ML(),AP(),zF(),PL(),OP(),t_(),P_(),FL={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:M_,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: ${M_.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(xn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=vn(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),LL,RL=__esmMin(()=>{_e(),jn(),$P(),LL={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?vn(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),zL,BL=__esmMin(()=>{_e(),JP(),zL={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
|
|
926
926
|
`);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(`
|
|
927
927
|
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(`
|
|
928
928
|
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(`
|
|
@@ -934,19 +934,19 @@ Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`
|
|
|
934
934
|
All dependencies found.`);return}N.length>0&&ge.log(`\nMissing required: ${N.map(t=>t.name).join(`, `)}`),F.length>0&&ge.log(`Missing optional: ${F.map(t=>t.name).join(`, `)}`);let q=buildInstallCommand(S,I);q?ge.log(`\nTo install:\n ${q}`):ge.log(`
|
|
935
935
|
No install command available for your package manager. Install manually.`),process.exit(+(N.length>0))}}});function prefixLines(t,n,S,C){let N=``,F=``,emit=t=>{C?F+=t:n.write(t)};return t.setEncoding(`utf-8`),t.on(`data`,t=>{N+=t;let n;for(;(n=N.indexOf(`
|
|
936
936
|
`))!==-1;)emit(S+N.slice(0,n+1)),N=N.slice(n+1)}),t.on(`end`,()=>{N.length>0&&emit(S+N+`
|
|
937
|
-
`)}),()=>{F.length>0&&(n.write(F),F=``)}}var
|
|
937
|
+
`)}),()=>{F.length>0&&(n.write(F),F=``)}}var VL=__esmMin(()=>{});function buildCacheEnabledByEnv(t=process.env){let n=t.GJSIFY_BUILD_CACHE;return n===void 0?!1:n!==``&&n!==`0`&&n!==`false`}function buildCacheRoot(t){return xn(t,`node_modules`,`.cache`,`gjsify`,`build`)}function sanitizePackageDirName(t){return`${t.replace(/^@/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}-${createHash(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function hashFileStream(t){let n=createHash(`sha256`),S=openSync(t,`r`);try{let t=Buffer.alloc(64*1024);for(;;){let C=readSync(S,t,0,t.length,null);if(C<=0)break;n.update(t.subarray(0,C))}}finally{closeSync(S)}return n.digest(`hex`)}function hashPackageInputs(t){let n=packageBuildInputs(t),S=createHash(`sha256`);S.update(`gjsify-build-cache-inputs/v4
|
|
938
938
|
`);for(let t of n){if(t.link!==void 0){let n;try{n=hashFileStream(t.abs)}catch{n=`link:${t.link}`}S.update(`${t.rel} ${n}\n`);continue}try{S.update(`${t.rel} ${hashFileStream(t.abs)}\n`)}catch{S.update(`${t.rel} unreadable\n`)}}return S.digest(`hex`)}function walkFiles(t,n,S){let C;try{C=readdirSync(t)}catch{return}C.sort();for(let N of C){if(N===`node_modules`)continue;let C=xn(t,N),F=n===``?N:`${n}/${N}`,I;try{I=lstatSync(C)}catch{continue}if(I.isSymbolicLink())try{S.push({rel:F,abs:C,link:readlinkSync(C)})}catch{}else I.isDirectory()?walkFiles(C,F,S):I.isFile()&&S.push({rel:F,abs:C})}}function hashOutputDirs(t,n){let S=createHash(`sha256`);S.update(`gjsify-build-cache-outputs/v4
|
|
939
|
-
`);for(let C of[...n].sort()){let n=xn(t,C);if(!existsSync(n)){S.update(`${C} absent\n`);continue}let N=[];walkFiles(n,C,N);for(let t of N){if(t.link!==void 0){S.update(`${t.rel} link:${t.link}\n`);continue}try{S.update(`${t.rel} ${hashFileStream(t.abs)}\n`)}catch{S.update(`${t.rel} unreadable\n`)}}}return S.digest(`hex`)}function outputUnits(t){let n=[];for(let S of
|
|
940
|
-
`),n.update(`script:${t.script}\n`);for(let S of t.args??[])n.update(`arg:${S}\n`);for(let S of Object.keys(t.toolchain).sort())n.update(`tool:${S}@${t.toolchain[S]}\n`);n.update(`self:${t.ownHash}\n`);let S=t.depHashes instanceof Map?t.depHashes:new Map(Object.entries(t.depHashes));for(let t of[...S.keys()].sort())n.update(`dep:${t} ${S.get(t)}\n`);return n.digest(`hex`).slice(0,32)}function resolveToolchainVersions(t){let n={};for(let S of HL){let C=`none`;try{let n=readFileSync(xn(t,`node_modules`,...S.split(`/`),`package.json`),`utf-8`),N=JSON.parse(n);typeof N.version==`string`&&(C=N.version)}catch{}S===`@gjsify/cli`&&C===`none`&&(C=readOwnCliVersion()??`none`),n[S]=C}return n}function readOwnCliVersion(){try{let t=wn(fileURLToPath(import.meta.url));for(let n=0;n<4;n++){let n=xn(t,`package.json`);if(existsSync(n)){let t=JSON.parse(readFileSync(n,`utf-8`));if(t.name===`@gjsify/cli`&&typeof t.version==`string`)return t.version}t=wn(t)}}catch{}return null}function copyDirRecursive(t,n){mkdirSync(n,{recursive:!0});for(let S of readdirSync(t).sort()){let C=xn(t,S),N=xn(n,S),F=lstatSync(C);if(F.isSymbolicLink())replicateLinkSync(C,N);else if(F.isDirectory())copyDirRecursive(C,N);else if(F.isFile()){copyFileSync(C,N);try{chmodSync(N,F.mode&511)}catch{}}}}function buildCacheEntryDir(t,n,S){return xn(t,sanitizePackageDirName(n),S)}function readCacheEntry(t,n,S){let C=xn(UL(t,n,S),`manifest.json`);try{let N=JSON.parse(readFileSync(C,`utf-8`));if(N.version!==1||N.layout!==`v4`||N.package!==n||N.key!==S||!Array.isArray(N.dirs))return null;for(let C of N.dirs)if(!existsSync(xn(UL(t,n,S),`outputs`,C)))return null;return N}catch{return null}}function storeCacheEntry(t,n,S,C,N){let F=UL(t,n.name,S),I=`${F}.tmp-${process.pid}`;try{rmSync(I,{recursive:!0,force:!0}),mkdirSync(xn(I,`outputs`),{recursive:!0});for(let t of N)copyDirRecursive(xn(n.location,t),xn(I,`outputs`,t));let H=new Date().toISOString(),W={version:1,layout:`v4`,package:n.name,script:C,key:S,dirs:[...N],outputsHash:hashOutputDirs(n.location,N),createdAt:H,usedAt:H};return writeFileSync(xn(I,`manifest.json`),JSON.stringify(W,null,2)),rmSync(F,{recursive:!0,force:!0}),renameSync(I,F),pruneCacheEntries(t,n.name),W}catch{try{rmSync(I,{recursive:!0,force:!0})}catch{}return null}}function restoreCacheEntry(t,n,S){let C=UL(t,n.name,S.key);try{if(S.dirs.length>0&&hashOutputDirs(n.location,S.dirs)===S.outputsHash)return touchManifestUsed(C,S),`up-to-date`;for(let t of S.dirs){let S=xn(n.location,t);rmSync(S,{recursive:!0,force:!0}),copyDirRecursive(xn(C,`outputs`,t),S)}return touchManifestUsed(C,S),S.dirs.length>0?`restored`:`up-to-date`}catch{return null}}function touchManifestUsed(t,n){try{n.usedAt=new Date().toISOString(),writeFileSync(xn(t,`manifest.json`),JSON.stringify(n,null,2))}catch{}}function pruneCacheEntries(t,n,S=2){let C=xn(t,sanitizePackageDirName(n)),N;try{N=readdirSync(C)}catch{return}let F=[];for(let t of N){if(t.includes(`.tmp-`)){try{rmSync(xn(C,t),{recursive:!0,force:!0})}catch{}continue}let n=``;try{let S=JSON.parse(readFileSync(xn(C,t,`manifest.json`),`utf-8`));n=S.usedAt??S.createdAt??``}catch{}F.push({name:t,stamp:n})}if(!(F.length<=S)){F.sort((t,n)=>t.stamp<n.stamp?1:t.stamp>n.stamp?-1:0);for(let t of F.slice(S))try{rmSync(xn(C,t.name),{recursive:!0,force:!0})}catch{}}}function buildCacheOptedOut(t){return t.manifest.gjsify?.buildCache===!1}var VL,HL,isBuildInfo,UL,BuildCacheRunner,WL=__esmMin(()=>{_e(),Kc(),Md(),jn(),Hn(),DP(),rL(),VF(),VL=zF,HL=[`@gjsify/cli`,`@gjsify/tsc`,`rolldown`,`typescript`],isBuildInfo=t=>t.endsWith(`.tsbuildinfo`),UL=buildCacheEntryDir,BuildCacheRunner=class{options;cacheRoot;graph;toolchain;ownHashes=new Map;closures=new Map;keys=new Map;log;constructor(t){this.options=t,this.cacheRoot=buildCacheRoot(t.root),this.graph=buildDependencyGraph(t.workspaces,{includeDev:!0,includePeer:!0,includeOptional:!0}),this.toolchain=resolveToolchainVersions(t.root),this.log=t.log??(t=>ge.error(t));for(let n of t.targets??[])if(this.graph.byName.has(n)){this.ownHashOf(n);for(let t of this.closureOf(n))this.ownHashOf(t)}}ownHashOf(t){let n=this.ownHashes.get(t);if(n===void 0){let S=this.graph.byName.get(t);n=S?hashPackageInputs(S.location):`unknown-workspace`,this.ownHashes.set(t,n)}return n}closureOf(t){let n=this.closures.get(t);if(n===void 0){let S=new Set,C=[...this.graph.edges.get(t)??[]];for(;C.length>0;){let n=C.shift();if(!(n===t||S.has(n))){S.add(n);for(let N of this.graph.edges.get(n)??[])!S.has(N)&&N!==t&&C.push(N)}}n=[...S].sort(),this.closures.set(t,n)}return n}keyFor(t){let n=this.keys.get(t.name);if(n===void 0){let S=new Map;for(let n of this.closureOf(t.name))S.set(n,this.ownHashOf(n));n=composeCacheKey({script:this.options.script,args:this.options.args,toolchain:this.toolchain,ownHash:this.ownHashOf(t.name),depHashes:S}),this.keys.set(t.name,n)}return n}tryRestore(t){try{if(buildCacheOptedOut(t))return this.log(`[gjsify build-cache] ${t.name}: opted out (gjsify.buildCache=false) — running uncached`),!1;let n=this.keyFor(t),S=readCacheEntry(this.cacheRoot,t.name,n);if(!S||S.script!==this.options.script)return this.log(`[gjsify build-cache] ${t.name}: miss ${n} — running "${this.options.script}"`),!1;let C=restoreCacheEntry(this.cacheRoot,t,S);if(C===null)return this.log(`[gjsify build-cache] ${t.name}: entry ${n} unrestorable — running "${this.options.script}"`),!1;let N=S.dirs.length>0?S.dirs.join(`, `):`no output dirs`;return this.log(`[gjsify build-cache] ${t.name}: hit ${n} — ${C===`restored`?`restored ${N}`:`${N} up to date`} (skipped "${this.options.script}")`),!0}catch(n){return this.log(`[gjsify build-cache] ${t.name}: cache error (${n.message}) — running uncached`),!1}}snapshotOutputs(t){try{return snapshotOutputDirs(t.location)}catch{return{}}}storeAfterSuccess(t,n){try{if(buildCacheOptedOut(t))return;let S=this.keyFor(t),C=modifiedOutputDirs(t.location,n);if(storeCacheEntry(this.cacheRoot,t,S,this.options.script,C)){let n=C.length>0?C.join(`, `):`no output dirs modified`;this.log(`[gjsify build-cache] ${t.name}: stored ${S} (${n})`)}}catch(n){this.log(`[gjsify build-cache] ${t.name}: store failed (${n.message}) — continuing`)}}}});function editDistance(t,n){if(t===n)return 0;if(t.length===0)return n.length;if(n.length===0)return t.length;let S=Array.from({length:n.length+1},(t,n)=>n),C=Array.from({length:n.length+1},()=>0);for(let N=1;N<=t.length;N++){C[0]=N;for(let F=1;F<=n.length;F++){let I=t[N-1]===n[F-1]?0:1;C[F]=Math.min(S[F]+1,C[F-1]+1,S[F-1]+I)}[S,C]=[C,S]}return S[n.length]}function suggestClosest(t,n){if(n.length===0)return;let S=t.toLowerCase(),C=Math.max(2,Math.floor(t.length/3)),N,F=1/0;for(let t of n){let n=editDistance(S,t.toLowerCase());n<F&&(F=n,N=t)}return N!==void 0&&F<=C?N:void 0}var GL=__esmMin(()=>{});function reportUnlinked(t,n){for(let S of t)n.has(S.from)&&ge.error(`gjsify workspace: "${S.from}" depends on "${S.to}": ${S.spec}, which the local workspace (${S.to}@${S.version}) does not satisfy — NOT built as a dependency. npm and yarn take that one from the registry; \`gjsify install\` links the local one anyway, so if it is the local one you mean, make the range admit ${S.version}.`)}async function runOne$1(t,n,S,C,N,F){if(F&&F.tryRestore(t))return;let I=F?.snapshotOutputs(t),H=C===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${C} ${H.join(` `)}`);let{code:W}=await spawnToCompletion(C,H,{completion:`exit`,cwd:t.location,color:!0});if(W!==0)throw Error(`${C} ${H.join(` `)} exited with code ${W}`);F&&I&&F.storeAfterSuccess(t,I)}function detectPackageManager(){if(isGjs()||usingSelfShim())return`gjsify`;let t=process.env.npm_config_user_agent??``;return t.startsWith(`yarn/`)?`yarn`:t.startsWith(`gjsify/`)?`gjsify`:`npm`}var KL,qL=__esmMin(()=>{_e(),j_(),DP(),kP(),WL(),t_(),jL(),GL(),KL={command:`workspace <name> <script> [args..]`,description:"Run a workspace script. Both `workspace <name> <script>` and the yarn spelling `workspace <name> run <script>` work.",builder:t=>t.positional(`name`,{description:"Workspace name (matches package.json `name` field).",type:`string`,demandOption:!0}).positional(`script`,{description:`Script name to run inside that workspace.`,type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments forwarded to the script.`,type:`string`,array:!0}).option(`with-dependencies`,{description:"Pre-build the target workspace's transitive workspace dependencies in topological order before running the script in the target. Deps that don't declare the script are skipped (--if-present behaviour). Replaces manual `gjsify workspace A build && gjsify workspace B build && …` chains.",type:`boolean`,alias:[`d`,`t`,`topological`],default:!1}).option(`include-dev`,{description:"When --with-dependencies is set, also walk devDependencies (production deps only by default — matches `gjsify foreach -t`).",type:`boolean`,default:!1}).option(`continue-on-error`,{description:`When --with-dependencies is set, keep running remaining deps after one fails (default: stop on first failure).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip the script for 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 it and store the output dirs it modified. Also applies to the deps run via --with-dependencies. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=S.find(n=>n.name===t.name);if(!C){let C=suggestClosest(t.name,S.map(t=>t.name)),N=C?` — did you mean "${C}"?`:``;return ge.error(`gjsify workspace: no workspace named "${t.name}"${N} (discovered ${S.length} workspace(s) under ${n})`),process.exit(1)}let N=detectPackageManager(),F=t.verbose===!0,I=t[`with-dependencies`]===!0,H=t[`continue-on-error`]===!0,W=t.script,q=t.args??[];W===`run`&&q.length>0&&([W,...q]=q);let Y=C.manifest.scripts??{};if(typeof Y[W]!=`string`){let n=suggestClosest(W,Object.keys(Y));return ge.error(`gjsify workspace: workspace "${t.name}" has no script "${W}"`+(n?` — did you mean "${n}"?`:``)),process.exit(1)}let X;if(I){let n=t[`include-dev`]===!0,N=buildDependencyGraph(S,{includeDev:n}),F=affectedClosure(N,[C.name]),I=S.filter(t=>F.has(t.name));reportUnlinked(N.unlinked,F),X=topologicalSort(buildDependencyGraph(I,{includeDev:n})),X.length===1&&ge.error(`gjsify workspace: --with-dependencies found no workspace dependencies of "${C.name}" — running "${W}" in it alone.`)}else X=[C];let Z=t.cached??buildCacheEnabledByEnv()?new BuildCacheRunner({root:n,workspaces:S,script:W,args:q,targets:X.map(t=>t.name)}):void 0,te=[];for(let t of X){if(typeof(t.manifest.scripts??{})[W]!=`string`){F&&ge.error(`[${t.name}] (no "${W}" script — skipping)`);continue}try{await runOne$1(t,W,q,N,F,Z)}catch(n){let S=n instanceof Error?n:Error(String(n));if(ge.error(`[${t.name}] ${S.message}`),!H)return process.exit(1);te.push({workspace:t.name,error:S})}}return te.length>0?(ge.error(`gjsify workspace: ${te.length} workspace(s) failed: ${te.map(t=>t.workspace).join(`, `)}`),process.exit(1)):process.exit(0)}},__name$1(runOne$1,`runOne`)});async function runCheck(t,n){let S=[],C=detectPackageManager();if(C===`gjsify`&&readPackageJson$2(xn(t.location,`package.json`))?.scripts?.check===void 0)return 0;let N=C===`gjsify`?[`run`,`check`]:[`run`,`check`,`--if-present`];try{let{code:F}=await spawnToCompletion(C,N,{completion:`exit`,cwd:t.location,stdio:n===null?`inherit`:`pipe`,onSpawn:t=>{let C=!process.stdout.isTTY;if(n!==null&&t.stdout&&t.stderr){let N=`[${n}] `;S.push(prefixLines(t.stdout,process.stdout,N,C)),S.push(prefixLines(t.stderr,process.stderr,N,C))}}});for(let t of S)t();return F??1}catch{for(let t of S)t();return 1}}var JL,YL=__esmMin(()=>{_e(),BL(),j_(),OP(),jn(),Dg(),DP(),kP(),qL(),JL={command:`check`,description:"Run `npm run check` (TypeScript type-check) across the current workspace. In a workspace root: walks every package with a `check` script (excludes @girs/*; honours --include/--exclude). In a single package: runs the local `check` script directly. Symmetric peer of `gjsify format` / `lint` / `fix`. (Legacy system-dep `gjsify check` is now `gjsify system-check` — see #254.)",builder:t=>t.option(`include`,{description:`Only run in workspaces matching these glob patterns (repeatable).`,type:`string`,array:!0}).option(`exclude`,{description:`Skip workspaces matching these glob patterns (repeatable). Always excludes @girs/*.`,type:`string`,array:!0}).option(`parallel`,{description:`Run workspace checks in parallel (default). Use --no-parallel to run them sequentially with full per-workspace output.`,type:`boolean`,alias:`p`,default:!0}).option(`jobs`,{description:`Max parallel workers (when --parallel). Default: os.cpus().length.`,type:`number`,alias:`j`}).option(`verbose`,{description:`Log the per-workspace command before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=findWorkspaceRoot(n);if(S&&n!==S&&readPackageJson$2(xn(n,`package.json`))?.scripts?.check){t.verbose&&ge.log(`[check] cwd=${n} → npm run check`);let{code:S}=await spawnToCompletion(detectPackageManager(),[`run`,`check`],{cwd:n,completion:`exit`});return process.exit(S??1)}if(!S)return ge.error("gjsify check: no workspace root found from cwd. Run inside a workspace (or a package within one) with `npm run check` defined."),process.exit(1);let C=discoverWorkspaces(S),N=[`@girs/*`,...t.exclude??[]],F=filterWorkspaces(C,{include:t.include,exclude:N}).filter(t=>t.manifest.scripts?.check!==void 0);if(F.length===0)return ge.error("gjsify check: no workspaces with a `check` script found."),process.exit(1);if(t.verbose&&ge.log(`[check] root=${S} workspaces=${F.length} parallel=${t.parallel?`yes`:`no`}`),!t.parallel){let n=0,S=0;for(let C of F){t.verbose&&ge.log(`[check] → ${C.name}`);let N=await runCheck(C,null);N!==0&&(S++,n===0&&(n=N))}return n!==0&&ge.error(`gjsify check: failures in ${S} workspace(s)`),process.exit(n)}let I=t.jobs??Math.max(1,cpus().length),H=[],W=0,q=[];for(let t=0;t<I;t++)q.push((async()=>{for(;;){let t=W++;if(t>=F.length)return;let n=F[t],S=await runCheck(n,n.name);S!==0&&H.push({name:n.name,code:S})}})());if(await Promise.all(q),H.length>0){ge.error(`\ngjsify check: ${H.length} of ${F.length} workspace(s) failed:`);for(let t of H)ge.error(` ✗ ${t.name} (exit ${t.code})`);return process.exit(1)}t.verbose&&ge.log(`\ngjsify check: ${F.length} workspace(s) green.`),process.exit(0)}}});function manifestPath(){let t=wn(fileURLToPath(import.meta.url)),n=[xn(t,`..`,`..`,`showcases.json`),xn(t,`..`,`showcases.json`)];return n.find(t=>existsSync(t))??n[0]}function discoverShowcases(){let t=manifestPath();if(!existsSync(t))return[];let n;try{n=JSON.parse(readFileSync(t,`utf-8`))}catch{return[]}if(!Array.isArray(n.showcases))return[];let S=n.showcases.map(t=>({name:t.name,packageName:t.package,category:t.category,description:t.description??``}));return S.sort((t,n)=>t.category.localeCompare(n.category)||t.name.localeCompare(n.name)),S}function findShowcase(t){return discoverShowcases().find(n=>n.name===t)}var XL=__esmMin(()=>{Md(),jn(),Hn()});function parseSpec(t){if(!t)throw Error(`dlx: empty package spec`);if(t.startsWith(`./`)||t.startsWith(`../`)||bn(t)||existsSync(t))return{kind:`local`,path:vn(t)};let n=t,S,C=t.lastIndexOf(`@`);if(C>0&&(n=t.slice(0,C),S=t.slice(C+1)),!ZL.test(n))throw Error(`dlx: invalid package name "${n}"`);return{kind:`registry`,name:n,version:S,spec:t}}var ZL,QL=__esmMin(()=>{Md(),jn(),ZL=/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/});function resolveGjsEntry(t,n){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`dlx: no package.json found at ${t}`);let C=JSON.parse(readFileSync(S,`utf-8`)),N=C.gjsify?.bin,F=C.gjsify?.main,I=C.main,H,W=null,q=!1;if(n!==null){if(!N||!N[n]){let S=N?Object.keys(N).join(`, `):`(none)`;throw Error(`dlx: package "${C.name??t}" has no GJS bin named "${n}" — known: ${S}`)}H=N[n],W=n}else if(N&&Object.keys(N).length===1){let t=Object.keys(N)[0];H=N[t],W=t}else F?H=F:I&&(H=I,q=!0);if(N&&Object.keys(N).length>1&&n===null){let n=Object.keys(N).join(`, `);throw Error(`dlx: package "${C.name??t}" defines multiple GJS bins — pass one of: ${n}`)}if(!H)throw Error(`dlx: package "${C.name??t}" has no GJS entry — set \`gjsify.main\` (or \`gjsify.bin\`) in its package.json`);let Y=vn(t,H);if(!existsSync(Y))throw Error(`dlx: GJS entry not found: ${Y}`);return{bundlePath:Y,binName:W,fromFallback:q}}function resolveNodeEntry(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`no package.json found at ${t}`);let S=JSON.parse(readFileSync(n,`utf-8`)),C=S.gjsify?.example?.node;if(C){let n=vn(t,C);if(!existsSync(n))throw Error(`declared node entry not found: ${n} (gjsify.example.node)`);return n}let N=S.gjsify?.main??(S.gjsify?.bin?Object.values(S.gjsify.bin)[0]:void 0)??S.main;if(!N)throw Error(`package "${S.name??t}" has no entry to derive a node bundle from — set \`gjsify.example.node\` to its \`--app node\` bundle path.`);let F=N.replace(/\.gjs\.(js|mjs|cjs)$/,``).replace(/\.(js|mjs|cjs)$/,``),I=[`${F}.node.mjs`,`${F}.node.js`,`${F}.node.cjs`];for(let n of I){let S=vn(t,n);if(existsSync(S))return S}throw Error(`package "${S.name??t}" has no \`--app node\` bundle — looked for ${I.join(`, `)}.\n Build one (e.g. \`gjsify build src/app.ts --app node --outfile dist/app.node.mjs\`) or set \`gjsify.example.node\` to its path.`)}var $L=__esmMin(()=>{Md(),jn()});function lexCompare(t,n){return t<n?-1:+(t>n)}function createCacheKey(t){let n=[...t.packages].sort(lexCompare),S=Object.entries(t.registries??{}).sort(([t],[n])=>lexCompare(t,n)),C=JSON.stringify([n,S]);return createHash(`sha256`).update(C).digest(`hex`)}function dlxCacheRoot(){let t=process.env.XDG_CACHE_HOME,n=xn(t&&t.length>0?t:xn(homedir(),`.cache`),`gjsify`,`dlx`);return mkdirSync(n,{recursive:!0}),n}function cacheDirFor(t){let n=xn(dlxCacheRoot(),t);return mkdirSync(n,{recursive:!0}),n}function makePrepareDir(t){let n=xn(t,`${Date.now().toString(16)}-${process.pid.toString(16)}`);return mkdirSync(n,{recursive:!0}),n}function getValidCachedPkg(t,n=tR){let S=xn(t,`pkg`),C;try{C=lstatSync(S)}catch(t){if(t.code===`ENOENT`)return;throw t}if(!C.isSymbolicLink())return;let N;try{N=realpathSync(S)}catch{return}return Date.now()-C.mtime.getTime()<=n*eR?N:void 0}function symlinkSwap(t,n,S={}){let C=S.junctions??dirLinksAreJunctions(),N=xn(t,`pkg`),F=xn(t,`pkg.tmp-${Date.now().toString(16)}-${process.pid.toString(16)}`);linkDirSync(F,n);try{C&&rmSync(N,{force:!0,recursive:!1,maxRetries:10,retryDelay:100}),renameSync(F,N)}catch(t){let S=t.code;if(S===`EBUSY`||S===`EPERM`||S===`EEXIST`||S===`EACCES`){rmSync(F,{force:!0});try{return realpathSync(N)}catch{return realpathSync(n)}}throw t}return realpathSync(N)}function resolveInstalledPkgDir(t,n){return vn(t,`node_modules`,n)}var eR,tR,nR=__esmMin(()=>{Kc(),Md(),Dg(),jn(),rL(),eR=6e4,tR=1440*7});async function ensurePkgDir(t,n){if(t.kind===`local`)return{pkgDir:t.path,cachedPkgName:null};let S=[t.spec,...n.extraSpecs??[]],C=cacheDirFor(createCacheKey({packages:S})),N=n.cacheMaxAge>0?getValidCachedPkg(C,n.cacheMaxAge):void 0;if(N)return{pkgDir:resolveInstalledPkgDir(N,t.name),cachedPkgName:t.name};let F=makePrepareDir(C),I=makeProgressReporter({enabled:!n.verbose});return await installPackages({prefix:F,specs:S,verbose:n.verbose,registry:n.registry,lockfile:!0,frozen:n.frozen,progress:I}),{pkgDir:resolveInstalledPkgDir(symlinkSwap(C,F),t.name),cachedPkgName:t.name}}function splitBinAndArgs(t,n,S){if(!n)return{binName:null,extraArgs:S};let C=xn(t,`package.json`);if(existsSync(C))try{let t=JSON.parse(readFileSync(C,`utf-8`)).gjsify?.bin;if(t&&Object.prototype.hasOwnProperty.call(t,n))return{binName:n,extraArgs:S}}catch{}return{binName:null,extraArgs:[n,...S]}}var rR,iR=__esmMin(()=>{_e(),vI(),QL(),$L(),nI(),nR(),CL(),Md(),jn(),rR={command:`dlx <spec> [binOrArg] [extraArgs..]`,description:`Run the GJS bundle of an npm-published package without installing it locally.`,builder:t=>t.parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}).positional(`spec`,{description:"Package spec (`name`, `name@version`, `@scope/name@spec`, or local path).",type:`string`,demandOption:!0}).positional(`binOrArg`,{description:"Optional bin name when the package defines `gjsify.bin` with multiple entries; otherwise treated as the first argument forwarded to the bundle. To pass a flag here (e.g. `--help`) use the `--` separator: `gjsify dlx <pkg> -- --help`.",type:`string`}).positional(`extraArgs`,{description:"Extra args forwarded to `gjs -m <bundle>`. Use `--` before flags to bypass gjsify-level parsing (`gjsify dlx <pkg> -- --help --verbose`).",type:`string`,array:!0}).option(`cache-max-age`,{description:`Cache TTL in minutes. Defaults to 7 days. Use 0 to bypass cache.`,type:`number`,default:1440*7}).option(`reinstall`,{description:`Bypass the cache for this run (alias for --cache-max-age=0).`,type:`boolean`,default:!1}).option(`frozen`,{description:`Use the project-local gjsify-lock.json verbatim — fail if missing or stale (no resolver pass).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging (passes --loglevel verbose to npm).`,type:`boolean`,default:!1}).option(`registry`,{description:`Registry URL override.`,type:`string`}),handler:async t=>{let n=parseSpec(t.spec),S=t.reinstall?0:t[`cache-max-age`],{pkgDir:C,cachedPkgName:N}=await ensurePkgDir(n,{verbose:t.verbose,registry:t.registry,cacheMaxAge:S,frozen:t.frozen}),F=[...t.extraArgs??[],...doubleDashArgs(t)],{binName:I,extraArgs:H}=splitBinAndArgs(C,t.binOrArg,F),W=resolveGjsEntry(C,I);W.fromFallback&&ge.warn(`[gjsify dlx] package "${N??n.kind}" declares no \`gjsify.main\` — falling back to package.json#main. Add \`gjsify.main\` to silence.`),await runGjsBundle(W.bundlePath,H,{completion:`exit`,exitOnSuccess:!0})}}});async function loadNpmrc(t){let n=[],S=xn(t,`.npmrc`);existsSync(S)&&n.push(readFileSync(S,`utf-8`));let C=process.env.NPM_CONFIG_USERCONFIG;if(C&&existsSync(C))n.push(readFileSync(C,`utf-8`));else{let t=xn(homedir(),`.npmrc`);existsSync(t)&&n.push(readFileSync(t,`utf-8`))}return parseNpmrc(n.join(`
|
|
941
|
-
`).replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(t,n)=>process.env[n]??``))}function hasAnyAuthToken(t){return Object.keys(t.authTokens).length>0}function hasAnyCredential(t){return hasAnyAuthToken(t)||Object.keys(t.basicAuth).length>0}var
|
|
939
|
+
`);for(let C of[...n].sort()){let n=xn(t,C);if(!existsSync(n)){S.update(`${C} absent\n`);continue}let N=[];walkFiles(n,C,N);for(let t of N){if(t.link!==void 0){S.update(`${t.rel} link:${t.link}\n`);continue}try{S.update(`${t.rel} ${hashFileStream(t.abs)}\n`)}catch{S.update(`${t.rel} unreadable\n`)}}}return S.digest(`hex`)}function outputUnits(t){let n=[];for(let S of HL){let C=xn(t,S);if(!existsSync(C))continue;let N;try{N=readdirSync(C).filter(t=>t!==`node_modules`&&!isBuildInfo(t))}catch{continue}let F=N.every(t=>{try{return lstatSync(xn(C,t)).isDirectory()}catch{return!1}});if(N.length===0||!F){n.push(S);continue}for(let t of[...N].sort())n.push(`${S}/${t}`)}return n}function signatureOf(t,n){let S=[];walkFiles(xn(t,n),n,S);let C=createHash(`sha256`);for(let t of S){let n=`link`;if(t.link===void 0)try{let S=lstatSync(t.abs);n=`${S.size}:${S.mtimeMs}`}catch{n=`gone`}C.update(`${t.rel} ${n}\n`)}return C.digest(`hex`)}function snapshotOutputDirs(t){let n={};for(let t of HL)n[t]=null;for(let S of outputUnits(t))n[S]=signatureOf(t,S);return n}function modifiedOutputDirs(t,n){let S=[];for(let C of outputUnits(t))signatureOf(t,C)!==(n[C]??null)&&S.push(C);return S.sort()}function composeCacheKey(t){let n=createHash(`sha256`);n.update(`gjsify-build-cache/v4
|
|
940
|
+
`),n.update(`script:${t.script}\n`);for(let S of t.args??[])n.update(`arg:${S}\n`);for(let S of Object.keys(t.toolchain).sort())n.update(`tool:${S}@${t.toolchain[S]}\n`);n.update(`self:${t.ownHash}\n`);let S=t.depHashes instanceof Map?t.depHashes:new Map(Object.entries(t.depHashes));for(let t of[...S.keys()].sort())n.update(`dep:${t} ${S.get(t)}\n`);return n.digest(`hex`).slice(0,32)}function resolveToolchainVersions(t){let n={};for(let S of UL){let C=`none`;try{let n=readFileSync(xn(t,`node_modules`,...S.split(`/`),`package.json`),`utf-8`),N=JSON.parse(n);typeof N.version==`string`&&(C=N.version)}catch{}S===`@gjsify/cli`&&C===`none`&&(C=readOwnCliVersion()??`none`),n[S]=C}return n}function readOwnCliVersion(){try{let t=wn(fileURLToPath(import.meta.url));for(let n=0;n<4;n++){let n=xn(t,`package.json`);if(existsSync(n)){let t=JSON.parse(readFileSync(n,`utf-8`));if(t.name===`@gjsify/cli`&&typeof t.version==`string`)return t.version}t=wn(t)}}catch{}return null}function copyDirRecursive(t,n){mkdirSync(n,{recursive:!0});for(let S of readdirSync(t).sort()){let C=xn(t,S),N=xn(n,S),F=lstatSync(C);if(F.isSymbolicLink())replicateLinkSync(C,N);else if(F.isDirectory())copyDirRecursive(C,N);else if(F.isFile()){copyFileSync(C,N);try{chmodSync(N,F.mode&511)}catch{}}}}function buildCacheEntryDir(t,n,S){return xn(t,sanitizePackageDirName(n),S)}function readCacheEntry(t,n,S){let C=xn(WL(t,n,S),`manifest.json`);try{let N=JSON.parse(readFileSync(C,`utf-8`));if(N.version!==1||N.layout!==`v4`||N.package!==n||N.key!==S||!Array.isArray(N.dirs))return null;for(let C of N.dirs)if(!existsSync(xn(WL(t,n,S),`outputs`,C)))return null;return N}catch{return null}}function storeCacheEntry(t,n,S,C,N){let F=WL(t,n.name,S),I=`${F}.tmp-${process.pid}`;try{rmSync(I,{recursive:!0,force:!0}),mkdirSync(xn(I,`outputs`),{recursive:!0});for(let t of N)copyDirRecursive(xn(n.location,t),xn(I,`outputs`,t));let H=new Date().toISOString(),W={version:1,layout:`v4`,package:n.name,script:C,key:S,dirs:[...N],outputsHash:hashOutputDirs(n.location,N),createdAt:H,usedAt:H};return writeFileSync(xn(I,`manifest.json`),JSON.stringify(W,null,2)),rmSync(F,{recursive:!0,force:!0}),renameSync(I,F),pruneCacheEntries(t,n.name),W}catch{try{rmSync(I,{recursive:!0,force:!0})}catch{}return null}}function restoreCacheEntry(t,n,S){let C=WL(t,n.name,S.key);try{if(S.dirs.length>0&&hashOutputDirs(n.location,S.dirs)===S.outputsHash)return touchManifestUsed(C,S),`up-to-date`;for(let t of S.dirs){let S=xn(n.location,t);rmSync(S,{recursive:!0,force:!0}),copyDirRecursive(xn(C,`outputs`,t),S)}return touchManifestUsed(C,S),S.dirs.length>0?`restored`:`up-to-date`}catch{return null}}function touchManifestUsed(t,n){try{n.usedAt=new Date().toISOString(),writeFileSync(xn(t,`manifest.json`),JSON.stringify(n,null,2))}catch{}}function pruneCacheEntries(t,n,S=2){let C=xn(t,sanitizePackageDirName(n)),N;try{N=readdirSync(C)}catch{return}let F=[];for(let t of N){if(t.includes(`.tmp-`)){try{rmSync(xn(C,t),{recursive:!0,force:!0})}catch{}continue}let n=``;try{let S=JSON.parse(readFileSync(xn(C,t,`manifest.json`),`utf-8`));n=S.usedAt??S.createdAt??``}catch{}F.push({name:t,stamp:n})}if(!(F.length<=S)){F.sort((t,n)=>t.stamp<n.stamp?1:t.stamp>n.stamp?-1:0);for(let t of F.slice(S))try{rmSync(xn(C,t.name),{recursive:!0,force:!0})}catch{}}}function buildCacheOptedOut(t){return t.manifest.gjsify?.buildCache===!1}var HL,UL,isBuildInfo,WL,BuildCacheRunner,GL=__esmMin(()=>{_e(),Kc(),Md(),jn(),Hn(),OP(),iL(),HF(),HL=BF,UL=[`@gjsify/cli`,`@gjsify/tsc`,`rolldown`,`typescript`],isBuildInfo=t=>t.endsWith(`.tsbuildinfo`),WL=buildCacheEntryDir,BuildCacheRunner=class{options;cacheRoot;graph;toolchain;ownHashes=new Map;closures=new Map;keys=new Map;log;constructor(t){this.options=t,this.cacheRoot=buildCacheRoot(t.root),this.graph=buildDependencyGraph(t.workspaces,{includeDev:!0,includePeer:!0,includeOptional:!0}),this.toolchain=resolveToolchainVersions(t.root),this.log=t.log??(t=>ge.error(t));for(let n of t.targets??[])if(this.graph.byName.has(n)){this.ownHashOf(n);for(let t of this.closureOf(n))this.ownHashOf(t)}}ownHashOf(t){let n=this.ownHashes.get(t);if(n===void 0){let S=this.graph.byName.get(t);n=S?hashPackageInputs(S.location):`unknown-workspace`,this.ownHashes.set(t,n)}return n}closureOf(t){let n=this.closures.get(t);if(n===void 0){let S=new Set,C=[...this.graph.edges.get(t)??[]];for(;C.length>0;){let n=C.shift();if(!(n===t||S.has(n))){S.add(n);for(let N of this.graph.edges.get(n)??[])!S.has(N)&&N!==t&&C.push(N)}}n=[...S].sort(),this.closures.set(t,n)}return n}keyFor(t){let n=this.keys.get(t.name);if(n===void 0){let S=new Map;for(let n of this.closureOf(t.name))S.set(n,this.ownHashOf(n));n=composeCacheKey({script:this.options.script,args:this.options.args,toolchain:this.toolchain,ownHash:this.ownHashOf(t.name),depHashes:S}),this.keys.set(t.name,n)}return n}tryRestore(t){try{if(buildCacheOptedOut(t))return this.log(`[gjsify build-cache] ${t.name}: opted out (gjsify.buildCache=false) — running uncached`),!1;let n=this.keyFor(t),S=readCacheEntry(this.cacheRoot,t.name,n);if(!S||S.script!==this.options.script)return this.log(`[gjsify build-cache] ${t.name}: miss ${n} — running "${this.options.script}"`),!1;let C=restoreCacheEntry(this.cacheRoot,t,S);if(C===null)return this.log(`[gjsify build-cache] ${t.name}: entry ${n} unrestorable — running "${this.options.script}"`),!1;let N=S.dirs.length>0?S.dirs.join(`, `):`no output dirs`;return this.log(`[gjsify build-cache] ${t.name}: hit ${n} — ${C===`restored`?`restored ${N}`:`${N} up to date`} (skipped "${this.options.script}")`),!0}catch(n){return this.log(`[gjsify build-cache] ${t.name}: cache error (${n.message}) — running uncached`),!1}}snapshotOutputs(t){try{return snapshotOutputDirs(t.location)}catch{return{}}}storeAfterSuccess(t,n){try{if(buildCacheOptedOut(t))return;let S=this.keyFor(t),C=modifiedOutputDirs(t.location,n);if(storeCacheEntry(this.cacheRoot,t,S,this.options.script,C)){let n=C.length>0?C.join(`, `):`no output dirs modified`;this.log(`[gjsify build-cache] ${t.name}: stored ${S} (${n})`)}}catch(n){this.log(`[gjsify build-cache] ${t.name}: store failed (${n.message}) — continuing`)}}}});function editDistance(t,n){if(t===n)return 0;if(t.length===0)return n.length;if(n.length===0)return t.length;let S=Array.from({length:n.length+1},(t,n)=>n),C=Array.from({length:n.length+1},()=>0);for(let N=1;N<=t.length;N++){C[0]=N;for(let F=1;F<=n.length;F++){let I=t[N-1]===n[F-1]?0:1;C[F]=Math.min(S[F]+1,C[F-1]+1,S[F-1]+I)}[S,C]=[C,S]}return S[n.length]}function suggestClosest(t,n){if(n.length===0)return;let S=t.toLowerCase(),C=Math.max(2,Math.floor(t.length/3)),N,F=1/0;for(let t of n){let n=editDistance(S,t.toLowerCase());n<F&&(F=n,N=t)}return N!==void 0&&F<=C?N:void 0}var KL=__esmMin(()=>{});function reportUnlinked(t,n){for(let S of t)n.has(S.from)&&ge.error(`gjsify workspace: "${S.from}" depends on "${S.to}": ${S.spec}, which the local workspace (${S.to}@${S.version}) does not satisfy — NOT built as a dependency. npm and yarn take that one from the registry; \`gjsify install\` links the local one anyway, so if it is the local one you mean, make the range admit ${S.version}.`)}async function runOne$1(t,n,S,C,N,F){if(F&&F.tryRestore(t))return;let I=F?.snapshotOutputs(t),H=C===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${C} ${H.join(` `)}`);let{code:W}=await spawnToCompletion(C,H,{completion:`exit`,cwd:t.location,color:!0});if(W!==0)throw Error(`${C} ${H.join(` `)} exited with code ${W}`);F&&I&&F.storeAfterSuccess(t,I)}function detectPackageManager(){if(isGjs()||usingSelfShim())return`gjsify`;let t=process.env.npm_config_user_agent??``;return t.startsWith(`yarn/`)?`yarn`:t.startsWith(`gjsify/`)?`gjsify`:`npm`}var qL,JL=__esmMin(()=>{_e(),j_(),OP(),AP(),GL(),t_(),ML(),KL(),qL={command:`workspace <name> <script> [args..]`,description:"Run a workspace script. Both `workspace <name> <script>` and the yarn spelling `workspace <name> run <script>` work.",builder:t=>t.positional(`name`,{description:"Workspace name (matches package.json `name` field).",type:`string`,demandOption:!0}).positional(`script`,{description:`Script name to run inside that workspace.`,type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments forwarded to the script.`,type:`string`,array:!0}).option(`with-dependencies`,{description:"Pre-build the target workspace's transitive workspace dependencies in topological order before running the script in the target. Deps that don't declare the script are skipped (--if-present behaviour). Replaces manual `gjsify workspace A build && gjsify workspace B build && …` chains.",type:`boolean`,alias:[`d`,`t`,`topological`],default:!1}).option(`include-dev`,{description:"When --with-dependencies is set, also walk devDependencies (production deps only by default — matches `gjsify foreach -t`).",type:`boolean`,default:!1}).option(`continue-on-error`,{description:`When --with-dependencies is set, keep running remaining deps after one fails (default: stop on first failure).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip the script for 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 it and store the output dirs it modified. Also applies to the deps run via --with-dependencies. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=S.find(n=>n.name===t.name);if(!C){let C=suggestClosest(t.name,S.map(t=>t.name)),N=C?` — did you mean "${C}"?`:``;return ge.error(`gjsify workspace: no workspace named "${t.name}"${N} (discovered ${S.length} workspace(s) under ${n})`),process.exit(1)}let N=detectPackageManager(),F=t.verbose===!0,I=t[`with-dependencies`]===!0,H=t[`continue-on-error`]===!0,W=t.script,q=t.args??[];W===`run`&&q.length>0&&([W,...q]=q);let Y=C.manifest.scripts??{};if(typeof Y[W]!=`string`){let n=suggestClosest(W,Object.keys(Y));return ge.error(`gjsify workspace: workspace "${t.name}" has no script "${W}"`+(n?` — did you mean "${n}"?`:``)),process.exit(1)}let X;if(I){let n=t[`include-dev`]===!0,N=buildDependencyGraph(S,{includeDev:n}),F=affectedClosure(N,[C.name]),I=S.filter(t=>F.has(t.name));reportUnlinked(N.unlinked,F),X=topologicalSort(buildDependencyGraph(I,{includeDev:n})),X.length===1&&ge.error(`gjsify workspace: --with-dependencies found no workspace dependencies of "${C.name}" — running "${W}" in it alone.`)}else X=[C];let Z=t.cached??buildCacheEnabledByEnv()?new BuildCacheRunner({root:n,workspaces:S,script:W,args:q,targets:X.map(t=>t.name)}):void 0,te=[];for(let t of X){if(typeof(t.manifest.scripts??{})[W]!=`string`){F&&ge.error(`[${t.name}] (no "${W}" script — skipping)`);continue}try{await runOne$1(t,W,q,N,F,Z)}catch(n){let S=n instanceof Error?n:Error(String(n));if(ge.error(`[${t.name}] ${S.message}`),!H)return process.exit(1);te.push({workspace:t.name,error:S})}}return te.length>0?(ge.error(`gjsify workspace: ${te.length} workspace(s) failed: ${te.map(t=>t.workspace).join(`, `)}`),process.exit(1)):process.exit(0)}},__name$1(runOne$1,`runOne`)});async function runCheck(t,n){let S=[],C=detectPackageManager();if(C===`gjsify`&&readPackageJson$2(xn(t.location,`package.json`))?.scripts?.check===void 0)return 0;let N=C===`gjsify`?[`run`,`check`]:[`run`,`check`,`--if-present`];try{let{code:F}=await spawnToCompletion(C,N,{completion:`exit`,cwd:t.location,stdio:n===null?`inherit`:`pipe`,onSpawn:t=>{let C=!process.stdout.isTTY;if(n!==null&&t.stdout&&t.stderr){let N=`[${n}] `;S.push(prefixLines(t.stdout,process.stdout,N,C)),S.push(prefixLines(t.stderr,process.stderr,N,C))}}});for(let t of S)t();return F??1}catch{for(let t of S)t();return 1}}var YL,XL=__esmMin(()=>{_e(),VL(),j_(),kP(),jn(),Dg(),OP(),AP(),JL(),YL={command:`check`,description:"Run `npm run check` (TypeScript type-check) across the current workspace. In a workspace root: walks every package with a `check` script (excludes @girs/*; honours --include/--exclude). In a single package: runs the local `check` script directly. Symmetric peer of `gjsify format` / `lint` / `fix`. (Legacy system-dep `gjsify check` is now `gjsify system-check` — see #254.)",builder:t=>t.option(`include`,{description:`Only run in workspaces matching these glob patterns (repeatable).`,type:`string`,array:!0}).option(`exclude`,{description:`Skip workspaces matching these glob patterns (repeatable). Always excludes @girs/*.`,type:`string`,array:!0}).option(`parallel`,{description:`Run workspace checks in parallel (default). Use --no-parallel to run them sequentially with full per-workspace output.`,type:`boolean`,alias:`p`,default:!0}).option(`jobs`,{description:`Max parallel workers (when --parallel). Default: os.cpus().length.`,type:`number`,alias:`j`}).option(`verbose`,{description:`Log the per-workspace command before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=findWorkspaceRoot(n);if(S&&n!==S&&readPackageJson$2(xn(n,`package.json`))?.scripts?.check){t.verbose&&ge.log(`[check] cwd=${n} → npm run check`);let{code:S}=await spawnToCompletion(detectPackageManager(),[`run`,`check`],{cwd:n,completion:`exit`});return process.exit(S??1)}if(!S)return ge.error("gjsify check: no workspace root found from cwd. Run inside a workspace (or a package within one) with `npm run check` defined."),process.exit(1);let C=discoverWorkspaces(S),N=[`@girs/*`,...t.exclude??[]],F=filterWorkspaces(C,{include:t.include,exclude:N}).filter(t=>t.manifest.scripts?.check!==void 0);if(F.length===0)return ge.error("gjsify check: no workspaces with a `check` script found."),process.exit(1);if(t.verbose&&ge.log(`[check] root=${S} workspaces=${F.length} parallel=${t.parallel?`yes`:`no`}`),!t.parallel){let n=0,S=0;for(let C of F){t.verbose&&ge.log(`[check] → ${C.name}`);let N=await runCheck(C,null);N!==0&&(S++,n===0&&(n=N))}return n!==0&&ge.error(`gjsify check: failures in ${S} workspace(s)`),process.exit(n)}let I=t.jobs??Math.max(1,cpus().length),H=[],W=0,q=[];for(let t=0;t<I;t++)q.push((async()=>{for(;;){let t=W++;if(t>=F.length)return;let n=F[t],S=await runCheck(n,n.name);S!==0&&H.push({name:n.name,code:S})}})());if(await Promise.all(q),H.length>0){ge.error(`\ngjsify check: ${H.length} of ${F.length} workspace(s) failed:`);for(let t of H)ge.error(` ✗ ${t.name} (exit ${t.code})`);return process.exit(1)}t.verbose&&ge.log(`\ngjsify check: ${F.length} workspace(s) green.`),process.exit(0)}}});function manifestPath(){let t=process.env.GJSIFY_SHOWCASES_MANIFEST;if(t)return t;let n=wn(fileURLToPath(import.meta.url)),S=[xn(n,`..`,`..`,`showcases.json`),xn(n,`..`,`showcases.json`)];return S.find(t=>existsSync(t))??S[0]}function discoverShowcases(){let t=manifestPath();if(!existsSync(t))return[];let n;try{n=JSON.parse(readFileSync(t,`utf-8`))}catch{return[]}if(!Array.isArray(n.showcases))return[];let S=n.showcases.map(t=>({name:t.name,packageName:t.package,category:t.category,description:t.description??``}));return S.sort((t,n)=>t.category.localeCompare(n.category)||t.name.localeCompare(n.name)),S}function findShowcase(t){return discoverShowcases().find(n=>n.name===t)}var ZL=__esmMin(()=>{Md(),jn(),Hn()});function parseSpec(t){if(!t)throw Error(`dlx: empty package spec`);if(t.startsWith(`./`)||t.startsWith(`../`)||bn(t)||existsSync(t))return{kind:`local`,path:vn(t)};let n=t,S,C=t.lastIndexOf(`@`);if(C>0&&(n=t.slice(0,C),S=t.slice(C+1)),!QL.test(n))throw Error(`dlx: invalid package name "${n}"`);return{kind:`registry`,name:n,version:S,spec:t}}var QL,$L=__esmMin(()=>{Md(),jn(),QL=/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/});function resolveGjsEntry(t,n){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`dlx: no package.json found at ${t}`);let C=JSON.parse(readFileSync(S,`utf-8`)),N=C.gjsify?.bin,F=C.gjsify?.main,I=C.main,H,W=null,q=!1;if(n!==null){if(!N||!N[n]){let S=N?Object.keys(N).join(`, `):`(none)`;throw Error(`dlx: package "${C.name??t}" has no GJS bin named "${n}" — known: ${S}`)}H=N[n],W=n}else if(N&&Object.keys(N).length===1){let t=Object.keys(N)[0];H=N[t],W=t}else F?H=F:I&&(H=I,q=!0);if(N&&Object.keys(N).length>1&&n===null){let n=Object.keys(N).join(`, `);throw Error(`dlx: package "${C.name??t}" defines multiple GJS bins — pass one of: ${n}`)}if(!H)throw Error(`dlx: package "${C.name??t}" has no GJS entry — set \`gjsify.main\` (or \`gjsify.bin\`) in its package.json`);let Y=vn(t,H);if(!existsSync(Y))throw Error(`dlx: GJS entry not found: ${Y}`);return{bundlePath:Y,binName:W,fromFallback:q}}function resolveNodeEntry(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`no package.json found at ${t}`);let S=JSON.parse(readFileSync(n,`utf-8`)),C=S.gjsify?.example?.node;if(C){let n=vn(t,C);if(!existsSync(n))throw Error(`declared node entry not found: ${n} (gjsify.example.node)`);return n}let N=S.gjsify?.main??(S.gjsify?.bin?Object.values(S.gjsify.bin)[0]:void 0)??S.main;if(!N)throw Error(`package "${S.name??t}" has no entry to derive a node bundle from — set \`gjsify.example.node\` to its \`--app node\` bundle path.`);let F=N.replace(/\.gjs\.(js|mjs|cjs)$/,``).replace(/\.(js|mjs|cjs)$/,``),I=[`${F}.node.mjs`,`${F}.node.js`,`${F}.node.cjs`];for(let n of I){let S=vn(t,n);if(existsSync(S))return S}throw Error(`package "${S.name??t}" has no \`--app node\` bundle — looked for ${I.join(`, `)}.\n Build one (e.g. \`gjsify build src/app.ts --app node --outfile dist/app.node.mjs\`) or set \`gjsify.example.node\` to its path.`)}var eR=__esmMin(()=>{Md(),jn()});function lexCompare(t,n){return t<n?-1:+(t>n)}function createCacheKey(t){let n=[...t.packages].sort(lexCompare),S=Object.entries(t.registries??{}).sort(([t],[n])=>lexCompare(t,n)),C=JSON.stringify([n,S]);return createHash(`sha256`).update(C).digest(`hex`)}function dlxCacheRoot(){let t=process.env.XDG_CACHE_HOME,n=xn(t&&t.length>0?t:xn(homedir(),`.cache`),`gjsify`,`dlx`);return mkdirSync(n,{recursive:!0}),n}function cacheDirFor(t){let n=xn(dlxCacheRoot(),t);return mkdirSync(n,{recursive:!0}),n}function makePrepareDir(t){let n=xn(t,`${Date.now().toString(16)}-${process.pid.toString(16)}`);return mkdirSync(n,{recursive:!0}),n}function getValidCachedPkg(t,n=nR){let S=xn(t,`pkg`),C;try{C=lstatSync(S)}catch(t){if(t.code===`ENOENT`)return;throw t}if(!C.isSymbolicLink())return;let N;try{N=realpathSync(S)}catch{return}return Date.now()-C.mtime.getTime()<=n*tR?N:void 0}function symlinkSwap(t,n,S={}){let C=S.junctions??dirLinksAreJunctions(),N=xn(t,`pkg`),F=xn(t,`pkg.tmp-${Date.now().toString(16)}-${process.pid.toString(16)}`);linkDirSync(F,n);try{C&&rmSync(N,{force:!0,recursive:!1,maxRetries:10,retryDelay:100}),renameSync(F,N)}catch(t){let S=t.code;if(S===`EBUSY`||S===`EPERM`||S===`EEXIST`||S===`EACCES`){rmSync(F,{force:!0});try{return realpathSync(N)}catch{return realpathSync(n)}}throw t}return realpathSync(N)}function resolveInstalledPkgDir(t,n){return vn(t,`node_modules`,n)}var tR,nR,rR=__esmMin(()=>{Kc(),Md(),Dg(),jn(),iL(),tR=6e4,nR=1440*7});async function ensurePkgDir(t,n){if(t.kind===`local`)return{pkgDir:t.path,cachedPkgName:null};let S=[t.spec,...n.extraSpecs??[]],C=cacheDirFor(createCacheKey({packages:S})),N=n.cacheMaxAge>0?getValidCachedPkg(C,n.cacheMaxAge):void 0;if(N)return{pkgDir:resolveInstalledPkgDir(N,t.name),cachedPkgName:t.name};let F=makePrepareDir(C),I=makeProgressReporter({enabled:!n.verbose});return await installPackages({prefix:F,specs:S,verbose:n.verbose,registry:n.registry,lockfile:!0,frozen:n.frozen,progress:I}),{pkgDir:resolveInstalledPkgDir(symlinkSwap(C,F),t.name),cachedPkgName:t.name}}function splitBinAndArgs(t,n,S){if(!n)return{binName:null,extraArgs:S};let C=xn(t,`package.json`);if(existsSync(C))try{let t=JSON.parse(readFileSync(C,`utf-8`)).gjsify?.bin;if(t&&Object.prototype.hasOwnProperty.call(t,n))return{binName:n,extraArgs:S}}catch{}return{binName:null,extraArgs:[n,...S]}}var iR,aR=__esmMin(()=>{_e(),yI(),$L(),eR(),rI(),rR(),wL(),Md(),jn(),iR={command:`dlx <spec> [binOrArg] [extraArgs..]`,description:`Run the GJS bundle of an npm-published package without installing it locally.`,builder:t=>t.parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}).positional(`spec`,{description:"Package spec (`name`, `name@version`, `@scope/name@spec`, or local path).",type:`string`,demandOption:!0}).positional(`binOrArg`,{description:"Optional bin name when the package defines `gjsify.bin` with multiple entries; otherwise treated as the first argument forwarded to the bundle. To pass a flag here (e.g. `--help`) use the `--` separator: `gjsify dlx <pkg> -- --help`.",type:`string`}).positional(`extraArgs`,{description:"Extra args forwarded to `gjs -m <bundle>`. Use `--` before flags to bypass gjsify-level parsing (`gjsify dlx <pkg> -- --help --verbose`).",type:`string`,array:!0}).option(`cache-max-age`,{description:`Cache TTL in minutes. Defaults to 7 days. Use 0 to bypass cache.`,type:`number`,default:1440*7}).option(`reinstall`,{description:`Bypass the cache for this run (alias for --cache-max-age=0).`,type:`boolean`,default:!1}).option(`frozen`,{description:`Use the project-local gjsify-lock.json verbatim — fail if missing or stale (no resolver pass).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging (passes --loglevel verbose to npm).`,type:`boolean`,default:!1}).option(`registry`,{description:`Registry URL override.`,type:`string`}),handler:async t=>{let n=parseSpec(t.spec),S=t.reinstall?0:t[`cache-max-age`],{pkgDir:C,cachedPkgName:N}=await ensurePkgDir(n,{verbose:t.verbose,registry:t.registry,cacheMaxAge:S,frozen:t.frozen}),F=[...t.extraArgs??[],...doubleDashArgs(t)],{binName:I,extraArgs:H}=splitBinAndArgs(C,t.binOrArg,F),W=resolveGjsEntry(C,I);W.fromFallback&&ge.warn(`[gjsify dlx] package "${N??n.kind}" declares no \`gjsify.main\` — falling back to package.json#main. Add \`gjsify.main\` to silence.`),await runGjsBundle(W.bundlePath,H,{completion:`exit`,exitOnSuccess:!0})}}});async function loadNpmrc(t){let n=[],S=xn(t,`.npmrc`);existsSync(S)&&n.push(readFileSync(S,`utf-8`));let C=process.env.NPM_CONFIG_USERCONFIG;if(C&&existsSync(C))n.push(readFileSync(C,`utf-8`));else{let t=xn(homedir(),`.npmrc`);existsSync(t)&&n.push(readFileSync(t,`utf-8`))}return parseNpmrc(n.join(`
|
|
941
|
+
`).replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(t,n)=>process.env[n]??``))}function hasAnyAuthToken(t){return Object.keys(t.authTokens).length>0}function hasAnyCredential(t){return hasAnyAuthToken(t)||Object.keys(t.basicAuth).length>0}var oR=__esmMin(()=>{Md(),Dg(),jn(),Jm()});function readCliVersion(){let t=cliVersion();return t===`unknown`?void 0:t}function runningAs(t){return t?`[gjsify ${t}] `:``}async function resolveShowcaseDir(t,n,S=[]){let C=resolveLocalShowcaseDir(t);if(C)return C;let{pkgDir:N}=await ensurePkgDir(parseSpec(n?`${t.packageName}@${n}`:t.packageName),{verbose:!1,cacheMaxAge:1440*7,frozen:!1,extraSpecs:S});return N}function resolveLocalShowcaseDir(t){try{let n=createRequire(import.meta.url).resolve(`${t.packageName}/package.json`);if(existsSync(n))return wn(n)}catch{}return null}function gtkRuntimeSpecs(t){let n=`${process.platform}-${process.arch}`;if(![`win32-x64`,`darwin-arm64`,`darwin-x64`].includes(n))return[];let S=`@gjsify/gtk-runtime-${n}`;return[t?`${S}@${t}`:S]}async function preflightDeclaredRuntimes(t,n){try{return declaredRuntimesFromPackument(await fetchPackument(t.packageName,{npmrc:await loadNpmrc(process.cwd()),fullMetadata:!0}),n)}catch{return}}function declaredRuntimesFromPackument(t,n){let S=n??t[`dist-tags`]?.latest,C=S?t.versions?.[S]:void 0;if(C)return readDeclaredRuntimes(C)}async function runShowcaseOnRuntime(t,n,S){if(resolveLocalShowcaseDir(t)===null){let C=await preflightDeclaredRuntimes(t,S);if(C!==void 0){let S=checkRuntimeSupported(n,C,t.name);if(!S.ok)return ge.error(S.message),process.exit(1)}}let C;try{C=await resolveShowcaseDir(t,S,[S?`@gjsify/node-gi@${S}`:`@gjsify/node-gi`,...gtkRuntimeSpecs(S)])}catch(n){return ge.error(`Could not resolve showcase "${t.name}": ${n.message}`),process.exit(1)}let N={};try{N=JSON.parse(readFileSync(`${C}/package.json`,`utf-8`))}catch{}let F=checkRuntimeSupported(n,readDeclaredRuntimes(N),t.name);if(!F.ok)return ge.error(F.message),process.exit(1);let I;try{I=resolveNodeEntry(C)}catch(C){let F=typeof N.name==`string`?`${N.name}@${S??`?`}`:t.packageName;return ge.error(`Cannot run showcase "${t.name}" on ${n}: ${C.message}\n\n ${F} declares --runtime ${n} but ships no \`--app node\` bundle, so that\n version of the showcase cannot run there. You are running gjsify ${S??`(unknown)`},\n and \`showcase\` pins the showcase to the CLI's own version.\n\n ${sR}\n\n Or run it on GJS, which every showcase ships: gjsify showcase ${t.name} --runtime gjs`),process.exit(1)}ge.log(`Running showcase: ${t.name} ${runningAs(S)}on ${n} (${I})\n`);try{await runRuntimeBundle(n,I,[],{completion:`exit`,exitOnSuccess:!0})}catch(t){return ge.error(`${t.message}\n\n The showcase and the \`@gjsify/node-gi\` bridge it needs are both installed by THIS CLI\n (gjsify ${S??`(unknown)`}) into its own cache, so a missing bridge points at the CLI\n rather than at anything in your project.\n\n ${sR}`),process.exit(1)}}var sR,cR,lR=__esmMin(()=>{_e(),ZL(),JP(),Al(),jn(),Md(),aR(),Jm(),oR(),$L(),Xm(),eR(),xI(),P_(),sR=`A package runner reuses a CACHED copy of an unpinned bin. Force the current one:
|
|
942
942
|
npx @gjsify/cli@latest showcase <name>
|
|
943
943
|
bunx @gjsify/cli@latest showcase <name>
|
|
944
|
-
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,
|
|
944
|
+
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,cR={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:M_,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:
|
|
945
945
|
`);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: ${M_.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:
|
|
946
|
-
`);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(()=>(
|
|
947
|
-
`),N(Error(CR));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};nn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:hR[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 SR,CR,wR=__esmMin(()=>{_e(),rn(),wd(),gR(),_R(),SR={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},CR=`Cancelled by user`}),TR,ER=__esmMin(()=>{_e(),xR(),wR(),TR={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:dR})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Tn(t,$(t));return vn(wn(t),n)}var DR,OR,kR=__esmMin(()=>{_e(),w_(),hd(),jn(),yu(),DR=promisify(execFile),OR={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.xml),S=t.target?vn(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?vn(t.sourcedir):wn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(wn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await DR(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=xn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var AR=__esmMin(()=>{w_(),jn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=xn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(xn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Tn(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:xn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=xn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${xn(n,t.filename)}`,xn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await jR(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Tn(S.replace(/\.in$/,``)):`${t}.xml`}}var jR,MR,NR=__esmMin(()=>{_e(),w_(),hd(),Dg(),jn(),yu(),AR(),jR=promisify(execFile),MR={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.poDir),S=vn(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?vn(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),PR,FR,IR=__esmMin(()=>{_e(),w_(),hd(),jn(),yu(),PR=promisify(execFile),FR={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.schemadir),S=t.targetdir?vn(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await PR(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=vn(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var LR,RR=__esmMin(()=>{Md(),jn(),LR=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`50`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var zR,BR,VR=__esmMin(()=>{zR=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],BR=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of UR){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?BR:zR),cleanup:W??[]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${HR}. 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 HR,UR,WR=__esmMin(()=>{VR(),HR=`1.0.0`,UR=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return GR}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:`${t.command}${execFieldCode(N)}`,APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`),t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}return F.push(`</component>`),F.join(`
|
|
946
|
+
`);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(()=>($G(),QG));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=wn(fileURLToPath(import.meta.url)),n=[xn(t,`..`,`dist-templates`),xn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,xn(wn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=xn(t,S),N=xn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=uR[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 uR,dR=__esmMin(()=>{Md(),Al(),jn(),Hn(),uR={"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,...pR[t]].join(` `)}function runScriptCommand(t){return mR[t]}function packageManagersForRuntime(t){return hR[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 fR,pR,mR,hR,gR,_R=__esmMin(()=>{fR=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],pR={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},mR={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},hR={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},gR={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 vR=__esmMin(()=>{_R()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=vn(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[yR,n],[bR,applicationIdFor(n)]],C=new Set([`node_modules`,`dist`,`lib`]),N=[t];for(;N.length>0;){let t=N.pop();for(let n of readdirSync(t,{withFileTypes:!0})){let F=xn(t,n.name);if(n.isDirectory()){C.has(n.name)||N.push(F);continue}if(!n.isFile())continue;let I=n.name.lastIndexOf(`.`),H=I>=0?n.name.slice(I):``;if(!xR.has(H))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,n]of S)q=q.replaceAll(t,n);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}}function templateManifest(t){try{return JSON.parse(readFileSync(xn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var yR,bR,xR,SR=__esmMin(()=>{_e(),w_(),Md(),jn(),dR(),_R(),vR(),yR=`new-gjsify-app`,bR=`org.gjsify.example`,xR=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`])});function isCancelled(t){return t instanceof Error&&t.message===wR}function render(t,n,S){S||tn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${CR.cyan}❯${CR.reset}`:` `,F=S===n?`${CR.bold}${CR.green}${C.label}${CR.reset}`:C.label,I=C.description?` ${CR.dim}${C.description}${CR.reset}`:``;tn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;tn.write(`${CR.bold}${t}${CR.reset} ${CR.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${CR.reset}\n`),render(n,F,!0),emitKeypressEvents(nn),nn.isTTY&&nn.setRawMode(!0),nn.resume();let cleanup=()=>{nn.removeListener(`keypress`,onKeypress),nn.isTTY&&nn.setRawMode(!1),nn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),tn.write(`
|
|
947
|
+
`),N(Error(wR));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};nn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:gR[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 CR,wR,TR=__esmMin(()=>{_e(),rn(),wd(),_R(),vR(),CR={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},wR=`Cancelled by user`}),ER,DR=__esmMin(()=>{_e(),SR(),TR(),ER={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:fR})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Tn(t,$(t));return vn(wn(t),n)}var OR,kR,AR=__esmMin(()=>{_e(),w_(),hd(),jn(),yu(),OR=promisify(execFile),kR={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.xml),S=t.target?vn(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?vn(t.sourcedir):wn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(wn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await OR(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=xn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var jR=__esmMin(()=>{w_(),jn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=xn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(xn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Tn(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:xn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=xn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${xn(n,t.filename)}`,xn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await MR(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Tn(S.replace(/\.in$/,``)):`${t}.xml`}}var MR,NR,PR=__esmMin(()=>{_e(),w_(),hd(),Dg(),jn(),yu(),jR(),MR=promisify(execFile),NR={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.poDir),S=vn(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?vn(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),FR,IR,LR=__esmMin(()=>{_e(),w_(),hd(),jn(),yu(),FR=promisify(execFile),IR={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=vn(t.schemadir),S=t.targetdir?vn(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await FR(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=vn(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var RR,zR=__esmMin(()=>{Md(),jn(),RR=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`50`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var BR,VR,HR=__esmMin(()=>{BR=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],VR=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of WR){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?VR:BR),cleanup:W??[]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${UR}. 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 UR,WR,GR=__esmMin(()=>{HR(),UR=`1.0.0`,WR=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return KR}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:`${t.command}${execFieldCode(N)}`,APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`),t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}return F.push(`</component>`),F.join(`
|
|
948
948
|
`)+`
|
|
949
|
-
`}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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var
|
|
949
|
+
`}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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var KR,qR=__esmMin(()=>{KR=`[Desktop Entry]
|
|
950
950
|
Name={{NAME}}
|
|
951
951
|
Comment={{SUMMARY}}
|
|
952
952
|
Exec={{COMMAND}}
|
|
@@ -960,7 +960,7 @@ StartupWMClass={{APP_ID}}
|
|
|
960
960
|
`}function loadFlathubCliTemplate(){return`{
|
|
961
961
|
"skip-icons-check": true
|
|
962
962
|
}
|
|
963
|
-
`}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(t){return validateAppMetadata(toMetadataInputs(t))}function renderMetainfoApp(t){return renderMetainfoApp$1(toMetadataInputs(t))}function renderMetainfoCli(t){return renderMetainfoCli$1(toMetadataInputs(t))}function renderDesktop(t){return renderDesktopEntry(toMetadataInputs(t))}function renderFlathubJson(t){return t===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var
|
|
963
|
+
`}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(t){return validateAppMetadata(toMetadataInputs(t))}function renderMetainfoApp(t){return renderMetainfoApp$1(toMetadataInputs(t))}function renderMetainfoCli(t){return renderMetainfoCli$1(toMetadataInputs(t))}function renderDesktop(t){return renderDesktopEntry(toMetadataInputs(t))}function renderFlathubJson(t){return t===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var JR=__esmMin(()=>{qR()});function oxcBindingSuffix(){let t=process.platform,n=process.arch,S;if(t===`linux`)S=`linux`;else if(t===`darwin`)S=`darwin`;else if(t===`win32`)S=`win32`;else throw Error(`[gjsify oxc] Unsupported platform: ${t}`);let C;if(n===`x64`)C=`x64`;else if(n===`arm64`)C=`arm64`;else throw Error(`[gjsify oxc] Unsupported arch on ${S}: ${n}`);if(S===`linux`){let t=hostLibc(`linux`)===`musl`?`musl`:`gnu`;return`${S}-${C}-${t}`}return S===`win32`?`${S}-${C}-msvc`:`${S}-${C}`}function bindingPackageName(t){return`${t===`oxlint`?`@oxlint`:`@oxfmt`}/binding-${oxcBindingSuffix()}`}function probeNodeModules(t,n,S){let C=xn(t,`node_modules`,n,S);return existsSync(C)?C:null}function findOxcLauncher(t,n=process.cwd()){let S=xn(`bin`,t),C=probeNodeModules(n,t,S);if(C)return C;let N=findWorkspaceRoot(n);if(N&&N!==n){let n=probeNodeModules(N,t,S);if(n)return n}let F=vn(n,`..`);for(let n=0;n<6;n++){let n=probeNodeModules(F,t,S);if(n)return n;let C=vn(F,`..`);if(C===F)break;F=C}throw new OxcNotFoundError(t,n)}function findOxlintConfig(t=process.cwd()){return findConfigFile(t,[`.oxlintrc.json`])}function findOxfmtConfig(t=process.cwd()){return findConfigFile(t,[`.oxfmtrc`,`.oxfmtrc.json`])}function findConfigFile(t,n){let S=t;for(let t=0;t<12;t++){for(let t of n){let n=xn(S,t);if(existsSync(n))return n}let t=vn(S,`..`);if(t===S)break;S=t}return null}async function tryLoadNativeOxfmt(){return YR||(YR=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let t=`@gjsify/oxfmt-native`,n=await import(pathToFileURL(resolveNpmPackage(t,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(t)).href);if(!n.hasNativeOxfmt())return null;let S;try{let t=pathToFileURL(resolveNpmPackage(`@gjsify/utils/native-library`,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(`@gjsify/utils/native-library`)).href;({openNativeLibrary:S}=await import(t))}catch(t){return XR=t instanceof Error?t:Error(String(t)),null}return XR=S(`GjsifyOxfmt`),XR?null:n}catch{return null}})(),YR)}async function shouldUseNativeOxfmt(){let t=(globalThis.process?.env??{}).GJSIFY_OXFMT;if(t===`npm`)return!1;if(t===`native`){if(!await tryLoadNativeOxfmt())throw Error(`GJSIFY_OXFMT=native but @gjsify/oxfmt-native is not loadable (no prebuild for this architecture, or not running under GJS).`+(XR?`\n${XR.message}`:``));return!0}if(!isGjs())return!1;let n=await tryLoadNativeOxfmt()!==null;return!n&&XR&&ge.debug(XR.message),n}async function runOxc(t,n,S={}){if(t===`oxfmt`&&await shouldUseNativeOxfmt()){let t=await tryLoadNativeOxfmt();if(!t)throw Error(`@gjsify/oxfmt-native not loadable`);return S.verbose&&ge.log(`[gjsify oxc] @gjsify/oxfmt-native (in-process) ${n.join(` `)}`),t.runOxfmt(n)}return spawnOxcLauncher(t,n,S)}function spawnOxcLauncher(t,n,S={}){let C=S.cwd??process.cwd(),N=findOxcLauncher(t,C),F=nodeBinary();return S.verbose&&ge.log(`[gjsify oxc] ${F} ${N} ${n.join(` `)}`),spawnToCompletion(F,[N,...n],{completion:`return`,cwd:C,notFound:()=>new OxcNotFoundError(t,C,F)}).then(({code:n,signal:S})=>S===null?n??0:(ge.error(`[gjsify oxc] ${t} terminated by signal ${S}`),1))}function runOxlint(t,n={}){return runOxc(`oxlint`,t,n)}function runOxfmt(t,n={}){return runOxc(`oxfmt`,t,n)}function loadOxlintTemplate(){return`{
|
|
964
964
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
|
965
965
|
"categories": {
|
|
966
966
|
"correctness": "error"
|
|
@@ -1049,11 +1049,11 @@ StartupWMClass={{APP_ID}}
|
|
|
1049
1049
|
"**/*.metainfo.xml"
|
|
1050
1050
|
]
|
|
1051
1051
|
}
|
|
1052
|
-
`}function printOxcNotFound(t){ge.error(t.message)}function setOxcExitCode(t){process.exitCode=t,t!==0&&gjsExit(t)}function hasOxcDevDep(t=process.cwd(),n=`oxfmt`){let S=xn(t,`package.json`);if(!existsSync(S))return!1;try{let t=JSON.parse(readFileSync(S,`utf-8`));return!!(t?.devDependencies?.[n]||t?.dependencies?.[n])}catch{return!1}}var OxcNotFoundError,
|
|
1052
|
+
`}function printOxcNotFound(t){ge.error(t.message)}function setOxcExitCode(t){process.exitCode=t,t!==0&&gjsExit(t)}function hasOxcDevDep(t=process.cwd(),n=`oxfmt`){let S=xn(t,`package.json`);if(!existsSync(S))return!1;try{let t=JSON.parse(readFileSync(S,`utf-8`));return!!(t?.devDependencies?.[n]||t?.dependencies?.[n])}catch{return!1}}var OxcNotFoundError,YR,XR,ZR=__esmMin(()=>{_e(),Md(),jn(),Al(),Hn(),lL(),AP(),MP(),tF(),xI(),j_(),t_(),OxcNotFoundError=class extends Error{tool;cwd;missingInterpreter;constructor(t,n,S){let C=(()=>{try{return bindingPackageName(t)}catch{return`@${t===`oxlint`?`oxlint`:`oxfmt`}/binding-<platform>`}})();super(S===void 0?`[gjsify oxc] ${t} not found.\n Expected: ${t}/bin/${t} in node_modules of ${n} or any workspace root above it.\n Install it via: gjsify install -D ${t}\n (this adds ${t} to devDependencies; the matching ${C} napi binding lands automatically as an optionalDependency.)`:`[gjsify oxc] cannot run ${t}: no \`${S}\` binary on PATH.\n ${t} IS installed — its launcher was found. What is missing is the\n interpreter that runs it: ${t}'s launcher is a Node ESM script.\n`+(t===`oxfmt`?" For a Node-free formatter install the GI bridge:\n gjsify install -D @gjsify/oxfmt-native\n (`gjsify format`/`fix` then run oxfmt in-process under GJS.)":" oxlint has no native GJS bridge yet — its JS-plugin host lives in the\n Node launcher — so `gjsify lint` needs Node on the host for now.")),this.tool=t,this.cwd=n,this.missingInterpreter=S,this.name=`OxcNotFoundError`}},YR=null,XR=null});function writeIfFresh(t,n,S,C){return existsSync(t)&&!S?(ge.log(`[gjsify flatpak init] skipped ${C}: ${t} (exists; --force to overwrite)`),null):(mkdirSync(wn(t),{recursive:!0}),writeFileSync(t,n,`utf-8`),ge.log(`[gjsify flatpak init] wrote ${C}: ${t}`),t)}function friendlyName(t,n){if(t.startsWith(`@`))return t.slice(t.indexOf(`/`)+1);if(t===n){let t=n.split(`.`);return t[t.length-1]??n}return t}function mergeArrays(t,n){if(!(!t?.length&&!n?.length))return[...t??[],...n??[]]}function deriveModuleName(t){let n=t.split(`.`);return n[n.length-1]||t}var QR,$R=__esmMin(()=>{_e(),Md(),jn(),zR(),HR(),GR(),JR(),YF(),ZR(),QR={command:`init`,description:"Generate Flatpak manifest + MetaInfo XML + .desktop + flathub.json from `gjsify.flatpak` config.",builder:t=>t.option(`app-id`,{description:"Reverse-DNS app id (default: `gjsify.flatpak.appId` or package.json#name)",type:`string`}).option(`runtime`,{description:`Runtime family`,choices:[`gnome`,`freedesktop`]}).option(`runtime-version`,{description:`Runtime version (default: gnome -> 50, freedesktop -> 24.08)`,type:`string`}).option(`kind`,{description:`App kind: "app" (default, desktop) or "cli" (console-application MetaInfo, no .desktop)`,choices:[`app`,`cli`]}).option(`cli-only`,{description:"(Deprecated) Alias for `--kind cli`. Use --kind instead.",type:`boolean`,default:!1}).option(`manifest`,{description:"Output path for the manifest. Default: `<app-id>.json` in cwd.",type:`string`,normalize:!0}).option(`metainfo`,{description:"Output path for the MetaInfo XML. Default: `data/<app-id>.metainfo.xml.in` in cwd.",type:`string`,normalize:!0}).option(`desktop`,{description:"Output path for the .desktop entry (app kind only). Default: `data/<app-id>.desktop.in`.",type:`string`,normalize:!0}).option(`flathub-json`,{description:"Output path for the flathub.json policy stub. Default: `flathub.json` in cwd.",type:`string`,normalize:!0}).option(`command`,{description:`Binary name in /app/bin (default: app id)`,type:`string`}).option(`sdk-extension`,{description:`Extra SDK extension (repeatable)`,type:`string`,array:!0}).option(`finish-arg`,{description:`Extra finish-arg (repeatable). Override defaults entirely with multiple --finish-arg.`,type:`string`,array:!0}).option(`force`,{description:`Overwrite existing output files (manifest, metainfo, desktop, flathub.json)`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the resolved manifest fields before writing`,type:`boolean`,default:!1}).option(`format`,{description:"Run `oxfmt --write` on the generated JS/TS files when `oxfmt` is detected in the project. Default: true. Pass --no-format to skip. Note: oxfmt formats JS/TS only — the JSON/XML/.desktop manifests generated here are not reformatted (CSS/JSON formatting was dropped in the oxc migration).",type:`boolean`,default:!0}),handler:async t=>{let n=await new Config().forCommand().catch(()=>({})),S=n.flatpak??{},C=process.cwd(),N=readPackageJson(C),F=t.appId??S.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak init: no app id available. Pass --app-id, set gjsify.flatpak.appId in package.json, or rename the package to a reverse-DNS id like org.example.MyApp.`);let I=t.kind??S.kind??(t.cliOnly?`cli`:`app`),H=pickFlatpakBuildKeys(n.ship?.flatpak,S).values,{runtime:W,runtimeId:q,sdk:Y,runtimeVersion:X}=resolveRuntime(H,{runtime:t.runtime,runtimeVersion:t.runtimeVersion}),Z=mergeArrays(H.sdkExtensions,t.sdkExtension),te=H.appendPath??(Z?.length?deriveAppendPath(Z):void 0),ne=t.command??S.command??F,re=t.finishArg,ie=re===void 0?H.finishArgs??(I===`cli`?VR:BR):re,ae={id:F,runtime:q,"runtime-version":X,sdk:Y};Z?.length&&(ae[`sdk-extensions`]=Z),te?.length&&(ae[`build-options`]={"append-path":te.join(`:`)}),ae.command=ne,ae[`finish-args`]=ie;let oe=H.cleanup;oe?.length&&(ae.cleanup=oe);let Q=[];S.modules?.length?Q.push(...S.modules):(S.extraModules?.length&&Q.push(...S.extraModules),Q.push({name:deriveModuleName(F),buildsystem:`meson`,sources:[{type:`dir`,path:`.`}]})),ae.modules=Q;let se=[],trackWrite=t=>{t&&se.push(t)};trackWrite(writeIfFresh(vn(C,t.manifest??`${F}.json`),JSON.stringify(ae,null,2)+`
|
|
1053
1053
|
`,t.force??!1,`manifest`));let ce=N.name??F,le={appId:F,name:S.name??friendlyName(ce,F),command:ne,kind:I,flatpak:S},ue=validateScaffoldInputs(le);if(ue.length>0){ge.warn(`[gjsify flatpak init] Manifest written, but MetaInfo / .desktop are skipped — config gaps:`);for(let t of ue)ge.warn(` - ${t.field}: ${t.hint}`);ge.warn(`
|
|
1054
|
-
Fill these fields in package.json#gjsify.flatpak (or .gjsifyrc.*) and re-run with --force.`)}else{let n=I===`cli`?renderMetainfoCli(le):renderMetainfoApp(le);trackWrite(writeIfFresh(vn(C,t.metainfo??`data/${F}.metainfo.xml.in`),n,t.force??!1,`metainfo`)),I===`app`&&(trackWrite(writeIfFresh(vn(C,t.desktop??`data/${F}.desktop.in`),renderDesktop(le),t.force??!1,`desktop`)),S.icon||ge.warn(`[gjsify flatpak init] No gjsify.flatpak.icon set. Flathub requires a scalable SVG at\n data/icons/hicolor/scalable/apps/${F}.svg`)),trackWrite(writeIfFresh(vn(C,t.flathubJson??`flathub.json`),renderFlathubJson(I),t.force??!1,`flathub.json`))}let de=se.filter(t=>/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t));if(de.length>0&&t.format!==!1&&hasOxcDevDep(C))try{await runOxfmt([`--write`,...de],{cwd:C})}catch(t){if(t instanceof OxcNotFoundError)ge.warn("[gjsify flatpak init] post-format skipped: oxfmt declared but binding not installed. Run `gjsify install` then re-run with --force, or pass --no-format.");else throw t}t.verbose&&(ge.log(`[gjsify flatpak init] kind=${I} runtime=${q} ${X} sdk=${Y}`),ge.log(`[gjsify flatpak init] command=${ne} finish-args=${JSON.stringify(ie)}`))}}});function findDefaultManifest(t){return scanForManifest(t)??`flatpak.json`}function scanForManifest(t){let n=[];try{n=readdirSync(t)}catch{return}for(let S of n)if(S.endsWith(`.json`)&&!(S===`package.json`||S===`tsconfig.json`||S.startsWith(`.`)))try{let n=JSON.parse(readFileSync(vn(t,S),`utf-8`));if(typeof n.id==`string`&&typeof n.runtime==`string`&&Array.isArray(n.modules))return S}catch{}}function readManifestAppId(t){let n=readFileSync(t,`utf-8`),S=JSON.parse(n);if(typeof S.id!=`string`)throw Error(`gjsify flatpak build: ${t} has no string "id" field`);return S.id}async function runFlatpakBuilder(t,n){return runProc(`flatpak-builder`,t,n,{notFoundHint:"flatpak-builder not found. Install via your distro (Fedora: `sudo dnf install flatpak-builder`)."})}async function runFlatpak(t,n){return runProc(`flatpak`,t,n,{notFoundHint:`flatpak not found. Install via your distro and add Flathub: see https://flathub.org/setup.`})}async function runTar(t,n){return runProc(`tar`,t,n,{notFoundHint:`tar not found.`})}async function runProc(t,n,S,C){S.verbose&&ge.log(`[gjsify flatpak] ${t} ${n.join(` `)}`);let{code:N}=await spawnToCompletion(t,n,{completion:`exit`,notFound:()=>Error(`gjsify flatpak: ${C.notFoundHint}`)});if(N!==0)throw Error(`gjsify flatpak: ${t} exited with status ${N}`)}var
|
|
1054
|
+
Fill these fields in package.json#gjsify.flatpak (or .gjsifyrc.*) and re-run with --force.`)}else{let n=I===`cli`?renderMetainfoCli(le):renderMetainfoApp(le);trackWrite(writeIfFresh(vn(C,t.metainfo??`data/${F}.metainfo.xml.in`),n,t.force??!1,`metainfo`)),I===`app`&&(trackWrite(writeIfFresh(vn(C,t.desktop??`data/${F}.desktop.in`),renderDesktop(le),t.force??!1,`desktop`)),S.icon||ge.warn(`[gjsify flatpak init] No gjsify.flatpak.icon set. Flathub requires a scalable SVG at\n data/icons/hicolor/scalable/apps/${F}.svg`)),trackWrite(writeIfFresh(vn(C,t.flathubJson??`flathub.json`),renderFlathubJson(I),t.force??!1,`flathub.json`))}let de=se.filter(t=>/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t));if(de.length>0&&t.format!==!1&&hasOxcDevDep(C))try{await runOxfmt([`--write`,...de],{cwd:C})}catch(t){if(t instanceof OxcNotFoundError)ge.warn("[gjsify flatpak init] post-format skipped: oxfmt declared but binding not installed. Run `gjsify install` then re-run with --force, or pass --no-format.");else throw t}t.verbose&&(ge.log(`[gjsify flatpak init] kind=${I} runtime=${q} ${X} sdk=${Y}`),ge.log(`[gjsify flatpak init] command=${ne} finish-args=${JSON.stringify(ie)}`))}}});function findDefaultManifest(t){return scanForManifest(t)??`flatpak.json`}function scanForManifest(t){let n=[];try{n=readdirSync(t)}catch{return}for(let S of n)if(S.endsWith(`.json`)&&!(S===`package.json`||S===`tsconfig.json`||S.startsWith(`.`)))try{let n=JSON.parse(readFileSync(vn(t,S),`utf-8`));if(typeof n.id==`string`&&typeof n.runtime==`string`&&Array.isArray(n.modules))return S}catch{}}function readManifestAppId(t){let n=readFileSync(t,`utf-8`),S=JSON.parse(n);if(typeof S.id!=`string`)throw Error(`gjsify flatpak build: ${t} has no string "id" field`);return S.id}async function runFlatpakBuilder(t,n){return runProc(`flatpak-builder`,t,n,{notFoundHint:"flatpak-builder not found. Install via your distro (Fedora: `sudo dnf install flatpak-builder`)."})}async function runFlatpak(t,n){return runProc(`flatpak`,t,n,{notFoundHint:`flatpak not found. Install via your distro and add Flathub: see https://flathub.org/setup.`})}async function runTar(t,n){return runProc(`tar`,t,n,{notFoundHint:`tar not found.`})}async function runProc(t,n,S,C){S.verbose&&ge.log(`[gjsify flatpak] ${t} ${n.join(` `)}`);let{code:N}=await spawnToCompletion(t,n,{completion:`exit`,notFound:()=>Error(`gjsify flatpak: ${C.notFoundHint}`)});if(N!==0)throw Error(`gjsify flatpak: ${t} exited with status ${N}`)}var ez,tz=__esmMin(()=>{_e(),Md(),jn(),j_(),ez={command:`build [manifest]`,description:"Build the Flatpak via `flatpak-builder`. Wraps a typical install + export + bundle + tarball pipeline.",builder:t=>t.positional(`manifest`,{description:`Path to the Flatpak manifest (default: first *.json that looks like a manifest in cwd)`,type:`string`,normalize:!0}).option(`build-dir`,{description:`flatpak-builder working directory`,type:`string`,default:`flatpak-build`,normalize:!0}).option(`install`,{description:"After build, run `flatpak-builder --user --install` to install locally",type:`boolean`,default:!1}).option(`repo`,{description:"Export the build into the given OSTree repo (passes `--repo=<dir>` to flatpak-builder)",type:`string`,normalize:!0}).option(`bundle`,{description:"After --repo export, build a single-file bundle (`flatpak build-bundle`) at this path",type:`string`,normalize:!0}).option(`tarball`,{description:`Create a tarball of the build dir (parity with the legacy build-flatpak.sh tarball step)`,type:`string`,normalize:!0}).option(`force-clean`,{description:`Pass --force-clean to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`sandbox`,{description:`Pass --sandbox to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`delete-build-dirs`,{description:`Pass --delete-build-dirs to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`install-deps-from`,{description:"Pass --install-deps-from to flatpak-builder (e.g. `flathub`)",type:`string`}).option(`verbose`,{description:`Print the underlying flatpak-builder invocations`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=vn(n,t.manifest??findDefaultManifest(n));if(!existsSync(S))throw Error(`gjsify flatpak build: manifest ${S} not found`);let C=vn(n,t.buildDir??`flatpak-build`),N=[];if(t.forceClean!==!1&&N.push(`--force-clean`),t.sandbox!==!1&&N.push(`--sandbox`),t.deleteBuildDirs!==!1&&N.push(`--delete-build-dirs`),t.installDepsFrom&&N.push(`--install-deps-from=${t.installDepsFrom}`),existsSync(C)&&rmSync(C,{recursive:!0,force:!0}),await runFlatpakBuilder([...N,C,S],{verbose:t.verbose}),t.install&&await runFlatpakBuilder([`--user`,`--install`,`--force-clean`,C,S],{verbose:t.verbose}),t.repo){let N=vn(n,t.repo);mkdirSync(wn(N),{recursive:!0}),await runFlatpakBuilder([`--repo=${N}`,`--force-clean`,C,S],{verbose:t.verbose})}if(t.bundle){if(!t.repo)throw Error(`gjsify flatpak build: --bundle requires --repo (the bundle is built from the OSTree repo).`);let C=vn(n,t.bundle);mkdirSync(wn(C),{recursive:!0}),await runFlatpak([`build-bundle`,vn(n,t.repo),C,readManifestAppId(S)],{verbose:t.verbose})}if(t.tarball){let S=vn(n,t.tarball);mkdirSync(wn(S),{recursive:!0}),await runTar([`-czf`,S,`-C`,C,`.`],{verbose:t.verbose})}return ge.log(`[gjsify flatpak build] done (${C})`),process.exit(0)}}});function detectLockfile(t){return existsSync(vn(t,`yarn.lock`))?`yarn.lock`:existsSync(vn(t,`package-lock.json`))?`package-lock.json`:`yarn.lock`}var nz,rz=__esmMin(()=>{_e(),j_(),Md(),jn(),nz={command:`deps`,description:"Generate Flatpak offline-cache sources from a yarn.lock / package-lock.json (wraps `flatpak-node-generator`).",builder:t=>t.option(`lockfile`,{description:`Path to lockfile (default: yarn.lock or package-lock.json in cwd)`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile type. Default: detected from filename.`,choices:[`yarn`,`npm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:`flatpak-node-sources.json`,normalize:!0}).option(`xdg-layout`,{description:`Pass --xdg-layout (recommended for Yarn Berry / PnP setups)`,type:`boolean`,default:!0}).option(`electron-node-headers`,{description:`Pass --electron-node-headers`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the underlying flatpak-node-generator invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=vn(n,t.lockfile??detectLockfile(n));if(!existsSync(S))throw Error(`gjsify flatpak deps: lockfile ${S} not found (use --lockfile to override)`);let C=t.type??(S.endsWith(`package-lock.json`)?`npm`:`yarn`),N=vn(n,t.out??`flatpak-node-sources.json`);mkdirSync(wn(N),{recursive:!0});let F=[C,S,`-o`,N];t.xdgLayout!==!1&&F.push(`--xdg-layout`),t.electronNodeHeaders&&F.push(`--electron-node-headers`),t.verbose&&ge.log(`[gjsify flatpak deps] flatpak-node-generator ${F.join(` `)}`);let I=await spawnToCompletion(`flatpak-node-generator`,F,{completion:`return`,notFound:()=>Error("gjsify flatpak deps: flatpak-node-generator not found. Install via `pipx install flatpak-node-generator` (see https://github.com/flatpak/flatpak-builder-tools/tree/master/node).")});if(I.code!==0)throw Error(`gjsify flatpak deps: flatpak-node-generator exited with ${describeExit(I)}`);ge.log(`[gjsify flatpak deps] wrote ${N}`)}}});function classifyDependency(t,n,S){let C=S.get(t);return C&&!az.test(n)?{kind:`workspace`,target:C}:n.startsWith(`workspace:`)?{kind:`missing-workspace`}:az.test(n)?{kind:`ignored`}:{kind:`external`}}function planFocus(t,n,S){let C=new Map(t.map(t=>[t.name,t])),N=[...new Set(n)].filter(t=>!C.has(t));if(N.length>0){let t=[...C.keys()].sort(),n=t.slice(0,oz).join(`, `),F=t.length>oz?`, … (${t.length-oz} more)`:``;throw Error(`${S}: --focus names unknown workspace(s): ${N.join(`, `)}. Pass a package name from a workspace's package.json. Known workspaces: ${n}${F}.`)}let F=new Set(n.map(t=>C.get(t))),I=new Set;for(let t of F)for(let n of iz)for(let[S,N]of Object.entries(t.manifest[n]??{})){if(typeof N!=`string`)continue;let t=classifyDependency(S,N,C);t.kind===`workspace`?F.add(t.target):t.kind===`external`&&I.add(`${S}@${N}`)}return{workspaces:t.filter(t=>F.has(t)),specs:[...I]}}var iz,az,oz,sz=__esmMin(()=>{iz=[`dependencies`,`devDependencies`,`optionalDependencies`],az=/^(link|file|portal|git\+|https?):/,oz=20});function parseSri(t){if(!t)return null;let n=t.indexOf(`-`);if(n<=0||n===t.length-1)return null;let S=t.slice(0,n),C=t.slice(n+1).replace(/=+$/,``),N=Xe.from(C,`base64`).toString(`hex`);return N.length<4?null:{algorithm:S,hex:N}}function parseNpmLike(t){let n=[],S=t,C=S.packages;if(C&&typeof C==`object`){for(let t of Object.values(C))t?.resolved&&t.integrity&&n.push({url:t.resolved,integrity:t.integrity});if(n.length>0)return n}return S.dependencies&&typeof S.dependencies==`object`&&collectV1Deps(S.dependencies,n),n}function collectV1Deps(t,n){for(let S of Object.values(t))S?.resolved&&S.integrity&&n.push({url:S.resolved,integrity:S.integrity}),S?.dependencies&&collectV1Deps(S.dependencies,n)}function parseYarnClassic(t){if(/^__metadata:/m.test(t))throw Error("gjsify flatpak sources: Yarn Berry (v2+) yarn.lock is not supported — its `checksum` is a cache hash, not a tarball SRI. Run `gjsify install` to produce a gjsify-lock.json, or use a classic (v1) yarn.lock.");let n=[],S=0;for(let C of t.split(/\n\s*\n/)){let t=C.match(/^\s+resolved\s+"([^"]+)"/m);if(!t)continue;let N=t[1].replace(/#.*$/,``),F=C.match(/^\s+integrity\s+(\S+)/m);if(!F){S++;continue}n.push({url:N,integrity:F[1]})}return S>0&&ge.warn(`[gjsify flatpak sources] ${S} yarn.lock entr(y/ies) had no integrity (pre-1.x format) and were skipped — re-lock with a modern yarn or use \`gjsify install\`.`),n}function parsePnpm(t){let n=[],S=!1,C=null;for(let N of t.split(`
|
|
1055
1055
|
`)){let t=N.replace(/\r$/,``);if(/^packages:\s*$/.test(t)){S=!0;continue}if(S&&/^[^\s#]/.test(t)&&(S=!1),!S)continue;let F=t.match(/^ {2}(?:'([^']+)'|"([^"]+)"|([^\s#][^:]*)):\s*$/);if(F){C=F[1]??F[2]??F[3]??null;continue}let I=t.match(/resolution:\s*\{([^}]*)\}/);if(I&&C){let t=I[1].match(/integrity:\s*(sha\d+-[A-Za-z0-9+/=]+)/);if(!t)continue;let S=I[1].match(/tarball:\s*([^\s,}]+)/),N=S?S[1]:reconstructNpmTarballUrl(C);N&&n.push({url:N,integrity:t[1]})}}return n}function reconstructNpmTarballUrl(t){let n,S;if(t.startsWith(`/`)){let C=t.slice(1).replace(/_.*$/,``),N=C.lastIndexOf(`/`);if(N<=0)return null;n=C.slice(0,N),S=C.slice(N+1)}else{let C=t.replace(/\(.*\)$/,``),N=C.lastIndexOf(`@`);if(N<=0)return null;n=C.slice(0,N),S=C.slice(N+1)}if(!n||!S||/[@:/]/.test(S))return null;let C=n.slice(n.lastIndexOf(`/`)+1);return`https://registry.npmjs.org/${n}/-/${C}-${S}.tgz`}function detectType(t){let n=t.toLowerCase();return n.endsWith(`pnpm-lock.yaml`)?`pnpm`:n.endsWith(`yarn.lock`)?`yarn`:n.endsWith(`package-lock.json`)?`npm`:`gjsify`}function defaultLockfile(t){for(let n of[`gjsify-lock.json`,`package-lock.json`,`yarn.lock`,`pnpm-lock.yaml`])if(existsSync(xn(t,n)))return n;return`gjsify-lock.json`}function focusedTarballs(t,n){let S=discoverWorkspaces(wn(t),{includeRoot:!0}),C=planFocus(S,n,`gjsify flatpak sources`),N=readLockfileNodes(t);if(!N)throw Error(`gjsify flatpak sources: ${t} is not a readable gjsify-lock.json.`);let F=reachableInstallPaths(N,C.specs.map(parseSpecName)),I=new Set(S.map(t=>t.name));return N.filter(t=>F.has(t.installPath)&&!I.has(t.name)).flatMap(t=>t.tarballUrl&&t.integrity?[{url:t.tarballUrl,integrity:t.integrity}]:[])}function parseLockfile(t,n){let S=readFileSync(t,`utf-8`);if(n===`yarn`)return parseYarnClassic(S);if(n===`pnpm`)return parsePnpm(S);let C;try{C=JSON.parse(S)}catch(n){throw Error(`gjsify flatpak sources: ${t} is not valid JSON: ${n.message}`)}return parseNpmLike(C)}function buildModuleSnippet(t,n){return[``,`# Add the generated sources to your app module and point XDG_CACHE_HOME`,`# at the vendored cache before running gjsify offline. Example module:`,`#`,`# {`,`# "name": "my-app",`,`# "buildsystem": "simple",`,`# "build-commands": [`,`# "export XDG_CACHE_HOME=\\"$(pwd)/${n}\\"",`,`# "gjsify install --immutable",`,`# "gjsify build src/main.ts --app gjs --outfile /app/bin/my-app"`,`# ],`,`# "sources": [`,`# { "type": "dir", "path": "." },`,`# "${t}"`,`# ]`,`# }`,``].join(`
|
|
1056
|
-
`)}var
|
|
1056
|
+
`)}var cz,lz,uz=__esmMin(()=>{_e(),Md(),jn(),ot(),OP(),sz(),xL(),zR(),cz=new Set([`sha256`,`sha512`]),lz={command:`sources`,description:"Generate an offline flatpak-builder `sources` array from any lockfile (gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml) for a no-network Flathub build.",builder:t=>t.option(`lockfile`,{description:`Path to the lockfile. Default: the first of gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml found in cwd.`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile format. Default: detected from the filename.`,choices:[`gjsify`,`npm`,`yarn`,`pnpm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:RR,normalize:!0}).option(`cache-root`,{description:`Relative dir the tarballs download into; point XDG_CACHE_HOME here in the build. Tarballs land at <cache-root>/gjsify/tarballs/v1/<algo>/<shard>/<hex>.tgz.`,type:`string`,default:`flatpak-gjsify-cache`}).option(`focus`,{description:"Only the tarballs the named workspaces (package names), the workspaces they depend on, and their external dependencies need, as `gjsify install --focus` installs them. gjsify-lock.json only.",type:`string`,array:!0}).option(`print-module`,{description:`Also print a ready-to-paste flatpak manifest module snippet to stderr`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=vn(n,t.lockfile??defaultLockfile(n));if(!existsSync(S))throw Error(`gjsify flatpak sources: lockfile ${S} not found. Run \`gjsify install\` (or npm/yarn/pnpm) first, or pass --lockfile.`);let C=t.type??detectType(S),N=t.focus;if(N&&N.length>0&&C!==`gjsify`)throw Error(`gjsify flatpak sources: --focus reads the per-package edges of gjsify-lock.json; ${C} lockfiles are not supported with it.`);let F=N&&N.length>0?focusedTarballs(S,N):parseLockfile(S,C),I=t.cacheRoot??`flatpak-gjsify-cache`,H=new Map,W=0,q=0;for(let{url:t,integrity:n}of F){let S=parseSri(n);if(!S){W++;continue}if(!cz.has(S.algorithm)){q++;continue}let C=`${S.algorithm}:${S.hex}`;if(H.has(C))continue;let N={type:`file`,url:t,dest:`${I}/gjsify/tarballs/v1/${S.algorithm}/${S.hex.slice(0,2)}`,"dest-filename":`${S.hex}.tgz`};S.algorithm===`sha512`?N.sha512=S.hex:N.sha256=S.hex,H.set(C,N)}let Y=[...H.values()].sort((t,n)=>t.url<n.url?-1:+(t.url>n.url)),X=vn(n,t.out??`gjsify-sources.json`);mkdirSync(wn(X),{recursive:!0}),writeFileSync(X,JSON.stringify(Y,null,2)+`
|
|
1057
1057
|
`),ge.log(`[gjsify flatpak sources] wrote ${X} — ${Y.length} tarball source(s) from ${C} lockfile (${F.length} locked entr${F.length===1?`y`:`ies`})`+(W?`, ${W} without a usable integrity skipped`:``)+(q?`, ${q} non-sha256/512 skipped`:``)),t.printModule&&ge.error(buildModuleSnippet(t.out??`gjsify-sources.json`,I))}}});function renderWorkflow(t){let n=`[${t.branches.map(t=>JSON.stringify(t)).join(`, `)}]`;return`name: Flatpak
|
|
1058
1058
|
|
|
1059
1059
|
on:
|
|
@@ -1082,20 +1082,20 @@ jobs:
|
|
|
1082
1082
|
manifest-path: ${t.manifest}
|
|
1083
1083
|
bundle: ${t.bundle}
|
|
1084
1084
|
cache-key: ${t.cacheKey}
|
|
1085
|
-
`}var uz,dz=__esmMin(()=>{_e(),Md(),jn(),JF(),RR(),VR(),WR(),uz={command:`ci`,description:`Scaffold .github/workflows/flatpak.yml using the flathub-infra container + flatpak-builder@v6 action.`,builder:t=>t.option(`manifest`,{description:`Manifest path the workflow points at (default: <app-id>.json)`,type:`string`,normalize:!0}).option(`bundle`,{description:`Bundle filename produced by the action (default: <app-id>.flatpak)`,type:`string`,normalize:!0}).option(`runtime-image`,{description:"Container image override. Default derived from gjsify.flatpak.runtime + runtimeVersion (e.g. `ghcr.io/flathub-infra/flatpak-github-actions:gnome-50`).",type:`string`}).option(`branches`,{description:`Branches the workflow runs on push for (default: main)`,type:`string`,array:!0}).option(`out`,{description:`Output path`,type:`string`,default:`.github/workflows/flatpak.yml`,normalize:!0}).option(`cache-key`,{description:"Override the action `cache-key` (default: `flatpak-builder-${{ github.sha }}`)",type:`string`}).option(`force`,{description:`Overwrite an existing workflow file`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print resolved fields`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await new Config().forCommand().catch(()=>({})),C=S.flatpak??{},N=readPackageJson(n),F=C.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak ci: no app id available. Set gjsify.flatpak.appId in package.json or rename the package to a reverse-DNS id.`);let I=t.manifest??`${F}.json`,H=t.bundle??`${F}.flatpak`,W=pickFlatpakBuildKeys(S.ship?.flatpak,C).values,{runtime:q,runtimeVersion:Y}=resolveRuntime(W,{}),X=t.runtimeImage??C.ciContainer??defaultCiContainer(q,Y),Z=t.branches??C.ciBranches??[`main`],te=t.cacheKey??"flatpak-builder-${{ github.sha }}",ne=vn(n,t.out??`.github/workflows/flatpak.yml`);if(existsSync(ne)&&!t.force){if(readFileSync(ne,`utf-8`)===renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te})){ge.log(`[gjsify flatpak ci] ${ne} already up to date`);return}throw Error(`gjsify flatpak ci: ${ne} exists with different content. Pass --force to overwrite.`)}let re=renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te});mkdirSync(wn(ne),{recursive:!0}),writeFileSync(ne,re,`utf-8`),t.verbose&&ge.log(`[gjsify flatpak ci] runtime-image=${X} manifest=${I} bundle=${H}`),ge.log(`[gjsify flatpak ci] wrote ${ne}`)}}});function resolveAppId(t,n,S){if(n.appId)return n.appId;try{let t=readPackageJson(S);if(looksLikeAppId(t.name))return t.name}catch{}if(t)return t.replace(/\.json$/,``)}function resolveManifestPath(t,n,S){if(t)return vn(S,t);if(n)return vn(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return vn(S,C[0]);throw Error(`gjsify flatpak check: no manifest path given and could not auto-detect. Pass the manifest as a positional argument.`)}async function runLinter(t,n,S){let C;try{C=await spawnToCompletion(t,n,{completion:`return`,stdio:S?`inherit`:`capture`})}catch(n){let S=n;return S.code===`ENOENT`?ge.error(`[gjsify flatpak check] ${t} not found in PATH.\nInstall via:\n flatpak install -y flathub org.flatpak.Builder\n alias ${t}="flatpak run --command=${t} org.flatpak.Builder"`):ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),!1}let N=C.code===0;return ge.log(`[gjsify flatpak check] ${N?`OK`:`FAIL`}: ${t} ${n.join(` `)}`),!N&&!S&&(C.stdout?.trim()&&ge.log(C.stdout.trimEnd()),C.stderr?.trim()&&ge.error(C.stderr.trimEnd())),N}var fz,pz=__esmMin(()=>{_e(),Md(),jn(),j_(),RR(),JF(),fz={command:`check [manifest]`,description:`Run Flathub pre-submission linters: appstreamcli validate + flatpak-builder-lint.`,builder:t=>t.positional(`manifest`,{description:"Path to the Flatpak manifest. Auto-detects `<app-id>.json` if omitted.",type:`string`,normalize:!0}).option(`repo`,{description:"Built ostree-repo path. If given, also runs `flatpak-builder-lint repo`.",type:`string`,normalize:!0}).option(`metainfo`,{description:"MetaInfo XML path. Default: `data/<app-id>.metainfo.xml.in`.",type:`string`,normalize:!0}).option(`appstream`,{description:"Run `appstreamcli validate --strict` (default: true).",type:`boolean`,default:!0}).option(`builder-lint`,{description:"Run `flatpak-builder-lint manifest` (default: true).",type:`boolean`,default:!0}).option(`verbose`,{description:`Stream linter stdout/stderr verbatim.`,type:`boolean`,default:!1}),handler:async t=>{let n=(await new Config().forCommand().catch(()=>({}))).flatpak??{},S=process.cwd(),C=resolveAppId(t.manifest,n,S),N=resolveManifestPath(t.manifest,C,S),F=vn(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,[`validate`,`--strict`,F],t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.builderLint!==!1){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runLinter(`flatpak-builder-lint`,[`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runLinter(`flatpak-builder-lint`,[`repo`,vn(S,t.repo)],t.verbose??!1)||I++)}if(I>0)return ge.error(`\n[gjsify flatpak check] ${I} check(s) failed.`),process.exit(1);ge.log(`[gjsify flatpak check] all checks passed.`)}}});async function readSourceListAtTag(t,n,S,C){let N;try{let{stdout:C}=await mz(`git`,[`show`,`${n}:${S}`],{cwd:t,maxBuffer:64*1024*1024});N=C}catch(N){return await assertGitMeantAbsent(t,n,S,N),C&&ge.log(`[gjsify flatpak sync-flathub] ${S} not present at ${n} — skipping`),null}if(N.trim()===``)return C&&ge.log(`[gjsify flatpak sync-flathub] ${S} is empty at ${n} — skipping`),null;let F;try{F=JSON.parse(N)}catch(t){throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not JSON: `+(t instanceof Error?t.message:String(t)))}if(!Array.isArray(F)||F.length===0)throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not a non-empty array of flatpak sources`);return N}async function assertGitMeantAbsent(t,n,S,C){if(typeof C?.code!=`number`)throw Error(`[gjsify flatpak sync-flathub] could not run \`git show ${n}:${S}\` — `+(C instanceof Error?C.message:String(C)));if(!await mz(`git`,[`rev-parse`,`--verify`,`--quiet`,`${n}^{commit}`],{cwd:t}).then(({stdout:t})=>t.trim()).catch(()=>``))throw Error(`[gjsify flatpak sync-flathub] ${n} does not resolve in ${t}, so whether it carries ${S} is unanswered. Run \`git fetch --tags\`, pass --version <an existing tag>, or run from the app checkout.`)}async function resolveLatestTag$1(t,n){try{let{stdout:S}=await mz(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t});return n&&ge.log(`[gjsify flatpak sync-flathub] resolved latest tag → ${S.trim()}`),S.trim()||null}catch{return null}}async function resolveCommitForTag(t,n,S){try{let{stdout:C}=await mz(`git`,[`rev-list`,`-n`,`1`,n],{cwd:t}),N=C.trim();if(!N)throw Error(`empty rev-list output`);return S&&ge.log(`[gjsify flatpak sync-flathub] resolved ${n} → ${N}`),N}catch(t){throw Error(`[gjsify flatpak sync-flathub] tag ${n} not found locally. Run \`git fetch --tags\` or pass --commit <sha>.\n underlying error: ${t instanceof Error?t.message:String(t)}`)}}function normaliseBranchSegment(t){return t.replace(/^v/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}function flathubCacheRoot(){return xn(process.env.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(xn(t,`.git`))){S&&ge.log(`[gjsify flatpak sync-flathub] reusing clone at ${t}`),await gitInRepo(t,[`fetch`,`origin`],S);let n=await detectDefaultBranch(t,S);await gitInRepo(t,[`checkout`,n],S),await gitInRepo(t,[`reset`,`--hard`,`origin/${n}`],S);return}mkdirSync(vn(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await mz(`git`,[`clone`,C,t])}catch(t){throw t?.code===`ENOENT`?Error("[gjsify flatpak sync-flathub] `git` not found. Install git from your distro (Fedora: `dnf install git`, Debian: `apt install git`)."):t}}async function detectDefaultBranch(t,n){try{let{stdout:S}=await mz(`git`,[`remote`,`show`,`origin`],{cwd:t}),C=S.match(/HEAD branch: (\S+)/);if(C&&C[1]&&C[1]!==`(unknown)`)return n&&ge.log(`[gjsify flatpak sync-flathub] default branch → ${C[1]}`),C[1]}catch{}return`master`}async function gitInRepo(t,n,S){S&&ge.log(`[gjsify flatpak sync-flathub] git ${n.join(` `)} (in ${t})`);let C=await spawnToCompletion(`git`,n,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `git` not found. Install it from your distro.")});if(C.code!==0)throw Error(`git ${n[0]} exited ${describeExit(C)}`)}async function ghCreate(t,n,S,C,N,F){let I=[`pr`,`create`,`--repo`,n,`--head`,S,`--title`,`Update to ${C}`,`--body`,N];F&&ge.log(`[gjsify flatpak sync-flathub] gh ${I.join(` `)} (in ${t})`);let H=await spawnToCompletion(`gh`,I,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `gh` (GitHub CLI) not found. Install via `dnf install gh` (Fedora), `apt install gh` (Debian/Ubuntu), or `flatpak install -y flathub com.github.cli`.")});if(H.code!==0)throw Error(`gh pr create exited ${describeExit(H)}`)}function editManifest(t,n){let S=JSON.parse(t),C=S.modules??[];if(C.length===0)throw Error(`[gjsify flatpak sync-flathub] manifest has no modules`);let N=C[0].sources??[];if(N.length===0)throw Error(`[gjsify flatpak sync-flathub] modules[0] has no sources`);let isObject=t=>typeof t==`object`,F=n.sourceIndex??N.findIndex(t=>isObject(t)&&t.type===`git`);if(F<0||F>=N.length)throw Error(`[gjsify flatpak sync-flathub] no git source found in modules[0].sources (use --source-index <n>)`);let I=N[F];if(!isObject(I)||I.type!==`git`){let t=isObject(I)?`type is "${I.type}"`:`is the file reference "${I}"`;throw Error(`[gjsify flatpak sync-flathub] modules[0].sources[${F}] ${t}, expected a git source`)}let H=I;H.tag=n.tag,H.commit=n.commit,H[`x-checker-data`]||={type:`git`,"tag-pattern":`^v(\\d+\\.\\d+\\.\\d+)$`,"version-scheme":`semantic`},n.sourcesFile&&!namesFile(N,n.sourcesFile)&&N.push(n.sourcesFile);let W=detectIndent$1(t);return JSON.stringify(S,null,W)+(t.endsWith(`
|
|
1085
|
+
`}var dz,fz=__esmMin(()=>{_e(),Md(),jn(),YF(),zR(),HR(),GR(),dz={command:`ci`,description:`Scaffold .github/workflows/flatpak.yml using the flathub-infra container + flatpak-builder@v6 action.`,builder:t=>t.option(`manifest`,{description:`Manifest path the workflow points at (default: <app-id>.json)`,type:`string`,normalize:!0}).option(`bundle`,{description:`Bundle filename produced by the action (default: <app-id>.flatpak)`,type:`string`,normalize:!0}).option(`runtime-image`,{description:"Container image override. Default derived from gjsify.flatpak.runtime + runtimeVersion (e.g. `ghcr.io/flathub-infra/flatpak-github-actions:gnome-50`).",type:`string`}).option(`branches`,{description:`Branches the workflow runs on push for (default: main)`,type:`string`,array:!0}).option(`out`,{description:`Output path`,type:`string`,default:`.github/workflows/flatpak.yml`,normalize:!0}).option(`cache-key`,{description:"Override the action `cache-key` (default: `flatpak-builder-${{ github.sha }}`)",type:`string`}).option(`force`,{description:`Overwrite an existing workflow file`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print resolved fields`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await new Config().forCommand().catch(()=>({})),C=S.flatpak??{},N=readPackageJson(n),F=C.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak ci: no app id available. Set gjsify.flatpak.appId in package.json or rename the package to a reverse-DNS id.`);let I=t.manifest??`${F}.json`,H=t.bundle??`${F}.flatpak`,W=pickFlatpakBuildKeys(S.ship?.flatpak,C).values,{runtime:q,runtimeVersion:Y}=resolveRuntime(W,{}),X=t.runtimeImage??C.ciContainer??defaultCiContainer(q,Y),Z=t.branches??C.ciBranches??[`main`],te=t.cacheKey??"flatpak-builder-${{ github.sha }}",ne=vn(n,t.out??`.github/workflows/flatpak.yml`);if(existsSync(ne)&&!t.force){if(readFileSync(ne,`utf-8`)===renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te})){ge.log(`[gjsify flatpak ci] ${ne} already up to date`);return}throw Error(`gjsify flatpak ci: ${ne} exists with different content. Pass --force to overwrite.`)}let re=renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te});mkdirSync(wn(ne),{recursive:!0}),writeFileSync(ne,re,`utf-8`),t.verbose&&ge.log(`[gjsify flatpak ci] runtime-image=${X} manifest=${I} bundle=${H}`),ge.log(`[gjsify flatpak ci] wrote ${ne}`)}}});function resolveAppId(t,n,S){if(n.appId)return n.appId;try{let t=readPackageJson(S);if(looksLikeAppId(t.name))return t.name}catch{}if(t)return t.replace(/\.json$/,``)}function resolveManifestPath(t,n,S){if(t)return vn(S,t);if(n)return vn(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return vn(S,C[0]);throw Error(`gjsify flatpak check: no manifest path given and could not auto-detect. Pass the manifest as a positional argument.`)}async function runLinter(t,n,S){let C;try{C=await spawnToCompletion(t,n,{completion:`return`,stdio:S?`inherit`:`capture`})}catch(n){let S=n;return S.code===`ENOENT`?ge.error(`[gjsify flatpak check] ${t} not found in PATH.\nInstall via:\n flatpak install -y flathub org.flatpak.Builder\n alias ${t}="flatpak run --command=${t} org.flatpak.Builder"`):ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),!1}let N=C.code===0;return ge.log(`[gjsify flatpak check] ${N?`OK`:`FAIL`}: ${t} ${n.join(` `)}`),!N&&!S&&(C.stdout?.trim()&&ge.log(C.stdout.trimEnd()),C.stderr?.trim()&&ge.error(C.stderr.trimEnd())),N}var pz,mz=__esmMin(()=>{_e(),Md(),jn(),j_(),zR(),YF(),pz={command:`check [manifest]`,description:`Run Flathub pre-submission linters: appstreamcli validate + flatpak-builder-lint.`,builder:t=>t.positional(`manifest`,{description:"Path to the Flatpak manifest. Auto-detects `<app-id>.json` if omitted.",type:`string`,normalize:!0}).option(`repo`,{description:"Built ostree-repo path. If given, also runs `flatpak-builder-lint repo`.",type:`string`,normalize:!0}).option(`metainfo`,{description:"MetaInfo XML path. Default: `data/<app-id>.metainfo.xml.in`.",type:`string`,normalize:!0}).option(`appstream`,{description:"Run `appstreamcli validate --strict` (default: true).",type:`boolean`,default:!0}).option(`builder-lint`,{description:"Run `flatpak-builder-lint manifest` (default: true).",type:`boolean`,default:!0}).option(`verbose`,{description:`Stream linter stdout/stderr verbatim.`,type:`boolean`,default:!1}),handler:async t=>{let n=(await new Config().forCommand().catch(()=>({}))).flatpak??{},S=process.cwd(),C=resolveAppId(t.manifest,n,S),N=resolveManifestPath(t.manifest,C,S),F=vn(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,[`validate`,`--strict`,F],t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.builderLint!==!1){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runLinter(`flatpak-builder-lint`,[`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runLinter(`flatpak-builder-lint`,[`repo`,vn(S,t.repo)],t.verbose??!1)||I++)}if(I>0)return ge.error(`\n[gjsify flatpak check] ${I} check(s) failed.`),process.exit(1);ge.log(`[gjsify flatpak check] all checks passed.`)}}});async function readSourceListAtTag(t,n,S,C){let N;try{let{stdout:C}=await hz(`git`,[`show`,`${n}:${S}`],{cwd:t,maxBuffer:64*1024*1024});N=C}catch(N){return await assertGitMeantAbsent(t,n,S,N),C&&ge.log(`[gjsify flatpak sync-flathub] ${S} not present at ${n} — skipping`),null}if(N.trim()===``)return C&&ge.log(`[gjsify flatpak sync-flathub] ${S} is empty at ${n} — skipping`),null;let F;try{F=JSON.parse(N)}catch(t){throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not JSON: `+(t instanceof Error?t.message:String(t)))}if(!Array.isArray(F)||F.length===0)throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not a non-empty array of flatpak sources`);return N}async function assertGitMeantAbsent(t,n,S,C){if(typeof C?.code!=`number`)throw Error(`[gjsify flatpak sync-flathub] could not run \`git show ${n}:${S}\` — `+(C instanceof Error?C.message:String(C)));if(!await hz(`git`,[`rev-parse`,`--verify`,`--quiet`,`${n}^{commit}`],{cwd:t}).then(({stdout:t})=>t.trim()).catch(()=>``))throw Error(`[gjsify flatpak sync-flathub] ${n} does not resolve in ${t}, so whether it carries ${S} is unanswered. Run \`git fetch --tags\`, pass --version <an existing tag>, or run from the app checkout.`)}async function resolveLatestTag$1(t,n){try{let{stdout:S}=await hz(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t});return n&&ge.log(`[gjsify flatpak sync-flathub] resolved latest tag → ${S.trim()}`),S.trim()||null}catch{return null}}async function resolveCommitForTag(t,n,S){try{let{stdout:C}=await hz(`git`,[`rev-list`,`-n`,`1`,n],{cwd:t}),N=C.trim();if(!N)throw Error(`empty rev-list output`);return S&&ge.log(`[gjsify flatpak sync-flathub] resolved ${n} → ${N}`),N}catch(t){throw Error(`[gjsify flatpak sync-flathub] tag ${n} not found locally. Run \`git fetch --tags\` or pass --commit <sha>.\n underlying error: ${t instanceof Error?t.message:String(t)}`)}}function normaliseBranchSegment(t){return t.replace(/^v/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}function flathubCacheRoot(){return xn(process.env.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(xn(t,`.git`))){S&&ge.log(`[gjsify flatpak sync-flathub] reusing clone at ${t}`),await gitInRepo(t,[`fetch`,`origin`],S);let n=await detectDefaultBranch(t,S);await gitInRepo(t,[`checkout`,n],S),await gitInRepo(t,[`reset`,`--hard`,`origin/${n}`],S);return}mkdirSync(vn(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await hz(`git`,[`clone`,C,t])}catch(t){throw t?.code===`ENOENT`?Error("[gjsify flatpak sync-flathub] `git` not found. Install git from your distro (Fedora: `dnf install git`, Debian: `apt install git`)."):t}}async function detectDefaultBranch(t,n){try{let{stdout:S}=await hz(`git`,[`remote`,`show`,`origin`],{cwd:t}),C=S.match(/HEAD branch: (\S+)/);if(C&&C[1]&&C[1]!==`(unknown)`)return n&&ge.log(`[gjsify flatpak sync-flathub] default branch → ${C[1]}`),C[1]}catch{}return`master`}async function gitInRepo(t,n,S){S&&ge.log(`[gjsify flatpak sync-flathub] git ${n.join(` `)} (in ${t})`);let C=await spawnToCompletion(`git`,n,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `git` not found. Install it from your distro.")});if(C.code!==0)throw Error(`git ${n[0]} exited ${describeExit(C)}`)}async function ghCreate(t,n,S,C,N,F){let I=[`pr`,`create`,`--repo`,n,`--head`,S,`--title`,`Update to ${C}`,`--body`,N];F&&ge.log(`[gjsify flatpak sync-flathub] gh ${I.join(` `)} (in ${t})`);let H=await spawnToCompletion(`gh`,I,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `gh` (GitHub CLI) not found. Install via `dnf install gh` (Fedora), `apt install gh` (Debian/Ubuntu), or `flatpak install -y flathub com.github.cli`.")});if(H.code!==0)throw Error(`gh pr create exited ${describeExit(H)}`)}function editManifest(t,n){let S=JSON.parse(t),C=S.modules??[];if(C.length===0)throw Error(`[gjsify flatpak sync-flathub] manifest has no modules`);let N=C[0].sources??[];if(N.length===0)throw Error(`[gjsify flatpak sync-flathub] modules[0] has no sources`);let isObject=t=>typeof t==`object`,F=n.sourceIndex??N.findIndex(t=>isObject(t)&&t.type===`git`);if(F<0||F>=N.length)throw Error(`[gjsify flatpak sync-flathub] no git source found in modules[0].sources (use --source-index <n>)`);let I=N[F];if(!isObject(I)||I.type!==`git`){let t=isObject(I)?`type is "${I.type}"`:`is the file reference "${I}"`;throw Error(`[gjsify flatpak sync-flathub] modules[0].sources[${F}] ${t}, expected a git source`)}let H=I;H.tag=n.tag,H.commit=n.commit,H[`x-checker-data`]||={type:`git`,"tag-pattern":`^v(\\d+\\.\\d+\\.\\d+)$`,"version-scheme":`semantic`},n.sourcesFile&&!namesFile(N,n.sourcesFile)&&N.push(n.sourcesFile);let W=detectIndent$1(t);return JSON.stringify(S,null,W)+(t.endsWith(`
|
|
1086
1086
|
`)?`
|
|
1087
|
-
`:``)}function namesFile(t,n){let S=stripDotSlash(n);return t.some(t=>typeof t==`string`&&stripDotSlash(t)===S)}function stripDotSlash(t){return t.replace(/^\.\//,``)}function detectIndent$1(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}var mz,hz,gz=__esmMin(()=>{_e(),Md(),jn(),Dg(),w_(),j_(),yu(),JF(),RR(),mz=promisify(execFile),hz={command:`sync-flathub`,description:`Update the per-app Flathub tracking-repo manifest to a new git tag + commit. Clones, edits, commits, optionally opens a PR.`,builder:t=>t.version(!1).option(`version`,{description:"Git tag to sync to. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `flathub/<appId>`.",type:`string`}).option(`commit`,{description:"Commit SHA to pin. Default: resolved via `git rev-list -n 1 <version>` in cwd.",type:`string`}).option(`branch`,{description:"Branch name in the flathub-repo. Default: `update-to-<version>`.",type:`string`}).option(`sources-file`,{description:`Generated offline tarball list to carry into the Flathub repo and name in the manifest. Default: \`${LR}\`. Skipped when the tag does not carry it.`,type:`string`,default:LR}).option(`source-index`,{description:"Index into modules[0].sources[] to update (when manifest has multiple sources). Default: first `type: git` source.",type:`number`}).option(`pr`,{description:"After commit + push, open a PR via `gh pr create`. Pass `--no-pr` to skip and stop after push.",type:`boolean`,default:!0}).option(`dry-run`,{description:`Show what would be edited; touch no files, run no git commands.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every git / gh invocation before running.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak sync-flathub] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag$1(n,t.verbose);if(!F)throw Error(`[gjsify flatpak sync-flathub] no version resolved — pass --version vX.Y.Z or create a git tag locally.`);let I=t.commit??await resolveCommitForTag(n,F,t.verbose),H=t.branch??`update-to-${normaliseBranchSegment(F)}`;if(ge.log(`[gjsify flatpak sync-flathub] appId=${C}`),ge.log(`[gjsify flatpak sync-flathub] flathubRepo=${N}`),ge.log(`[gjsify flatpak sync-flathub] version=${F}`),ge.log(`[gjsify flatpak sync-flathub] commit=${I}`),ge.log(`[gjsify flatpak sync-flathub] branch=${H}`),t.dryRun){ge.log(`[gjsify flatpak sync-flathub] --dry-run set; not cloning / writing / pushing.`);return}let W=flathubCacheRoot(),q=xn(W,N.replace(`/`,`__`));mkdirSync(W,{recursive:!0}),await ensureClone(q,N,t.verbose);let Y=xn(q,`${C}.json`);if(!existsSync(Y))throw Error(`[gjsify flatpak sync-flathub] Flathub manifest not found at ${Y} — wrong appId / wrong flathub-repo?`);let X=t.sourcesFile??`gjsify-sources.json`,Z=await readSourceListAtTag(n,F,X,t.verbose),te=!1;if(Z!==null){let t=xn(q,X);te=!existsSync(t)||readFileSync(t,`utf-8`)!==Z,te&&(writeFileSync(t,Z,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] ${X} copied from ${F}`))}let ne=readFileSync(Y,`utf-8`),re=editManifest(ne,{tag:F,commit:I,sourceIndex:t.sourceIndex,sourcesFile:Z===null?void 0:X});if(re===ne&&!te){ge.log(`[gjsify flatpak sync-flathub] manifest already at ${F} — nothing to do.`);return}if(writeFileSync(Y,re,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] manifest patched at ${Y}`),await gitInRepo(q,[`checkout`,`-B`,H],t.verbose),await gitInRepo(q,[`add`,`.`],t.verbose),await gitInRepo(q,[`commit`,`-m`,`Update to ${F}`],t.verbose),t.pr===!1){ge.log(`[gjsify flatpak sync-flathub] --no-pr set; branch ${H} committed locally in ${q}.`);return}await gitInRepo(q,[`push`,`-u`,`origin`,H,`--force-with-lease`],t.verbose),await ghCreate(q,N,H,F,`Auto-generated by \`gjsify flatpak sync-flathub\`.\n\n- Version: \`${F}\`\n- Commit: \`${I}\`\n`,t.verbose)}},__name$1(resolveLatestTag$1,`resolveLatestTag`),__name$1(detectIndent$1,`detectIndent`)});async function loadFlathubSource(t,n){let S;if(t.against){if(!existsSync(t.against))throw Error(`[gjsify flatpak diff] --against path ${t.against} does not exist`);S=readFileSync(t.against,`utf-8`)}else S=await fetchFlathubManifest(t.flathubRepo,t.appId,t.verbose);let C;try{C=JSON.parse(S)}catch(t){throw Error(`[gjsify flatpak diff] failed to parse Flathub manifest as JSON: ${t.message}`)}let N=(C.modules??[])[0]?.sources??[];if(N.length===0)return null;let F=n??N.findIndex(t=>isSourceObject(t)&&t.type===`git`);if(F<0||F>=N.length)return null;let I=N[F];return isSourceObject(I)?I:null}function isSourceObject(t){return typeof t==`object`&&!!t}async function fetchFlathubManifest(t,n,S){for(let C of[`master`,`main`]){let N=`https://raw.githubusercontent.com/${t}/${C}/${n}.json`;S&&ge.log(`[gjsify flatpak diff] fetch ${N}`);try{let t=await fetch(N);if(t.ok)return await t.text();S&&ge.log(`[gjsify flatpak diff] ${C} → HTTP ${t.status}`)}catch(t){S&&ge.log(`[gjsify flatpak diff] ${C} fetch error: ${t.message}`)}}throw Error(`[gjsify flatpak diff] could not fetch flathub manifest from ${t} on master or main`)}async function resolveLatestTag(t,n){try{let{stdout:S}=await _z(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t}),C=S.trim();return n&&ge.log(`[gjsify flatpak diff] local latest tag → ${C}`),C||null}catch{return null}}var _z,vz,yz=__esmMin(()=>{_e(),Md(),w_(),yu(),JF(),RR(),_z=promisify(execFile),vz={command:`diff`,description:`Compare the per-app Flathub tracking-repo manifest against the local git state and report version / commit drift.`,builder:t=>t.version(!1).option(`version`,{description:"Local version to compare against. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `gjsify.flatpak.flathubRepo` or `flathub/<appId>`.",type:`string`}).option(`against`,{description:`Read the Flathub manifest from a local file instead of fetching it. Useful in CI or offline.`,type:`string`}).option(`detail`,{description:`Also print the full Flathub manifest source entry alongside the resolved local version.`,type:`boolean`,default:!1}).option(`source-index`,{description:`Index into modules[0].sources[] to inspect (when the manifest has multiple sources).`,type:`number`}).option(`verbose`,{description:`Echo fetch URL + resolved values.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak diff] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag(n,t.verbose),I=await loadFlathubSource({appId:C,flathubRepo:N,against:t.against,verbose:t.verbose},t.sourceIndex),H=I?.tag,W=I?.commit;if(ge.log(`[gjsify flatpak diff] appId=${C}`),ge.log(`[gjsify flatpak diff] flathubRepo=${N}`),ge.log(`[gjsify flatpak diff] flathub: tag=${H??`(missing)`} commit=${W??`(missing)`}`),ge.log(`[gjsify flatpak diff] local: tag=${F??`(none)`}`),t.detail&&I&&(ge.log(`[gjsify flatpak diff] flathub manifest source:`),ge.log(JSON.stringify(I,null,2))),!F){ge.warn("[gjsify flatpak diff] no local git tag found — cut a release (`git tag vX.Y.Z`) or pass --version vX.Y.Z to compare against an explicit value.");return}if(!H)return ge.warn("[gjsify flatpak diff] flathub manifest has no `tag` field on the inspected source."),process.exit(1);if(H===F){ge.log(`✅ in sync (${F})`);return}ge.log(`❌ drift detected — flathub=${H} vs local=${F}`),ge.log(` run \`gjsify flatpak sync-flathub --version ${F}\` to update the Flathub manifest.`),process.exit(1)}}});function resolveCliEntry(){return vn(vn(wn(fileURLToPath(import.meta.url)),`..`,`..`),`index.js`)}async function runNode(t,n){let S=await spawnToCompletion(`node`,t,{completion:`return`,cwd:n});if(S.code!==0)throw Error(`sub-command exited with ${describeExit(S)}: node ${t.join(` `)}`)}var bz,xz,Sz=__esmMin(()=>{_e(),w_(),j_(),yu(),Hn(),jn(),bz=promisify(execFile),xz={command:`release <version>`,description:"Cut a release end-to-end: regenerate Flathub assets, run linters, create + push the git tag, then open the Flathub PR. Each step delegates to the equivalent `gjsify flatpak <sub>` command.",builder:t=>t.version(!1).positional(`version`,{description:"Release tag, e.g. `v0.6.6`.",type:`string`,demandOption:!0}).option(`skip-init`,{description:"Skip the `flatpak init --force` regen step.",type:`boolean`,default:!1}).option(`skip-check`,{description:"Skip the `flatpak check` linter step.",type:`boolean`,default:!1}).option(`skip-tag`,{description:"Skip the `git tag` + `git push --tags` step (use when the tag was already created out-of-band).",type:`boolean`,default:!1}).option(`push-tag`,{description:`Push the created tag after creating it. Default: true.`,type:`boolean`,default:!0}).option(`flathub-repo`,{description:`Flathub tracking-repo override forwarded to sync-flathub.`,type:`string`}).option(`dry-run`,{description:`Print each step that would run without executing any of them.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every sub-command invocation.`,type:`boolean`,default:!1}),handler:async t=>{let n=typeof t.version==`string`?t.version.trim():``;if(!n)throw Error(`[gjsify flatpak release] missing <version> positional`);let S=resolveCliEntry(),C=process.cwd(),N=[];t.skipInit||N.push({name:`init`,args:[S,`flatpak`,`init`,`--force`]}),t.skipCheck||N.push({name:`check`,args:[S,`flatpak`,`check`]});let F=[S,`flatpak`,`sync-flathub`,`--version`,n];if(t.flathubRepo&&F.push(`--flathub-repo`,t.flathubRepo),t.verbose&&F.push(`--verbose`),ge.log(`[gjsify flatpak release] starting release of ${n}`),t.dryRun){ge.log(`[gjsify flatpak release] --dry-run set; printing plan only:`);for(let t of N)ge.log(` · ${t.name}: node ${t.args.join(` `)}`);t.skipTag||ge.log(` · tag: git tag ${n}${t.pushTag===!1?``:` && git push origin `+n}`),ge.log(` · sync: node ${F.join(` `)}`);return}for(let n of N)t.verbose&&ge.log(`[gjsify flatpak release] step ${n.name}: node ${n.args.join(` `)}`),await runNode(n.args,C),ge.log(`[gjsify flatpak release] ${n.name} ✔`);if(!t.skipTag){t.verbose&&ge.log(`[gjsify flatpak release] git tag ${n}`);try{await bz(`git`,[`tag`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag ${n} created`)}catch(t){throw Error(`[gjsify flatpak release] git tag failed (${t.message}). If the tag already exists, re-run with --skip-tag.`)}t.pushTag!==!1&&(t.verbose&&ge.log(`[gjsify flatpak release] git push origin ${n}`),await bz(`git`,[`push`,`origin`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag pushed`))}t.verbose&&ge.log(`[gjsify flatpak release] sync: node ${F.join(` `)}`),await runNode(F,C),ge.log(`[gjsify flatpak release] ✅ release ${n} complete`)}}}),Cz,wz=__esmMin(()=>{QR(),ez(),nz(),lz(),dz(),pz(),gz(),yz(),Sz(),Cz={command:`flatpak <subcommand>`,description:`Flatpak toolchain: init/build/deps/sources/ci/check/sync-flathub/diff/release subcommands for shipping GJS apps and CLIs as Flatpaks.`,builder:t=>t.command(ZR.command,ZR.description,ZR.builder,ZR.handler).command($R.command,$R.description,$R.builder,$R.handler).command(tz.command,tz.description,tz.builder,tz.handler).command(cz.command,cz.description,cz.builder,cz.handler).command(uz.command,uz.description,uz.builder,uz.handler).command(fz.command,fz.description,fz.builder,fz.handler).command(hz.command,hz.description,hz.builder,hz.handler).command(vz.command,vz.description,vz.builder,vz.handler).command(xz.command,xz.description,xz.builder,xz.handler).demandCommand(1).strict()}});function concatBytes(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}function encodeUtf8(t){return new TextEncoder().encode(t)}var Tz=__esmMin(()=>{});function createArArchive(t){let n=[encodeUtf8(Ez)];for(let S of t)n.push(buildMemberHeader(S)),n.push(S.data),S.data.byteLength%2==1&&n.push(encodeUtf8(`
|
|
1087
|
+
`:``)}function namesFile(t,n){let S=stripDotSlash(n);return t.some(t=>typeof t==`string`&&stripDotSlash(t)===S)}function stripDotSlash(t){return t.replace(/^\.\//,``)}function detectIndent$1(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}var hz,gz,_z=__esmMin(()=>{_e(),Md(),jn(),Dg(),w_(),j_(),yu(),YF(),zR(),hz=promisify(execFile),gz={command:`sync-flathub`,description:`Update the per-app Flathub tracking-repo manifest to a new git tag + commit. Clones, edits, commits, optionally opens a PR.`,builder:t=>t.version(!1).option(`version`,{description:"Git tag to sync to. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `flathub/<appId>`.",type:`string`}).option(`commit`,{description:"Commit SHA to pin. Default: resolved via `git rev-list -n 1 <version>` in cwd.",type:`string`}).option(`branch`,{description:"Branch name in the flathub-repo. Default: `update-to-<version>`.",type:`string`}).option(`sources-file`,{description:`Generated offline tarball list to carry into the Flathub repo and name in the manifest. Default: \`${RR}\`. Skipped when the tag does not carry it.`,type:`string`,default:RR}).option(`source-index`,{description:"Index into modules[0].sources[] to update (when manifest has multiple sources). Default: first `type: git` source.",type:`number`}).option(`pr`,{description:"After commit + push, open a PR via `gh pr create`. Pass `--no-pr` to skip and stop after push.",type:`boolean`,default:!0}).option(`dry-run`,{description:`Show what would be edited; touch no files, run no git commands.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every git / gh invocation before running.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak sync-flathub] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag$1(n,t.verbose);if(!F)throw Error(`[gjsify flatpak sync-flathub] no version resolved — pass --version vX.Y.Z or create a git tag locally.`);let I=t.commit??await resolveCommitForTag(n,F,t.verbose),H=t.branch??`update-to-${normaliseBranchSegment(F)}`;if(ge.log(`[gjsify flatpak sync-flathub] appId=${C}`),ge.log(`[gjsify flatpak sync-flathub] flathubRepo=${N}`),ge.log(`[gjsify flatpak sync-flathub] version=${F}`),ge.log(`[gjsify flatpak sync-flathub] commit=${I}`),ge.log(`[gjsify flatpak sync-flathub] branch=${H}`),t.dryRun){ge.log(`[gjsify flatpak sync-flathub] --dry-run set; not cloning / writing / pushing.`);return}let W=flathubCacheRoot(),q=xn(W,N.replace(`/`,`__`));mkdirSync(W,{recursive:!0}),await ensureClone(q,N,t.verbose);let Y=xn(q,`${C}.json`);if(!existsSync(Y))throw Error(`[gjsify flatpak sync-flathub] Flathub manifest not found at ${Y} — wrong appId / wrong flathub-repo?`);let X=t.sourcesFile??`gjsify-sources.json`,Z=await readSourceListAtTag(n,F,X,t.verbose),te=!1;if(Z!==null){let t=xn(q,X);te=!existsSync(t)||readFileSync(t,`utf-8`)!==Z,te&&(writeFileSync(t,Z,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] ${X} copied from ${F}`))}let ne=readFileSync(Y,`utf-8`),re=editManifest(ne,{tag:F,commit:I,sourceIndex:t.sourceIndex,sourcesFile:Z===null?void 0:X});if(re===ne&&!te){ge.log(`[gjsify flatpak sync-flathub] manifest already at ${F} — nothing to do.`);return}if(writeFileSync(Y,re,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] manifest patched at ${Y}`),await gitInRepo(q,[`checkout`,`-B`,H],t.verbose),await gitInRepo(q,[`add`,`.`],t.verbose),await gitInRepo(q,[`commit`,`-m`,`Update to ${F}`],t.verbose),t.pr===!1){ge.log(`[gjsify flatpak sync-flathub] --no-pr set; branch ${H} committed locally in ${q}.`);return}await gitInRepo(q,[`push`,`-u`,`origin`,H,`--force-with-lease`],t.verbose),await ghCreate(q,N,H,F,`Auto-generated by \`gjsify flatpak sync-flathub\`.\n\n- Version: \`${F}\`\n- Commit: \`${I}\`\n`,t.verbose)}},__name$1(resolveLatestTag$1,`resolveLatestTag`),__name$1(detectIndent$1,`detectIndent`)});async function loadFlathubSource(t,n){let S;if(t.against){if(!existsSync(t.against))throw Error(`[gjsify flatpak diff] --against path ${t.against} does not exist`);S=readFileSync(t.against,`utf-8`)}else S=await fetchFlathubManifest(t.flathubRepo,t.appId,t.verbose);let C;try{C=JSON.parse(S)}catch(t){throw Error(`[gjsify flatpak diff] failed to parse Flathub manifest as JSON: ${t.message}`)}let N=(C.modules??[])[0]?.sources??[];if(N.length===0)return null;let F=n??N.findIndex(t=>isSourceObject(t)&&t.type===`git`);if(F<0||F>=N.length)return null;let I=N[F];return isSourceObject(I)?I:null}function isSourceObject(t){return typeof t==`object`&&!!t}async function fetchFlathubManifest(t,n,S){for(let C of[`master`,`main`]){let N=`https://raw.githubusercontent.com/${t}/${C}/${n}.json`;S&&ge.log(`[gjsify flatpak diff] fetch ${N}`);try{let t=await fetch(N);if(t.ok)return await t.text();S&&ge.log(`[gjsify flatpak diff] ${C} → HTTP ${t.status}`)}catch(t){S&&ge.log(`[gjsify flatpak diff] ${C} fetch error: ${t.message}`)}}throw Error(`[gjsify flatpak diff] could not fetch flathub manifest from ${t} on master or main`)}async function resolveLatestTag(t,n){try{let{stdout:S}=await vz(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t}),C=S.trim();return n&&ge.log(`[gjsify flatpak diff] local latest tag → ${C}`),C||null}catch{return null}}var vz,yz,bz=__esmMin(()=>{_e(),Md(),w_(),yu(),YF(),zR(),vz=promisify(execFile),yz={command:`diff`,description:`Compare the per-app Flathub tracking-repo manifest against the local git state and report version / commit drift.`,builder:t=>t.version(!1).option(`version`,{description:"Local version to compare against. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `gjsify.flatpak.flathubRepo` or `flathub/<appId>`.",type:`string`}).option(`against`,{description:`Read the Flathub manifest from a local file instead of fetching it. Useful in CI or offline.`,type:`string`}).option(`detail`,{description:`Also print the full Flathub manifest source entry alongside the resolved local version.`,type:`boolean`,default:!1}).option(`source-index`,{description:`Index into modules[0].sources[] to inspect (when the manifest has multiple sources).`,type:`number`}).option(`verbose`,{description:`Echo fetch URL + resolved values.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak diff] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag(n,t.verbose),I=await loadFlathubSource({appId:C,flathubRepo:N,against:t.against,verbose:t.verbose},t.sourceIndex),H=I?.tag,W=I?.commit;if(ge.log(`[gjsify flatpak diff] appId=${C}`),ge.log(`[gjsify flatpak diff] flathubRepo=${N}`),ge.log(`[gjsify flatpak diff] flathub: tag=${H??`(missing)`} commit=${W??`(missing)`}`),ge.log(`[gjsify flatpak diff] local: tag=${F??`(none)`}`),t.detail&&I&&(ge.log(`[gjsify flatpak diff] flathub manifest source:`),ge.log(JSON.stringify(I,null,2))),!F){ge.warn("[gjsify flatpak diff] no local git tag found — cut a release (`git tag vX.Y.Z`) or pass --version vX.Y.Z to compare against an explicit value.");return}if(!H)return ge.warn("[gjsify flatpak diff] flathub manifest has no `tag` field on the inspected source."),process.exit(1);if(H===F){ge.log(`✅ in sync (${F})`);return}ge.log(`❌ drift detected — flathub=${H} vs local=${F}`),ge.log(` run \`gjsify flatpak sync-flathub --version ${F}\` to update the Flathub manifest.`),process.exit(1)}}});function resolveCliEntry(){return vn(vn(wn(fileURLToPath(import.meta.url)),`..`,`..`),`index.js`)}async function runNode(t,n){let S=await spawnToCompletion(`node`,t,{completion:`return`,cwd:n});if(S.code!==0)throw Error(`sub-command exited with ${describeExit(S)}: node ${t.join(` `)}`)}var xz,Sz,Cz=__esmMin(()=>{_e(),w_(),j_(),yu(),Hn(),jn(),xz=promisify(execFile),Sz={command:`release <version>`,description:"Cut a release end-to-end: regenerate Flathub assets, run linters, create + push the git tag, then open the Flathub PR. Each step delegates to the equivalent `gjsify flatpak <sub>` command.",builder:t=>t.version(!1).positional(`version`,{description:"Release tag, e.g. `v0.6.6`.",type:`string`,demandOption:!0}).option(`skip-init`,{description:"Skip the `flatpak init --force` regen step.",type:`boolean`,default:!1}).option(`skip-check`,{description:"Skip the `flatpak check` linter step.",type:`boolean`,default:!1}).option(`skip-tag`,{description:"Skip the `git tag` + `git push --tags` step (use when the tag was already created out-of-band).",type:`boolean`,default:!1}).option(`push-tag`,{description:`Push the created tag after creating it. Default: true.`,type:`boolean`,default:!0}).option(`flathub-repo`,{description:`Flathub tracking-repo override forwarded to sync-flathub.`,type:`string`}).option(`dry-run`,{description:`Print each step that would run without executing any of them.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every sub-command invocation.`,type:`boolean`,default:!1}),handler:async t=>{let n=typeof t.version==`string`?t.version.trim():``;if(!n)throw Error(`[gjsify flatpak release] missing <version> positional`);let S=resolveCliEntry(),C=process.cwd(),N=[];t.skipInit||N.push({name:`init`,args:[S,`flatpak`,`init`,`--force`]}),t.skipCheck||N.push({name:`check`,args:[S,`flatpak`,`check`]});let F=[S,`flatpak`,`sync-flathub`,`--version`,n];if(t.flathubRepo&&F.push(`--flathub-repo`,t.flathubRepo),t.verbose&&F.push(`--verbose`),ge.log(`[gjsify flatpak release] starting release of ${n}`),t.dryRun){ge.log(`[gjsify flatpak release] --dry-run set; printing plan only:`);for(let t of N)ge.log(` · ${t.name}: node ${t.args.join(` `)}`);t.skipTag||ge.log(` · tag: git tag ${n}${t.pushTag===!1?``:` && git push origin `+n}`),ge.log(` · sync: node ${F.join(` `)}`);return}for(let n of N)t.verbose&&ge.log(`[gjsify flatpak release] step ${n.name}: node ${n.args.join(` `)}`),await runNode(n.args,C),ge.log(`[gjsify flatpak release] ${n.name} ✔`);if(!t.skipTag){t.verbose&&ge.log(`[gjsify flatpak release] git tag ${n}`);try{await xz(`git`,[`tag`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag ${n} created`)}catch(t){throw Error(`[gjsify flatpak release] git tag failed (${t.message}). If the tag already exists, re-run with --skip-tag.`)}t.pushTag!==!1&&(t.verbose&&ge.log(`[gjsify flatpak release] git push origin ${n}`),await xz(`git`,[`push`,`origin`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag pushed`))}t.verbose&&ge.log(`[gjsify flatpak release] sync: node ${F.join(` `)}`),await runNode(F,C),ge.log(`[gjsify flatpak release] ✅ release ${n} complete`)}}}),wz,Tz=__esmMin(()=>{$R(),tz(),rz(),uz(),fz(),mz(),_z(),bz(),Cz(),wz={command:`flatpak <subcommand>`,description:`Flatpak toolchain: init/build/deps/sources/ci/check/sync-flathub/diff/release subcommands for shipping GJS apps and CLIs as Flatpaks.`,builder:t=>t.command(QR.command,QR.description,QR.builder,QR.handler).command(ez.command,ez.description,ez.builder,ez.handler).command(nz.command,nz.description,nz.builder,nz.handler).command(lz.command,lz.description,lz.builder,lz.handler).command(dz.command,dz.description,dz.builder,dz.handler).command(pz.command,pz.description,pz.builder,pz.handler).command(gz.command,gz.description,gz.builder,gz.handler).command(yz.command,yz.description,yz.builder,yz.handler).command(Sz.command,Sz.description,Sz.builder,Sz.handler).demandCommand(1).strict()}});function concatBytes(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}function encodeUtf8(t){return new TextEncoder().encode(t)}var Ez=__esmMin(()=>{});function createArArchive(t){let n=[encodeUtf8(Dz)];for(let S of t)n.push(buildMemberHeader(S)),n.push(S.data),S.data.byteLength%2==1&&n.push(encodeUtf8(`
|
|
1088
1088
|
`));return concatBytes(n)}function buildMemberHeader(t){let n=pad(t.name,16)+pad(String(t.mtime??0),12)+pad(`0`,6)+pad(`0`,6)+pad((t.mode??33188).toString(8),8)+pad(String(t.data.byteLength),10)+`\`
|
|
1089
|
-
`;if(n.length!==
|
|
1090
|
-
`,
|
|
1089
|
+
`;if(n.length!==Oz)throw Error(`gjsify ship: internal error — ar header is ${n.length} bytes, expected ${Oz}.`);return encodeUtf8(n)}function pad(t,n){if(t.length>n)throw Error(`gjsify ship: ar header field "${t}" does not fit in ${n} bytes.`);return t.padEnd(n,` `)}var Dz,Oz,kz=__esmMin(()=>{Ez(),Dz=`!<arch>
|
|
1090
|
+
`,Oz=60});function warnAboutGjsFloor(t,n){return!Nz[t]||compareVersions(n,`1.82.3`)<=0||compareVersions(n,`1.88.1`)===0?[]:[`gjsify ship: \`Depends: gjs (>= ${n})\` is not satisfiable on Debian stable — ${Mz}. The package installs on forky/sid and on distributions with a newer GJS. Set \`gjsify.ship.minGjsVersion\` if this bundle genuinely runs on an older GJS; do NOT lower it to make apt happy, because the result is an install that succeeds and an app that does not start.`]}function warnAboutNodeFloor(t,n){return!Fz[t]||compareVersions(n,`22`)<=0?[]:[`gjsify ship: \`Depends: nodejs (>= ${n})\` is not satisfiable on any current DEB stable/LTS — ${Pz}. The package installs on forky/sid and on distributions with a newer Node. Set \`gjsify.ship.minNodeVersion\` if this bundle genuinely runs on an older Node; do NOT lower it to make apt happy, because the result is an install that succeeds and an app that dies on the first syntax or API the older interpreter does not have.`]}function compareVersions(t,n){let S=t.split(`.`).map(Number),C=n.split(`.`).map(Number);for(let t=0;t<Math.max(S.length,C.length);t++){let n=(S[t]??0)-(C[t]??0);if(n!==0)return n}return 0}function hostProvidedNamespaces(t,n=[]){let S=new Set;for(let t of n){let n=/([A-Za-z0-9]+)-([\d.]+)\.typelib$/.exec(t);n&&(S.add(`${n[1]}-${n[2]}`),S.add(n[1]))}return[...new Set(t)].sort().filter(t=>!Lz.test(t)&&!S.has(t))}function deriveDepends(t,n){let S=n.interpreter===`node`?[`${Az[t]} >= ${n.minNodeVersion??`24`}`]:[`gjs >= ${n.minGjsVersion??`1.86`}`],C=[],N=new Set(n.optionalNamespaces??[]),F=[],I=[];for(let H of hostProvidedNamespaces(n.namespaces,n.bundledTypelibs)){let W=lookupTypelib(H,n.typelibPackages);if(W===void 0){(N.has(H)?I:F).push(H);continue}N.has(H)&&!S.includes(W[t])?C.push(W[t]):S.push(W[t])}if(F.length>0)throw Error(`gjsify ship: the bundle imports ${F.map(t=>`gi://${t.split(`-`)[0]}`).join(`, `)}, and no ${t} package is known to ship ${F.length>1?`those typelibs`:`that typelib`}. An undeclared runtime dependency does not fail here — it fails on a user's machine after the download. Fill the gap in package.json:
|
|
1091
1091
|
"gjsify": { "ship": { "typelibPackages": { ${JSON.stringify(F[0])}: { "deb": "gir1.2-…", "rpm": "…" } } } }
|
|
1092
|
-
and please contribute the mapping back to \`utils/ship/depends.ts\` so the next project does not have to. (\`gjsify.ship.depends.<format>\` is for dependencies that are not typelibs at all — it appends, and deliberately does not silence this.)`);return n.hasIcons&&S.push(`hicolor-icon-theme`),n.hasSchemas&&S.push(
|
|
1092
|
+
and please contribute the mapping back to \`utils/ship/depends.ts\` so the next project does not have to. (\`gjsify.ship.depends.<format>\` is for dependencies that are not typelibs at all — it appends, and deliberately does not silence this.)`);return n.hasIcons&&S.push(`hicolor-icon-theme`),n.hasSchemas&&S.push(jz[t]),S.push(...n.extra),{requires:[...new Set(S)],recommends:[...new Set(C)].filter(t=>!S.includes(t)),unmappedOptional:I}}function lookupTypelib(t,n={}){let S={...Iz,...n},C=S[t];if(C!==void 0)return C;if(t.includes(`-`))return;let N=Object.keys(S).filter(n=>n.startsWith(`${t}-`));if(N.length===1)return S[N[0]]}function parseDepend(t){let n=/^(\S+)\s*(>=|<=|=|>|<)\s*(\S+)$/.exec(t);return n?{name:n[1],relation:n[2],version:n[3]}:{name:t.trim()}}function formatDebDepend(t){let n=parseDepend(t);if(n.relation===void 0)return n.name;let S=n.relation===`>`?`>>`:n.relation===`<`?`<<`:n.relation;return`${n.name} (${S} ${n.version})`}var Az,jz,Mz,Nz,Pz,Fz,Iz,Lz,Rz=__esmMin(()=>{Az={deb:`nodejs`,rpm:`nodejs(engine)`},jz={deb:`libglib2.0-bin`,rpm:`glib2`},Mz=`trixie ships 1.82.3 and forky 1.88.1; 1.84 and 1.86 were skipped`,Nz={deb:!0,rpm:!1},Pz=`trixie ships 20, forky 24; Ubuntu 24.04 LTS ships 18 and 26.04 LTS 22`,Fz={deb:!0,rpm:!1},Iz={"GLib-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GObject-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"Gio-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GioUnix-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GModule-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"Gtk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Gdk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Gsk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Adw-1":{deb:`gir1.2-adw-1`,rpm:`libadwaita`},"GdkPixbuf-2.0":{deb:`gir1.2-gdkpixbuf-2.0`,rpm:`gdk-pixbuf2`},"Pango-1.0":{deb:`gir1.2-pango-1.0`,rpm:`pango`},"PangoCairo-1.0":{deb:`gir1.2-pango-1.0`,rpm:`pango`},"Graphene-1.0":{deb:`gir1.2-graphene-1.0`,rpm:`graphene`},"cairo-1.0":{deb:`gir1.2-freedesktop`,rpm:`gobject-introspection`},"GtkSource-5":{deb:`gir1.2-gtksource-5`,rpm:`gtksourceview5`},"WebKit-6.0":{deb:`gir1.2-webkit-6.0`,rpm:`webkitgtk6.0`},"Soup-3.0":{deb:`gir1.2-soup-3.0`,rpm:`libsoup3`},"Json-1.0":{deb:`gir1.2-json-1.0`,rpm:`json-glib`},"Gst-1.0":{deb:`gir1.2-gstreamer-1.0`,rpm:`gstreamer1`},"Secret-1":{deb:`gir1.2-secret-1`,rpm:`libsecret`},"Notify-0.7":{deb:`gir1.2-notify-0.7`,rpm:`libnotify`},"Vte-3.91":{deb:`gir1.2-vte-3.91`,rpm:`vte291-gtk4`},"Manette-0.2":{deb:`gir1.2-manette-0.2`,rpm:`libmanette`},"Gda-6.0":{deb:`gir1.2-gda-6.0`,rpm:`libgda`}},Lz=/^Gjsify[A-Z]/});async function gzipDeterministic(t,n){let S=await gzip(t,n===void 0?void 0:{level:n});if(S.byteLength<10||S[0]!==31||S[1]!==139)throw Error(`gjsify ship: internal error — gzip did not produce a gzip stream.`);return S[4]=0,S[5]=0,S[6]=0,S[7]=0,S[9]=3,S}var zz=__esmMin(()=>{RI()});function isUnder(t,n){return t.startsWith(`${n}/`)}var Bz,Vz=__esmMin(()=>{Bz={applications:`share/applications`,icons:`share/icons/hicolor`,schemas:`share/glib-2.0/schemas`,mime:`share/mime/packages`,metainfo:`share/metainfo`,locale:`share/locale`,fonts:`share/fonts`}});function cacheRefreshCommands(t,n){let S=[];return t.hasDesktopEntry&&S.push({probe:`update-desktop-database`,run:`update-desktop-database -q ${n}/${Bz.applications}`}),t.hasIcons&&S.push({probe:`gtk-update-icon-cache`,run:`gtk-update-icon-cache -q -t -f ${n}/${Bz.icons}`}),t.hasMimeTypes&&S.push({probe:`update-mime-database`,run:`update-mime-database ${n}/share/mime`}),t.hasSchemas&&S.push({probe:`glib-compile-schemas`,run:`glib-compile-schemas ${n}/${Bz.schemas}`}),S.map(({probe:t,run:n})=>`if command -v ${t} >/dev/null 2>&1; then ${n} || true; fi`)}function renderDebScripts(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=S.map(t=>` ${t}`).join(`
|
|
1093
1093
|
`);return{postinst:[`#!/bin/sh`,`set -e`,`if [ "$1" = "configure" ]; then`,C,`fi`,``].join(`
|
|
1094
1094
|
`),postrm:[`#!/bin/sh`,`set -e`,`if [ "$1" = "remove" ]; then`,C,`fi`,``].join(`
|
|
1095
1095
|
`)}}function renderRpmScriptlets(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=`${S.join(`
|
|
1096
|
-
`)}\n`;return{post:C,postun:C}}var
|
|
1096
|
+
`)}\n`;return{post:C,postun:C}}var Hz=__esmMin(()=>{Vz()});function isSymbolicIcon(t){return $(t).toLowerCase()===`.svg`?/(?:^|[\\/])symbolic[\\/]/.test(t)?!0:Tn(t,$(t)).endsWith(`-symbolic`):!1}function iconThemeDir(t){if(isSymbolicIcon(t))return`symbolic`;if($(t).toLowerCase()===`.svg`)return`scalable`;let n=/(?:^|[\\/])(\d{1,4})x\1(?:[\\/]|$)/.exec(t);if(n)return`${n[1]}x${n[1]}`;let S=Tn(t,$(t)).split(/[-_.]/);for(let t=S.length-1;t>=0;t--){let n=S[t];if(n!==void 0&&/^\d{1,4}$/.test(n))return`${n}x${n}`}throw Error(`gjsify ship: cannot tell what size ${t} is. Put it in a \`<size>x<size>/\` directory, end its name with the size (\`icon-128.png\`), or ship an SVG.`)}function readPngSize(t,n){if(t.length<33||Wz.some((n,S)=>t[S]!==n))throw Error(`gjsify ship: ${n} is not a PNG — it does not start with the PNG signature.`);let S=new DataView(t.buffer,t.byteOffset,t.byteLength);if(S.getUint32(8)!==13||Buffer.from(t.subarray(12,16)).toString(`latin1`)!==`IHDR`)throw Error(`gjsify ship: ${n} is not a PNG this command can read — its first chunk is not IHDR.`);let C=t.length-Gz.length;if(Gz.some((n,S)=>t[C+S]!==n))throw Error(`gjsify ship: ${n} is truncated — it does not end with an IEND chunk, so it would embed as a picture that decodes to nothing.`);return{width:S.getUint32(16),height:S.getUint32(20)}}function rasterizerEnv(t={}){return{...t.env??process.env,...buildNativeEnv([],t)}}async function rasterizeSvg(t){if(t.sizes.length===0)return new Map;let n=t.command??`gjsify ship`,S=await(t.spawn??spawnToCompletion)(`gjs`,[`-c`,Kz,t.svg,...t.sizes.map(String)],{completion:`return`,stdio:`capture`,env:rasterizerEnv(),maxBuffer:64*1024*1024,notFound:()=>Error(`${n}: \`gjs\` is not on PATH, and it is what renders ${t.svg} into the sizes an icon needs on this OS. ${Uz}.`)}),C=S.stdout??``;if(S.code!==0){let C=(S.stderr??``).trim(),N=/Rsvg|Typelib|cairo/i.test(C)?` The Rsvg typelib or GJS's cairo binding is missing. ${Uz}.`:``;throw Error(`${n}: rendering ${t.svg} through gjs failed (exit ${S.code??S.signal}).${N}${C===``?``:`\n ${C.split(`
|
|
1097
1097
|
`).join(`
|
|
1098
|
-
`)}`}`)}let N;try{N=JSON.parse(C)}catch{throw Error(`${n}: gjs printed something other than the rendered icon while rendering ${t.svg}: ${C.slice(0,200)}`)}let F=new Map;for(let S of t.sizes){let C=N[String(S)];if(C===void 0)throw Error(`${n}: gjs rendered no ${S} px image of ${t.svg}.`);let I=new Uint8Array(Buffer.from(C,`base64`)),{width:H,height:W}=readPngSize(I,`the ${S} px render of ${t.svg}`);if(H!==S||W!==S)throw Error(`${n}: asked gjs for a ${S} px render of ${t.svg} and got ${H}×${W}.`);F.set(S,I)}return F}async function resolveAppIcon(t){let n=t.iconFiles.filter(t=>$(t).toLowerCase()===`.svg`&&!isSymbolicIcon(t)),S=t.iconFiles.filter(t=>$(t).toLowerCase()===`.png`&&!isSymbolicIcon(t)),C=`data/icons/hicolor/scalable/apps/${t.appId}.svg`;if(n.length===0&&S.length===0)throw Error(`gjsify ship: ${t.target} needs the app's icon and the project declares none. Add a scalable SVG at ${C} (or point \`gjsify.ship.icon\` at one) and \`gjsify ship\` renders every size from it. An app with no icon here ships with the generic one, and nothing on the target OS says so.`);let N=n.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??n[0],F=new Map,I=new Map;for(let n of S){let S=new Uint8Array(readFileSync(n)),{width:C,height:N}=readPngSize(S,n);if(C!==N)throw Error(`gjsify ship: ${n} is ${C}×${N}, and an app icon is square on every platform that reads one — Windows and macOS both index icon images by one edge length.`);let H=iconThemeDir(n);if(H!==`${C}x${C}`)throw Error(`gjsify ship: ${n} is ${C}×${N} but its path says ${H}. The theme looks the file up by the path, so this icon would be served at the wrong size — move it or resize it.`);if(!t.sizes.includes(C))continue;let W=I.get(C);if(W!==void 0)throw Error(`gjsify ship: ${n} and ${W} are both ${C} px icons. Keep one.`);I.set(C,n),F.set(C,S)}let H=t.sizes.filter(t=>!F.has(t));if(H.length>0){if(N===void 0)throw Error(`gjsify ship: ${t.target} needs the app's icon at ${H.join(`, `)} px and the project ships PNGs only for ${[...F.keys()].sort((t,n)=>t-n).join(`, `)||`no size`}. Add a scalable SVG at ${C} and the rest is rendered from it, or add ${H.map(n=>`data/icons/hicolor/${n}x${n}/apps/${t.appId}.png`).join(`, `)}.`);let n=await(t.rasterize??rasterizeSvg)({svg:N,sizes:H});for(let t of H){let S=n.get(t);if(S===void 0)throw Error(`gjsify ship: ${N} rendered no ${t} px image.`);F.set(t,S)}}return{source:I.size===0?`rendered from ${N}`:H.length===0?`${I.size} sized PNG(s) the project ships`:`${I.size} sized PNG(s) the project ships, the rest rendered from ${N}`,png:F}}function iconSizes(t){return[...t.png.keys()].sort((t,n)=>t-n)}var
|
|
1098
|
+
`)}`}`)}let N;try{N=JSON.parse(C)}catch{throw Error(`${n}: gjs printed something other than the rendered icon while rendering ${t.svg}: ${C.slice(0,200)}`)}let F=new Map;for(let S of t.sizes){let C=N[String(S)];if(C===void 0)throw Error(`${n}: gjs rendered no ${S} px image of ${t.svg}.`);let I=new Uint8Array(Buffer.from(C,`base64`)),{width:H,height:W}=readPngSize(I,`the ${S} px render of ${t.svg}`);if(H!==S||W!==S)throw Error(`${n}: asked gjs for a ${S} px render of ${t.svg} and got ${H}×${W}.`);F.set(S,I)}return F}async function resolveAppIcon(t){let n=t.iconFiles.filter(t=>$(t).toLowerCase()===`.svg`&&!isSymbolicIcon(t)),S=t.iconFiles.filter(t=>$(t).toLowerCase()===`.png`&&!isSymbolicIcon(t)),C=`data/icons/hicolor/scalable/apps/${t.appId}.svg`;if(n.length===0&&S.length===0)throw Error(`gjsify ship: ${t.target} needs the app's icon and the project declares none. Add a scalable SVG at ${C} (or point \`gjsify.ship.icon\` at one) and \`gjsify ship\` renders every size from it. An app with no icon here ships with the generic one, and nothing on the target OS says so.`);let N=n.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??n[0],F=new Map,I=new Map;for(let n of S){let S=new Uint8Array(readFileSync(n)),{width:C,height:N}=readPngSize(S,n);if(C!==N)throw Error(`gjsify ship: ${n} is ${C}×${N}, and an app icon is square on every platform that reads one — Windows and macOS both index icon images by one edge length.`);let H=iconThemeDir(n);if(H!==`${C}x${C}`)throw Error(`gjsify ship: ${n} is ${C}×${N} but its path says ${H}. The theme looks the file up by the path, so this icon would be served at the wrong size — move it or resize it.`);if(!t.sizes.includes(C))continue;let W=I.get(C);if(W!==void 0)throw Error(`gjsify ship: ${n} and ${W} are both ${C} px icons. Keep one.`);I.set(C,n),F.set(C,S)}let H=t.sizes.filter(t=>!F.has(t));if(H.length>0){if(N===void 0)throw Error(`gjsify ship: ${t.target} needs the app's icon at ${H.join(`, `)} px and the project ships PNGs only for ${[...F.keys()].sort((t,n)=>t-n).join(`, `)||`no size`}. Add a scalable SVG at ${C} and the rest is rendered from it, or add ${H.map(n=>`data/icons/hicolor/${n}x${n}/apps/${t.appId}.png`).join(`, `)}.`);let n=await(t.rasterize??rasterizeSvg)({svg:N,sizes:H});for(let t of H){let S=n.get(t);if(S===void 0)throw Error(`gjsify ship: ${N} rendered no ${t} px image.`);F.set(t,S)}}return{source:I.size===0?`rendered from ${N}`:H.length===0?`${I.size} sized PNG(s) the project ships`:`${I.size} sized PNG(s) the project ships, the rest rendered from ${N}`,png:F}}function iconSizes(t){return[...t.png.keys()].sort((t,n)=>t-n)}var Uz,Wz,Gz,Kz,qz=__esmMin(()=>{Md(),jn(),$P(),j_(),Uz="Fedora: `sudo dnf install gjs librsvg2`, Debian/Ubuntu: `sudo apt install gjs gir1.2-rsvg-2.0`, macOS: `brew install gjs librsvg gobject-introspection`",Wz=[137,80,78,71,13,10,26,10],Gz=[0,0,0,0,73,69,78,68,174,66,96,130],Kz=`imports.gi.versions.Rsvg = '2.0';
|
|
1099
1099
|
const { Rsvg, GLib } = imports.gi;
|
|
1100
1100
|
const Cairo = imports.cairo;
|
|
1101
1101
|
const [svg, ...sizes] = ARGV;
|
|
@@ -1114,58 +1114,58 @@ for (const text of sizes) {
|
|
|
1114
1114
|
GLib.unlink(path);
|
|
1115
1115
|
out[size] = GLib.base64_encode(bytes);
|
|
1116
1116
|
}
|
|
1117
|
-
print(JSON.stringify(out));`});function head(t,n){let S=Buffer.alloc(8);return S.write(t,0,`latin1`),S.writeUInt32BE(n,4),new Uint8Array(S)}function buildIcns(t){let n=qz.map(n=>{let S=t.png.get(n.size);if(S===void 0)throw Error(`gjsify ship: the macOS icon needs a ${n.size} px image (${n.iconset}) and the raster set has none — \`resolveAppIcon\` was asked for the wrong sizes.`);let{width:C,height:N}=readPngSize(S,`the ${n.size} px icon image`);if(C!==n.size||N!==n.size)throw Error(`gjsify ship: the image keyed ${n.size} in the icon raster set is ${C}×${N}.`);return{...n,png:S}}),S=concatBytes([head(`TOC `,8+8*n.length),...n.map(t=>head(t.type,8+t.png.length))]),C=n.map(t=>concatBytes([head(t.type,8+t.png.length),t.png]));return concatBytes([head(`icns`,8+S.length+C.reduce((t,n)=>t+n.length,0)),S,...C])}var qz,Jz,Yz=__esmMin(()=>{Tz(),Kz(),qz=[{type:`icp4`,size:16,iconset:`icon_16x16.png`},{type:`ic11`,size:32,iconset:`icon_16x16@2x.png`},{type:`icp5`,size:32,iconset:`icon_32x32.png`},{type:`ic12`,size:64,iconset:`icon_32x32@2x.png`},{type:`ic07`,size:128,iconset:`icon_128x128.png`},{type:`ic13`,size:256,iconset:`icon_128x128@2x.png`},{type:`ic08`,size:256,iconset:`icon_256x256.png`},{type:`ic14`,size:512,iconset:`icon_256x256@2x.png`},{type:`ic09`,size:512,iconset:`icon_512x512.png`},{type:`ic10`,size:1024,iconset:`icon_512x512@2x.png`}],Jz=[...new Set(qz.map(t=>t.size))].sort((t,n)=>t-n)});function entryHead(t){let n=Buffer.alloc(8);return n.writeUInt8(t>=256?0:t,0),n.writeUInt8(t>=256?0:t,1),n.writeUInt8(0,2),n.writeUInt8(0,3),n.writeUInt16LE(1,4),n.writeUInt16LE(32,6),new Uint8Array(n)}function entries(t){let n=[];for(let S of Xz){let C=t.png.get(S);if(C===void 0)throw Error(`gjsify ship: the Windows icon needs a ${S} px image and the raster set has none — \`resolveAppIcon\` was asked for the wrong sizes (it has ${[...t.png.keys()].join(`, `)}).`);let{width:N,height:F}=readPngSize(C,`the ${S} px icon image`);if(N!==S||F!==S)throw Error(`gjsify ship: the image keyed ${S} in the icon raster set is ${N}×${F}.`);if(S>256)throw Error(`gjsify ship: a Windows icon image cannot be ${S} px — 256 is the format's ceiling.`);n.push({size:S,png:C})}return n}function iconResources(t){let n=entries(t),S=Buffer.alloc(6);S.writeUInt16LE(0,0),S.writeUInt16LE(1,2),S.writeUInt16LE(n.length,4);let C=[];return n.forEach(({size:t,png:n},S)=>{let N=Buffer.alloc(6);N.writeUInt32LE(n.length,0),N.writeUInt16LE(S+1,4),C.push(entryHead(t),new Uint8Array(N))}),{group:concatBytes([new Uint8Array(S),...C]),icons:n.map(t=>t.png)}}var Xz,Zz=__esmMin(()=>{Tz(),Kz(),Xz=[16,24,32,48,64,256]});function movImm32(t,n,S){let C={eax:184,ecx:185,edx:186,r8d:184,r9d:185,r14d:190}[n];(n===`r8d`||n===`r9d`||n===`r14d`)&&t.push(65),t.push(C);let N=Buffer.alloc(4);N.writeInt32LE(S|0),t.push(...N)}function movStackDword(t,n,S){t.push(199,132,36);let C=Buffer.alloc(4);C.writeInt32LE(n),t.push(...C);let N=Buffer.alloc(4);N.writeInt32LE(S|0),t.push(...N)}function movStackFromReg(t,n,S){let C={rax:132,rbx:156,rsi:180,rdi:188}[n];t.push(72,137,C,36);let N=Buffer.alloc(4);N.writeInt32LE(S),t.push(...N)}function movRaxFromStack(t,n){t.push(72,139,132,36);let S=Buffer.alloc(4);S.writeInt32LE(n),t.push(...S)}function leaStack(t,n,S){let C={rax:132,rcx:140,rdx:148,rdi:188,r9:140}[n];t.push(n===`r9`?76:72,141,C,36);let N=Buffer.alloc(4);N.writeInt32LE(S),t.push(...N)}function buildResourceSection(t,n){let S=t.icons.length,iconLangAt=t=>48+S*8+t*24,C=iconLangAt(S),N=C+16+8,F=N+16+8,dataEntryAt=t=>F+t*16,I=align(dataEntryAt(S+1),8),H=[];for(let n of[...t.icons,t.group])H.push({at:I,bytes:n}),I=align(I+n.length,8);let W=Buffer.alloc(I),directory=(t,n)=>{W.writeUInt16LE(0,t+12),W.writeUInt16LE(n,t+14)},entry=(t,n,S,C)=>{W.writeUInt32LE(n,t),W.writeUInt32LE(C?(2147483648|S)>>>0:S,t+4)},dataEntry=(t,S)=>{W.writeUInt32LE(n+S.at,dataEntryAt(t)),W.writeUInt32LE(S.bytes.length,dataEntryAt(t)+4)};directory(0,2),entry(16,3,32,!0),entry(24,14,C,!0),directory(32,S);for(let t=0;t<S;t++)entry(48+t*8,t+1,iconLangAt(t),!0),directory(iconLangAt(t),1),entry(iconLangAt(t)+16,mB,dataEntryAt(t),!1),dataEntry(t,H[t]);directory(C,1),entry(C+16,1,N,!0),directory(N,1),entry(N+16,mB,dataEntryAt(S),!1),dataEntry(S,H[S]);for(let t of H)W.set(t.bytes,t.at);return new Uint8Array(W)}function emitStub(){let t=new Emitter;t.push(72,131,228,240),t.push(72,129,236,iB.size&255,iB.size>>8&255,0,0),leaStack(t,`rdi`,iB.args),t.push(49,192),movImm32(t,`ecx`,(iB.size-iB.args)/8),t.push(243,72,171),t.push(49,201),t.leaRip(`rdx`,`selfBuf`),movImm32(t,`r8d`,pB.selfBuf),t.callImport(`GetModuleFileNameW`),t.push(131,248,4),t.jcc(`b`,`fail`),t.leaRip(`rdx`,`selfBuf`),t.push(137,193),t.push(72,141,4,74),t.push(102,199,64,250,99,0),t.push(102,199,64,252,109,0),t.push(102,199,64,254,100,0),t.leaRip(`rcx`,`sysBuf`),movImm32(t,`edx`,pB.sysBuf),t.callImport(`GetSystemDirectoryW`),t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,`strQuote`),t.callImport(`lstrcpyW`);for(let n of[`sysBuf`,`strCmdExe`,`selfBuf`,`strQuoteSpace`])t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,n),t.callImport(`lstrcatW`);t.callImport(`GetCommandLineW`),t.push(72,137,194),t.push(102,131,58,34),t.jcc(`ne`,`skipPlain`),t.push(72,131,194,2),t.label(`skipQuoted`),t.push(102,139,2),t.push(102,133,192),t.jcc(`e`,`argsReady`),t.push(72,131,194,2),t.push(102,131,248,34),t.jcc(`ne`,`skipQuoted`),t.jmp(`skipSpace`),t.label(`skipPlain`),t.push(102,139,2),t.push(102,133,192),t.jcc(`e`,`argsReady`),t.push(102,131,248,32),t.jcc(`e`,`skipSpace`),t.push(102,131,248,9),t.jcc(`e`,`skipSpace`),t.push(72,131,194,2),t.jmp(`skipPlain`),t.label(`skipSpace`),t.push(102,139,2),t.push(102,131,248,32),t.jcc(`e`,`skipSpaceStep`),t.push(102,131,248,9),t.jcc(`ne`,`argsReady`),t.label(`skipSpaceStep`),t.push(72,131,194,2),t.jmp(`skipSpace`),t.label(`argsReady`),t.leaRip(`rcx`,`cmdBuf`),t.callImport(`lstrcatW`),t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,`strQuote`),t.callImport(`lstrcatW`),movImm32(t,`ecx`,-10),t.callImport(`GetStdHandle`),t.push(72,137,199),movImm32(t,`ecx`,-11),t.callImport(`GetStdHandle`),t.push(72,137,195),movImm32(t,`ecx`,-12),t.callImport(`GetStdHandle`),t.push(72,137,198),t.callImport(`GetConsoleCP`),t.push(133,192),t.jcc(`ne`,`haveConsole`),movImm32(t,`r14d`,cB),t.push(72,133,219),t.jcc(`e`,`needLog`),t.push(72,131,251,255),t.jcc(`e`,`needLog`),t.push(72,133,246),t.jcc(`e`,`needLog`),t.push(72,131,254,255),t.jcc(`ne`,`useStdHandles`),t.label(`needLog`),movImm32(t,`ecx`,pB.tmpBuf),t.leaRip(`rdx`,`tmpBuf`),t.callImport(`GetTempPathW`),t.leaRip(`rcx`,`logBuf`),t.leaRip(`rdx`,`tmpBuf`),t.callImport(`lstrcpyW`),t.leaRip(`rcx`,`logBuf`),t.leaRip(`rdx`,`strLogLeaf`),t.callImport(`lstrcatW`),t.leaRip(`rcx`,`logBuf`),movImm32(t,`edx`,lB),movImm32(t,`r8d`,uB),leaStack(t,`r9`,iB.securityAttributes),movStackDword(t,iB.securityAttributes,oB),movStackDword(t,iB.securityAttributes+16,1),movStackDword(t,iB.args,dB),movStackDword(t,iB.args+8,fB),movStackDword(t,iB.args+16,0),t.callImport(`CreateFileW`),t.push(72,131,248,255),t.jcc(`e`,`create`),t.push(72,133,219),t.jcc(`e`,`logIsStdout`),t.push(72,131,251,255),t.jcc(`ne`,`stdoutKept`),t.label(`logIsStdout`),t.push(72,137,195),t.label(`stdoutKept`),t.push(72,133,246),t.jcc(`e`,`logIsStderr`),t.push(72,131,254,255),t.jcc(`ne`,`useStdHandles`),t.label(`logIsStderr`),t.push(72,137,198),t.label(`useStdHandles`),movStackFromReg(t,`rdi`,iB.startupInfo+80),movStackFromReg(t,`rbx`,iB.startupInfo+88),movStackFromReg(t,`rsi`,iB.startupInfo+96),movStackDword(t,iB.startupInfo+60,sB),t.jmp(`create`),t.label(`haveConsole`),t.push(69,49,246),t.label(`create`),movStackDword(t,iB.startupInfo,aB),t.push(49,201),t.leaRip(`rdx`,`cmdBuf`),t.push(69,49,192),t.push(69,49,201),movStackDword(t,iB.args,1),t.push(68,137,180,36);{let n=Buffer.alloc(4);n.writeInt32LE(iB.args+8),t.push(...n)}movStackDword(t,iB.args+16,0),movStackDword(t,iB.args+24,0),leaStack(t,`rax`,iB.startupInfo),movStackFromReg(t,`rax`,iB.args+32),leaStack(t,`rax`,iB.processInformation),movStackFromReg(t,`rax`,iB.args+40),t.callImport(`CreateProcessW`),t.push(133,192),t.jcc(`e`,`fail`),movRaxFromStack(t,iB.processInformation),t.push(72,137,193),movImm32(t,`edx`,-1),t.callImport(`WaitForSingleObject`),movRaxFromStack(t,iB.processInformation),t.push(72,137,193),leaStack(t,`rdx`,iB.exitCode),t.callImport(`GetExitCodeProcess`),t.push(139,140,36);{let n=Buffer.alloc(4);n.writeInt32LE(iB.exitCode),t.push(...n)}return t.callImport(`ExitProcess`),t.label(`fail`),movImm32(t,`ecx`,1),t.callImport(`ExitProcess`),t.push(204),t}function wide(t){return new Uint8Array(Buffer.from(`${t}\0`,`utf16le`))}function dataItems(t){let n=[];for(let t of rB)n.push({symbol:`iat.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`iat.null`,bytes:new Uint8Array(8)}),n.push({symbol:`importDescriptors`,bytes:new Uint8Array(40)});for(let t of rB)n.push({symbol:`ilt.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`ilt.null`,bytes:new Uint8Array(8)});for(let t of rB){let S=Buffer.from(`\0\0${t}\0`,`latin1`);n.push({symbol:`hint.${t}`,bytes:new Uint8Array(S.length%2==0?S:Buffer.concat([S,Buffer.alloc(1)]))})}n.push({symbol:`dllName`,bytes:new Uint8Array(Buffer.from(`KERNEL32.dll\0\0`,`latin1`))}),n.push({symbol:`strQuote`,bytes:wide(`"`)}),n.push({symbol:`strCmdExe`,bytes:wide(`\\cmd.exe" /s /c ""`)}),n.push({symbol:`strQuoteSpace`,bytes:wide(`" `)}),n.push({symbol:`strLogLeaf`,bytes:wide(t.logLeaf)});for(let[t,S]of Object.entries(pB))n.push({symbol:t,bytes:new Uint8Array(S*2)});return n}function align(t,n){return Math.ceil(t/n)*n}function buildGuiLauncher(t){if(t.logLeaf===``||/[\\/:*?"<>|]/.test(t.logLeaf))throw Error(`gjsify ship: "${t.logLeaf}" cannot be the launcher's log file name — it is empty or holds a character Windows refuses in one. The stub writes it into \`%TEMP%\`, so the value is a leaf and never a path.`);let n=emitStub(),S=n.bytes.length,C=tB,N=C+align(S,tB),F=dataItems(t),I=new Map,H=0;for(let t of F)I.set(t.symbol,H),H+=t.bytes.length;let W=H,rvaOf=t=>{let n=I.get(t);if(n===void 0)throw Error(`gjsify ship: the launcher stub names no datum "${t}".`);return N+n},q=Buffer.alloc(W);for(let t of F)q.set(t.bytes,I.get(t.symbol)??0);q.writeUInt32LE(rvaOf(`ilt.GetModuleFileNameW`),I.get(`importDescriptors`)??0),q.writeUInt32LE(rvaOf(`dllName`),(I.get(`importDescriptors`)??0)+12),q.writeUInt32LE(rvaOf(`iat.GetModuleFileNameW`),(I.get(`importDescriptors`)??0)+16);for(let t of rB){let n=BigInt(rvaOf(`hint.${t}`));q.writeBigUInt64LE(n,I.get(`ilt.${t}`)??0),q.writeBigUInt64LE(n,I.get(`iat.${t}`)??0)}let Y=n.resolve(C,rvaOf),X=align(S,eB),Z=align(W,eB),te=eB,ne=te,re=ne+X,ie=N+align(W,tB),ae=t.icon===void 0?void 0:buildResourceSection(t.icon,ie),oe=ae===void 0?0:align(ae.length,eB),Q=re+Z,se=ae===void 0?2:3,ce=ae===void 0?N+align(W,tB):ie+align(ae.length,tB),le=Buffer.alloc(Q+oe);le.write(`MZ`,0,`ascii`),le.write(`This program cannot be run in DOS mode.\r\r
|
|
1118
|
-
$`,64,`ascii`),le.writeUInt32LE(
|
|
1119
|
-
`)}\n\t</array>`}function renderInfoPlist(t,n,S){let C=assertPlistText(t.name,`CFBundleName`,`gjsify.ship.name`),N=assertPlistText(t.binaryName,`CFBundleExecutable`,`gjsify.ship.binaryName`),F=assertPlistText(t.appId,`CFBundleIdentifier`,`gjsify.ship.appId`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,...n===void 0?[]:[stringEntry(`ATSApplicationFontsPath`,n)],stringEntry(`CFBundleDevelopmentRegion`,`en`),stringEntry(`CFBundleDisplayName`,C),stringEntry(`CFBundleExecutable`,N),...S===void 0?[]:[stringEntry(`CFBundleIconFile`,S)],stringEntry(`CFBundleIdentifier`,F),stringEntry(`CFBundleInfoDictionaryVersion`,`6.0`),stringEntry(`CFBundleName`,C),stringEntry(`CFBundlePackageType`,
|
|
1120
|
-
`)}function renderPkgInfo(){return`${
|
|
1117
|
+
print(JSON.stringify(out));`});function head(t,n){let S=Buffer.alloc(8);return S.write(t,0,`latin1`),S.writeUInt32BE(n,4),new Uint8Array(S)}function buildIcns(t){let n=Jz.map(n=>{let S=t.png.get(n.size);if(S===void 0)throw Error(`gjsify ship: the macOS icon needs a ${n.size} px image (${n.iconset}) and the raster set has none — \`resolveAppIcon\` was asked for the wrong sizes.`);let{width:C,height:N}=readPngSize(S,`the ${n.size} px icon image`);if(C!==n.size||N!==n.size)throw Error(`gjsify ship: the image keyed ${n.size} in the icon raster set is ${C}×${N}.`);return{...n,png:S}}),S=concatBytes([head(`TOC `,8+8*n.length),...n.map(t=>head(t.type,8+t.png.length))]),C=n.map(t=>concatBytes([head(t.type,8+t.png.length),t.png]));return concatBytes([head(`icns`,8+S.length+C.reduce((t,n)=>t+n.length,0)),S,...C])}var Jz,Yz,Xz=__esmMin(()=>{Ez(),qz(),Jz=[{type:`icp4`,size:16,iconset:`icon_16x16.png`},{type:`ic11`,size:32,iconset:`icon_16x16@2x.png`},{type:`icp5`,size:32,iconset:`icon_32x32.png`},{type:`ic12`,size:64,iconset:`icon_32x32@2x.png`},{type:`ic07`,size:128,iconset:`icon_128x128.png`},{type:`ic13`,size:256,iconset:`icon_128x128@2x.png`},{type:`ic08`,size:256,iconset:`icon_256x256.png`},{type:`ic14`,size:512,iconset:`icon_256x256@2x.png`},{type:`ic09`,size:512,iconset:`icon_512x512.png`},{type:`ic10`,size:1024,iconset:`icon_512x512@2x.png`}],Yz=[...new Set(Jz.map(t=>t.size))].sort((t,n)=>t-n)});function entryHead(t){let n=Buffer.alloc(8);return n.writeUInt8(t>=256?0:t,0),n.writeUInt8(t>=256?0:t,1),n.writeUInt8(0,2),n.writeUInt8(0,3),n.writeUInt16LE(1,4),n.writeUInt16LE(32,6),new Uint8Array(n)}function entries(t){let n=[];for(let S of Zz){let C=t.png.get(S);if(C===void 0)throw Error(`gjsify ship: the Windows icon needs a ${S} px image and the raster set has none — \`resolveAppIcon\` was asked for the wrong sizes (it has ${[...t.png.keys()].join(`, `)}).`);let{width:N,height:F}=readPngSize(C,`the ${S} px icon image`);if(N!==S||F!==S)throw Error(`gjsify ship: the image keyed ${S} in the icon raster set is ${N}×${F}.`);if(S>256)throw Error(`gjsify ship: a Windows icon image cannot be ${S} px — 256 is the format's ceiling.`);n.push({size:S,png:C})}return n}function iconResources(t){let n=entries(t),S=Buffer.alloc(6);S.writeUInt16LE(0,0),S.writeUInt16LE(1,2),S.writeUInt16LE(n.length,4);let C=[];return n.forEach(({size:t,png:n},S)=>{let N=Buffer.alloc(6);N.writeUInt32LE(n.length,0),N.writeUInt16LE(S+1,4),C.push(entryHead(t),new Uint8Array(N))}),{group:concatBytes([new Uint8Array(S),...C]),icons:n.map(t=>t.png)}}var Zz,Qz=__esmMin(()=>{Ez(),qz(),Zz=[16,24,32,48,64,256]});function movImm32(t,n,S){let C={eax:184,ecx:185,edx:186,r8d:184,r9d:185,r14d:190}[n];(n===`r8d`||n===`r9d`||n===`r14d`)&&t.push(65),t.push(C);let N=Buffer.alloc(4);N.writeInt32LE(S|0),t.push(...N)}function movStackDword(t,n,S){t.push(199,132,36);let C=Buffer.alloc(4);C.writeInt32LE(n),t.push(...C);let N=Buffer.alloc(4);N.writeInt32LE(S|0),t.push(...N)}function movStackFromReg(t,n,S){let C={rax:132,rbx:156,rsi:180,rdi:188}[n];t.push(72,137,C,36);let N=Buffer.alloc(4);N.writeInt32LE(S),t.push(...N)}function movRaxFromStack(t,n){t.push(72,139,132,36);let S=Buffer.alloc(4);S.writeInt32LE(n),t.push(...S)}function leaStack(t,n,S){let C={rax:132,rcx:140,rdx:148,rdi:188,r9:140}[n];t.push(n===`r9`?76:72,141,C,36);let N=Buffer.alloc(4);N.writeInt32LE(S),t.push(...N)}function buildResourceSection(t,n){let S=t.icons.length,iconLangAt=t=>48+S*8+t*24,C=iconLangAt(S),N=C+16+8,F=N+16+8,dataEntryAt=t=>F+t*16,I=align(dataEntryAt(S+1),8),H=[];for(let n of[...t.icons,t.group])H.push({at:I,bytes:n}),I=align(I+n.length,8);let W=Buffer.alloc(I),directory=(t,n)=>{W.writeUInt16LE(0,t+12),W.writeUInt16LE(n,t+14)},entry=(t,n,S,C)=>{W.writeUInt32LE(n,t),W.writeUInt32LE(C?(2147483648|S)>>>0:S,t+4)},dataEntry=(t,S)=>{W.writeUInt32LE(n+S.at,dataEntryAt(t)),W.writeUInt32LE(S.bytes.length,dataEntryAt(t)+4)};directory(0,2),entry(16,3,32,!0),entry(24,14,C,!0),directory(32,S);for(let t=0;t<S;t++)entry(48+t*8,t+1,iconLangAt(t),!0),directory(iconLangAt(t),1),entry(iconLangAt(t)+16,hB,dataEntryAt(t),!1),dataEntry(t,H[t]);directory(C,1),entry(C+16,1,N,!0),directory(N,1),entry(N+16,hB,dataEntryAt(S),!1),dataEntry(S,H[S]);for(let t of H)W.set(t.bytes,t.at);return new Uint8Array(W)}function emitStub(){let t=new Emitter;t.push(72,131,228,240),t.push(72,129,236,aB.size&255,aB.size>>8&255,0,0),leaStack(t,`rdi`,aB.args),t.push(49,192),movImm32(t,`ecx`,(aB.size-aB.args)/8),t.push(243,72,171),t.push(49,201),t.leaRip(`rdx`,`selfBuf`),movImm32(t,`r8d`,mB.selfBuf),t.callImport(`GetModuleFileNameW`),t.push(131,248,4),t.jcc(`b`,`fail`),t.leaRip(`rdx`,`selfBuf`),t.push(137,193),t.push(72,141,4,74),t.push(102,199,64,250,99,0),t.push(102,199,64,252,109,0),t.push(102,199,64,254,100,0),t.leaRip(`rcx`,`sysBuf`),movImm32(t,`edx`,mB.sysBuf),t.callImport(`GetSystemDirectoryW`),t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,`strQuote`),t.callImport(`lstrcpyW`);for(let n of[`sysBuf`,`strCmdExe`,`selfBuf`,`strQuoteSpace`])t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,n),t.callImport(`lstrcatW`);t.callImport(`GetCommandLineW`),t.push(72,137,194),t.push(102,131,58,34),t.jcc(`ne`,`skipPlain`),t.push(72,131,194,2),t.label(`skipQuoted`),t.push(102,139,2),t.push(102,133,192),t.jcc(`e`,`argsReady`),t.push(72,131,194,2),t.push(102,131,248,34),t.jcc(`ne`,`skipQuoted`),t.jmp(`skipSpace`),t.label(`skipPlain`),t.push(102,139,2),t.push(102,133,192),t.jcc(`e`,`argsReady`),t.push(102,131,248,32),t.jcc(`e`,`skipSpace`),t.push(102,131,248,9),t.jcc(`e`,`skipSpace`),t.push(72,131,194,2),t.jmp(`skipPlain`),t.label(`skipSpace`),t.push(102,139,2),t.push(102,131,248,32),t.jcc(`e`,`skipSpaceStep`),t.push(102,131,248,9),t.jcc(`ne`,`argsReady`),t.label(`skipSpaceStep`),t.push(72,131,194,2),t.jmp(`skipSpace`),t.label(`argsReady`),t.leaRip(`rcx`,`cmdBuf`),t.callImport(`lstrcatW`),t.leaRip(`rcx`,`cmdBuf`),t.leaRip(`rdx`,`strQuote`),t.callImport(`lstrcatW`),movImm32(t,`ecx`,-10),t.callImport(`GetStdHandle`),t.push(72,137,199),movImm32(t,`ecx`,-11),t.callImport(`GetStdHandle`),t.push(72,137,195),movImm32(t,`ecx`,-12),t.callImport(`GetStdHandle`),t.push(72,137,198),t.callImport(`GetConsoleCP`),t.push(133,192),t.jcc(`ne`,`haveConsole`),movImm32(t,`r14d`,lB),t.push(72,133,219),t.jcc(`e`,`needLog`),t.push(72,131,251,255),t.jcc(`e`,`needLog`),t.push(72,133,246),t.jcc(`e`,`needLog`),t.push(72,131,254,255),t.jcc(`ne`,`useStdHandles`),t.label(`needLog`),movImm32(t,`ecx`,mB.tmpBuf),t.leaRip(`rdx`,`tmpBuf`),t.callImport(`GetTempPathW`),t.leaRip(`rcx`,`logBuf`),t.leaRip(`rdx`,`tmpBuf`),t.callImport(`lstrcpyW`),t.leaRip(`rcx`,`logBuf`),t.leaRip(`rdx`,`strLogLeaf`),t.callImport(`lstrcatW`),t.leaRip(`rcx`,`logBuf`),movImm32(t,`edx`,uB),movImm32(t,`r8d`,dB),leaStack(t,`r9`,aB.securityAttributes),movStackDword(t,aB.securityAttributes,sB),movStackDword(t,aB.securityAttributes+16,1),movStackDword(t,aB.args,fB),movStackDword(t,aB.args+8,pB),movStackDword(t,aB.args+16,0),t.callImport(`CreateFileW`),t.push(72,131,248,255),t.jcc(`e`,`create`),t.push(72,133,219),t.jcc(`e`,`logIsStdout`),t.push(72,131,251,255),t.jcc(`ne`,`stdoutKept`),t.label(`logIsStdout`),t.push(72,137,195),t.label(`stdoutKept`),t.push(72,133,246),t.jcc(`e`,`logIsStderr`),t.push(72,131,254,255),t.jcc(`ne`,`useStdHandles`),t.label(`logIsStderr`),t.push(72,137,198),t.label(`useStdHandles`),movStackFromReg(t,`rdi`,aB.startupInfo+80),movStackFromReg(t,`rbx`,aB.startupInfo+88),movStackFromReg(t,`rsi`,aB.startupInfo+96),movStackDword(t,aB.startupInfo+60,cB),t.jmp(`create`),t.label(`haveConsole`),t.push(69,49,246),t.label(`create`),movStackDword(t,aB.startupInfo,oB),t.push(49,201),t.leaRip(`rdx`,`cmdBuf`),t.push(69,49,192),t.push(69,49,201),movStackDword(t,aB.args,1),t.push(68,137,180,36);{let n=Buffer.alloc(4);n.writeInt32LE(aB.args+8),t.push(...n)}movStackDword(t,aB.args+16,0),movStackDword(t,aB.args+24,0),leaStack(t,`rax`,aB.startupInfo),movStackFromReg(t,`rax`,aB.args+32),leaStack(t,`rax`,aB.processInformation),movStackFromReg(t,`rax`,aB.args+40),t.callImport(`CreateProcessW`),t.push(133,192),t.jcc(`e`,`fail`),movRaxFromStack(t,aB.processInformation),t.push(72,137,193),movImm32(t,`edx`,-1),t.callImport(`WaitForSingleObject`),movRaxFromStack(t,aB.processInformation),t.push(72,137,193),leaStack(t,`rdx`,aB.exitCode),t.callImport(`GetExitCodeProcess`),t.push(139,140,36);{let n=Buffer.alloc(4);n.writeInt32LE(aB.exitCode),t.push(...n)}return t.callImport(`ExitProcess`),t.label(`fail`),movImm32(t,`ecx`,1),t.callImport(`ExitProcess`),t.push(204),t}function wide(t){return new Uint8Array(Buffer.from(`${t}\0`,`utf16le`))}function dataItems(t){let n=[];for(let t of iB)n.push({symbol:`iat.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`iat.null`,bytes:new Uint8Array(8)}),n.push({symbol:`importDescriptors`,bytes:new Uint8Array(40)});for(let t of iB)n.push({symbol:`ilt.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`ilt.null`,bytes:new Uint8Array(8)});for(let t of iB){let S=Buffer.from(`\0\0${t}\0`,`latin1`);n.push({symbol:`hint.${t}`,bytes:new Uint8Array(S.length%2==0?S:Buffer.concat([S,Buffer.alloc(1)]))})}n.push({symbol:`dllName`,bytes:new Uint8Array(Buffer.from(`KERNEL32.dll\0\0`,`latin1`))}),n.push({symbol:`strQuote`,bytes:wide(`"`)}),n.push({symbol:`strCmdExe`,bytes:wide(`\\cmd.exe" /s /c ""`)}),n.push({symbol:`strQuoteSpace`,bytes:wide(`" `)}),n.push({symbol:`strLogLeaf`,bytes:wide(t.logLeaf)});for(let[t,S]of Object.entries(mB))n.push({symbol:t,bytes:new Uint8Array(S*2)});return n}function align(t,n){return Math.ceil(t/n)*n}function buildGuiLauncher(t){if(t.logLeaf===``||/[\\/:*?"<>|]/.test(t.logLeaf))throw Error(`gjsify ship: "${t.logLeaf}" cannot be the launcher's log file name — it is empty or holds a character Windows refuses in one. The stub writes it into \`%TEMP%\`, so the value is a leaf and never a path.`);let n=emitStub(),S=n.bytes.length,C=nB,N=C+align(S,nB),F=dataItems(t),I=new Map,H=0;for(let t of F)I.set(t.symbol,H),H+=t.bytes.length;let W=H,rvaOf=t=>{let n=I.get(t);if(n===void 0)throw Error(`gjsify ship: the launcher stub names no datum "${t}".`);return N+n},q=Buffer.alloc(W);for(let t of F)q.set(t.bytes,I.get(t.symbol)??0);q.writeUInt32LE(rvaOf(`ilt.GetModuleFileNameW`),I.get(`importDescriptors`)??0),q.writeUInt32LE(rvaOf(`dllName`),(I.get(`importDescriptors`)??0)+12),q.writeUInt32LE(rvaOf(`iat.GetModuleFileNameW`),(I.get(`importDescriptors`)??0)+16);for(let t of iB){let n=BigInt(rvaOf(`hint.${t}`));q.writeBigUInt64LE(n,I.get(`ilt.${t}`)??0),q.writeBigUInt64LE(n,I.get(`iat.${t}`)??0)}let Y=n.resolve(C,rvaOf),X=align(S,tB),Z=align(W,tB),te=tB,ne=te,re=ne+X,ie=N+align(W,nB),ae=t.icon===void 0?void 0:buildResourceSection(t.icon,ie),oe=ae===void 0?0:align(ae.length,tB),Q=re+Z,se=ae===void 0?2:3,ce=ae===void 0?N+align(W,nB):ie+align(ae.length,nB),le=Buffer.alloc(Q+oe);le.write(`MZ`,0,`ascii`),le.write(`This program cannot be run in DOS mode.\r\r
|
|
1118
|
+
$`,64,`ascii`),le.writeUInt32LE(eB,60),le.write(`PE\0\0`,eB,`ascii`),le.writeUInt16LE($z,132),le.writeUInt16LE(se,134),le.writeUInt32LE(0,136),le.writeUInt16LE(240,148),le.writeUInt16LE(35,150),le.writeUInt16LE(523,152),le.writeUInt8(14,154),le.writeUInt32LE(X,156),le.writeUInt32LE(Z+oe,160),le.writeUInt32LE(C,168),le.writeUInt32LE(C,172),le.writeBigUInt64LE(rB,176),le.writeUInt32LE(nB,184),le.writeUInt32LE(tB,188),le.writeUInt16LE(6,192),le.writeUInt16LE(6,200),le.writeUInt32LE(ce,208),le.writeUInt32LE(te,212),le.writeUInt16LE(2,220),le.writeUInt16LE(33024,222),le.writeBigUInt64LE(1048576n,224),le.writeBigUInt64LE(4096n,232),le.writeBigUInt64LE(1048576n,240),le.writeBigUInt64LE(4096n,248),le.writeUInt32LE(16,260),le.writeUInt32LE(rvaOf(`importDescriptors`),272),le.writeUInt32LE(40,276),le.writeUInt32LE(rvaOf(`iat.GetModuleFileNameW`),360),le.writeUInt32LE((iB.length+1)*8,364),ae!==void 0&&(le.writeUInt32LE(ie,280),le.writeUInt32LE(ae.length,284));let writeSection=(t,n,S,C,N,F,I)=>{let H=392+t*40;le.write(n.padEnd(8,`\0`),H,`latin1`),le.writeUInt32LE(C,H+8),le.writeUInt32LE(S,H+12),le.writeUInt32LE(F,H+16),le.writeUInt32LE(N,H+20),le.writeUInt32LE(I,H+36)};return writeSection(0,`.text`,C,S,ne,X,1610612768),writeSection(1,`.data`,N,W,re,Z,3221225536),ae!==void 0&&writeSection(2,`.rsrc`,ie,ae.length,Q,oe,1073741888),le.set(Y,ne),le.set(q,re),ae!==void 0&&le.set(ae,Q),new Uint8Array(le)}var $z,eB,tB,nB,rB,iB,Emitter,aB,oB,sB,cB,lB,uB,dB,fB,pB,mB,hB,gB=__esmMin(()=>{Qz(),$z=34404,eB=128,tB=512,nB=4096,rB=5368709120n,iB=[`GetModuleFileNameW`,`GetSystemDirectoryW`,`GetCommandLineW`,`GetConsoleCP`,`GetStdHandle`,`GetTempPathW`,`CreateFileW`,`CreateProcessW`,`WaitForSingleObject`,`GetExitCodeProcess`,`ExitProcess`,`lstrcpyW`,`lstrcatW`],Emitter=class{bytes=[];labels=new Map;ripFixups=[];branchFixups=[];push(...t){for(let n of t)this.bytes.push(n&255)}label(t){this.labels.set(t,this.bytes.length)}ripSlot(t){this.ripFixups.push({at:this.bytes.length,symbol:t}),this.push(0,0,0,0)}branchSlot(t){this.branchFixups.push({at:this.bytes.length,label:t}),this.push(0,0,0,0)}leaRip(t,n){let S={rax:5,rcx:13,rdx:21,rdi:61,r8:5,r9:13}[t];this.push(t===`r8`||t===`r9`?76:72,141,S),this.ripSlot(n)}callImport(t){this.push(255,21),this.ripSlot(`iat.${t}`)}jmp(t){this.push(233),this.branchSlot(t)}jcc(t,n){this.push(15,{e:132,ne:133,b:130}[t]),this.branchSlot(n)}resolve(t,n){let S=Buffer.from(this.bytes);for(let{at:C,symbol:N}of this.ripFixups)S.writeInt32LE(n(N)-(t+C+4),C);for(let{at:t,label:n}of this.branchFixups){let C=this.labels.get(n);if(C===void 0)throw Error(`gjsify ship: the launcher stub jumps to no label "${n}".`);S.writeInt32LE(C-(t+4),t)}return new Uint8Array(S)}},aB={args:32,securityAttributes:80,startupInfo:112,processInformation:216,exitCode:240,size:272},oB=104,sB=24,cB=256,lB=134217728,uB=1073741824,dB=3,fB=2,pB=128,mB={sysBuf:264,selfBuf:520,tmpBuf:264,logBuf:600,cmdBuf:4096},hB=1033});function xmlText(t){return t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function assertPlistText(t,n,S){let C=-1;for(let n of t){let t=n.codePointAt(0)??0;if(t<32&&t!==9&&t!==10&&t!==13){C=t;break}}if(C!==-1)throw Error(`gjsify ship: ${n} would carry the control character U+${C.toString(16).padStart(4,`0`).toUpperCase()}, and XML has no escape for it — the Info.plist would be unparseable by every reader macOS has. Set \`${S}\` to a value without it.`);return t}function stringEntry(t,n){return`\t<key>${t}</key>\n\t<string>${xmlText(n)}</string>`}function arrayEntry(t,n){return`\t<key>${t}</key>\n\t<array>\n${n.map(t=>`\t\t<string>${xmlText(t)}</string>`).join(`
|
|
1119
|
+
`)}\n\t</array>`}function renderInfoPlist(t,n,S){let C=assertPlistText(t.name,`CFBundleName`,`gjsify.ship.name`),N=assertPlistText(t.binaryName,`CFBundleExecutable`,`gjsify.ship.binaryName`),F=assertPlistText(t.appId,`CFBundleIdentifier`,`gjsify.ship.appId`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,...n===void 0?[]:[stringEntry(`ATSApplicationFontsPath`,n)],stringEntry(`CFBundleDevelopmentRegion`,`en`),stringEntry(`CFBundleDisplayName`,C),stringEntry(`CFBundleExecutable`,N),...S===void 0?[]:[stringEntry(`CFBundleIconFile`,S)],stringEntry(`CFBundleIdentifier`,F),stringEntry(`CFBundleInfoDictionaryVersion`,`6.0`),stringEntry(`CFBundleName`,C),stringEntry(`CFBundlePackageType`,bB),stringEntry(`CFBundleShortVersionString`,t.version),stringEntry(`CFBundleSignature`,xB),arrayEntry(`CFBundleSupportedPlatforms`,[`MacOSX`]),stringEntry(`CFBundleVersion`,`${t.version}-${t.release}`),`</dict>`,`</plist>`,``].join(`
|
|
1120
|
+
`)}function renderPkgInfo(){return`${bB}${xB}`}function renderEntitlements(t){return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,t.map(t=>`\t<key>${xmlText(t)}</key>\n\t<true/>`).join(`
|
|
1121
1121
|
`),`</dict>`,`</plist>`,``].join(`
|
|
1122
|
-
`)}var
|
|
1123
|
-
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(t,n,S){let C=t.dirs(n);if(S===`bin/${n.binaryName}`)return launcherPath(t,n);let N=`lib/${n.binaryName}/`,F=`${N}gi/`;return S.startsWith(F)?un.join(C.native,S.slice(F.length)):S.startsWith(N)?un.join(C.bundle,S.slice(N.length)):S.startsWith(`bin/`)?un.join(C.launcher,S.slice(4)):S.startsWith(`share/`)?un.join(C.data,S.slice(6)):un.join(C.other,S)}function placeStage(t,n,S,C=[]){let N=new Map,F=[],claim=(n,S,C)=>{let I=N.get(n);if(I!==void 0)throw Error(`gjsify ship: in the ${t.name} layout both ${I} and ${S} install as ${n}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);N.set(n,S),F.push({...C,path:n})};for(let C of S)claim(place(t,n,C.path),C.path,C);for(let C of t.metadata(n,S))claim(C.path,`the ${t.name} layout's own metadata`,C);for(let n of C)claim(n.path,`the runtime staged into the ${t.name} artifact`,n);return F.sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var
|
|
1122
|
+
`)}var _B,vB,yB,bB,xB,SB=__esmMin(()=>{_B=`Contents/Info.plist`,vB=`Contents/PkgInfo`,yB=`Contents/Resources`,bB=`APPL`,xB=`????`});function darwinFontsPath(t,n){let S=`${Bz.fonts}/${t.appId}`,C=n.find(t=>t.path.startsWith(`${S}/`));if(C===void 0)return;let N=wB.darwin.dirs(t);return un.relative(N.other,un.dirname(place(wB.darwin,t,C.path)))}function appBundleDir(t){if(CB.test(t.name))throw Error(`gjsify ship: the macOS layout would put this app in "${t.name}.app", and a bundle directory may contain no "/", "\\" or ":" — HFS+ and the Finder swap the first two, so the bundle would not be the one its own metadata names. Set \`gjsify.ship.name\` to the display name you want on disk.`);return`${t.name}.app`}function iconFor(t,n){if(t.kind===`app`){if(t.icon===void 0)throw Error(`gjsify ship: the ${n} layout writes the application's icon and was given none. A \`kind: "app"\` stage is rendered its icon by \`resolveAppIcon\` before the layout runs; reaching this row without one is a caller that skipped that step.`);return t.icon}}function launcherPath(t,n){return un.join(t.dirs(n).launcher,`${n.binaryName}${t.launcherExt}`)}function windowsGuiLauncherPath(t){let n=wB.windows;if(n.launcherExt.length!==4)throw Error(`gjsify ship: the windows launcher extension is "${n.launcherExt}" and the GUI stub can only reach a four-character one — it rewrites the last three characters of its own filename rather than searching for a path (\`utils/ship/pe-launcher.ts\`).`);return un.join(n.dirs(t).launcher,`${t.binaryName}.exe`)}function windowsLaunchLogLeaf(t){return`${t.binaryName}.launch.log`}function layoutForOs(t){let n=EB.get(t);if(n===void 0)throw Error(`"${t}" is not a \`process.platform\` token this gjsify has a layout for. Known: ${TB.map(t=>wB[t].os).join(`, `)} — the \`\${process.platform}-\${process.arch}\` spelling, so \`win32\` and never \`windows\`.`);return n}function resolveLayout(t){let n=t.trim().toLowerCase();if(Object.hasOwn(wB,n))return wB[n];let S=EB.get(n);if(S!==void 0)return S;throw Error(`gjsify ship: "${t}" is not an operating system this command has a layout for. Known: ${TB.join(`, `)} (\`win32\` is accepted for \`windows\`, because that is the spelling \`--expect-target <os>-<arch>\` uses).`)}function hostLayout(t=process.platform){let n=EB.get(t);if(n===void 0)throw Error(`gjsify ship: this host is ${t}, which has no layout. Name the one you want — \`gjsify ship <${TB.join(`|`)}> --stage\` — assembly is not host-bound (ADR 0024 § A1).`);return n}function assertLayoutSupportsArch(t,n){let S=t.arches;if(!(S===null||S.only.includes(n)))throw Error(`gjsify ship: the ${t.name} layout is not assemblable for \`--arch ${n}\` — ${S.only.length===1?`the only architecture it has`:`the architectures it has`} ${S.only.length===1?`is`:`are`} ${S.only.join(`, `)}.\n ${S.why}.\n \`--arch\` names the architecture the PAYLOAD was built for and cross-compiles nothing, so there is no
|
|
1123
|
+
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(t,n,S){let C=t.dirs(n);if(S===`bin/${n.binaryName}`)return launcherPath(t,n);let N=`lib/${n.binaryName}/`,F=`${N}gi/`;return S.startsWith(F)?un.join(C.native,S.slice(F.length)):S.startsWith(N)?un.join(C.bundle,S.slice(N.length)):S.startsWith(`bin/`)?un.join(C.launcher,S.slice(4)):S.startsWith(`share/`)?un.join(C.data,S.slice(6)):un.join(C.other,S)}function placeStage(t,n,S,C=[]){let N=new Map,F=[],claim=(n,S,C)=>{let I=N.get(n);if(I!==void 0)throw Error(`gjsify ship: in the ${t.name} layout both ${I} and ${S} install as ${n}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);N.set(n,S),F.push({...C,path:n})};for(let C of S)claim(place(t,n,C.path),C.path,C);for(let C of t.metadata(n,S))claim(C.path,`the ${t.name} layout's own metadata`,C);for(let n of C)claim(n.path,`the runtime staged into the ${t.name} artifact`,n);return F.sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var CB,wB,TB,EB,DB=__esmMin(()=>{jn(),Xz(),Qz(),gB(),SB(),Vz(),CB=/[/:\\]/,wB={linux:{name:`linux`,os:`linux`,shippedRuntime:`gjs`,launcherExt:``,root:()=>``,dirs:t=>({launcher:`bin`,bundle:`lib/${t.binaryName}`,native:`lib/${t.binaryName}/gi`,data:`share`,other:``}),metadata:()=>[],arches:null},darwin:{name:`darwin`,os:`darwin`,shippedRuntime:`node`,runtimeGap:'the staged launcher execs an interpreter off `PATH`, which a downloaded `.app` cannot assume — macOS ships no Node, and there is no RELOCATABLE GJS (`build-gtk-runtime-darwin.mjs`: "GJS ships no relocation"), so ADR 0024 § 4 derives Node here. A self-contained bundle needs `@gjsify/node-runtime-darwin-<arch>` and a `--app node` payload (#1354 M0), or `@gjsify/gjs-runtime-darwin-<arch>` (ADR 0024 stage 7).',fontGap:"the faces are staged in `share/fonts/<appId>` and `Info.plist` carries `ATSApplicationFontsPath` at it, which is macOS's own per-app activation and the route that matters whenever Pango on macOS resolves CoreText by default — which it does on a Homebrew GTK, because that one is not built against fontconfig. A `.app` carrying the bundled GTK runtime reads the same faces through fontconfig instead: `@gjsify/node-gi`'s loader selects it with `PANGOCAIRO_BACKEND=fc` (ADR 0038 § Amendment 3), and `initFonts()` from `@gjsify/gtk-host/fonts` registers them as it does on Windows. Either way no branch is needed in your app: a CoreText map answers G_IO_ERROR_NOT_SUPPORTED and the call reports that as declined. Confirm in the shipped bundle with `PangoCairo.FontMap.get_default().list_families()`, and `PANGOCAIRO_BACKEND=bogus` to print which backends it was built with.",launcherExt:``,root:appBundleDir,dirs:t=>{let n=appBundleDir(t);return{launcher:`${n}/Contents/MacOS`,bundle:`${n}/Contents/Resources/lib`,native:`${n}/Contents/Resources/native`,data:`${n}/Contents/Resources/share`,other:`${n}/Contents/Resources`}},icon:{sizes:Yz,writes:"the macOS bundle icon (`Contents/Resources/<binaryName>.icns`)"},metadata:(t,n)=>{let S=iconFor(t,`darwin`),C=S===void 0?void 0:`${t.binaryName}.icns`;return[{path:`${appBundleDir(t)}/${_B}`,mode:420,source:{kind:`text`,text:renderInfoPlist(t,darwinFontsPath(t,n),C)}},{path:`${appBundleDir(t)}/${vB}`,mode:420,source:{kind:`text`,text:renderPkgInfo()}},...S===void 0||C===void 0?[]:[{path:`${appBundleDir(t)}/${yB}/${C}`,mode:420,source:{kind:`bytes`,data:buildIcns(S)}}]]},arches:{only:[`x64`,`arm64`],why:"macOS runs on x86_64 and Apple silicon and nothing else, so those are the two `@gjsify/gtk-runtime-darwin-*` and `@gjsify/node-runtime-darwin-*` targets that exist"}},windows:{name:`windows`,os:`win32`,shippedRuntime:`node`,runtimeGap:"the staged launcher execs an interpreter off `PATH`, which a downloaded program directory cannot assume — Windows ships neither, and there is NO GJS host on Windows at all (ADR 0024 § 4), so § 4 derives Node here. A self-contained directory needs `@gjsify/node-runtime-win32-x64` and a `--app node` payload (#1354 M3).",fontGap:"the faces are staged in `share/fonts/<appId>` and the launcher exports GJSIFY_FONT_DIR at it, but WINDOWS HAS NO DECLARATIVE FONT ACTIVATION and nothing here reaches a bundled face on its own: GTK4 resolves pangowin32, whose font map is populated from DirectWrite and never from fontconfig or from GDI, unless something selects otherwise — which the bundled GTK runtime does (`PANGOCAIRO_BACKEND=fc`, ADR 0038 § Amendment 3), and an app may. MEASURED on the DirectWrite map, Windows 11 / GTK 4.22.4, rather than inferred (ADR 0038 W1-W5): a FONTCONFIG_FILE naming the staged directory moves the default font map by nothing even when it is the ONLY configuration present — that map does not read fontconfig, and exposes no config_changed or set_config with which to make it — while add_font_file on the same map a Gtk.Label renders through does register the family. So register them at startup, with one call from the GTK host layer: `import { initFonts } from '@gjsify/gtk-host/fonts'`, then `initFonts()` before the first window — it reads GJSIFY_FONT_DIR itself, registers every face it holds, and no-ops on the operating systems that already activated them. Without it the app renders in a substituted family with no error.",launcherExt:`.cmd`,root:()=>``,dirs:()=>({launcher:``,bundle:`app`,native:`lib`,data:`share`,other:``}),icon:{sizes:Zz,writes:"the Windows launcher icon (`.rsrc` of `<binaryName>.exe`)"},metadata:t=>{let n=iconFor(t,`windows`);return t.arch===`x64`?[{path:windowsGuiLauncherPath(t),mode:493,source:{kind:`bytes`,data:buildGuiLauncher({logLeaf:windowsLaunchLogLeaf(t),...n===void 0?{}:{icon:iconResources(n)}})}}]:[]},arches:{only:[`x64`],why:"the arm64 GTK closure `@gjsify/gtk-runtime-win32-arm64` does not exist yet — the prefix it would be built from is no longer missing, because ADR 0089 builds it from our `gjsify/gvsbuild` fork in CI and `@gjsify/node-gi` ships a win32-arm64 prebuild against it — so what is left is the runtime package this layout would stage, ordered in `status/open-todos/windows.md` and tracked in gjsify/gjsify#1117"}}},TB=Object.keys(wB),EB=new Map(TB.map(t=>[wB[t].os,wB[t]]))});async function compileSchemasForStage(t){if(t.schemaFiles.length===0)return[];rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t.workDir,{recursive:!0});for(let n of t.schemaFiles)copyFileSync(n,xn(t.workDir,Tn(n)));return await runSchemaCompiler(t.workDir),[{path:jB,mode:420,source:{kind:`file`,path:xn(t.workDir,`gschemas.compiled`)}}]}async function compileSchemasForPayload(t){let n=t.payload.filter(t=>isSchemaSource(t.path));if(n.length!==0){rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t.workDir,{recursive:!0});for(let S of n)writeFileSync(xn(t.workDir,un.basename(S.path)),S.data);return await runSchemaCompiler(t.workDir),{path:jB,mode:420,data:readFileSync(xn(t.workDir,`gschemas.compiled`))}}}function isSchemaSource(t){return t.startsWith(`${Bz.schemas}/`)&&t.endsWith(`.gschema.xml`)}async function runSchemaCompiler(t){try{await OB(kB,[`--strict`,`--targetdir=${t}`,t])}catch(t){let n=t;throw n.code===`ENOENT`?Error(`gjsify ship: this artifact has no install step, so \`${kB}\` has to run HERE to turn the payload's schemas into \`${jB}\` — and it is not on PATH. Install it (${AB}). Without the compiled cache the launcher points XDG_DATA_DIRS at a schema directory GSettings aborts on, so the bundle would build and then die at its first \`Gio.Settings.new()\`.`):Error(`gjsify ship: \`${kB} --strict\` refused this project's schemas.\n${(n.stderr??``).trimEnd()}\n \`--strict\` is deliberate: without it a malformed schema is SKIPPED at exit 0 and a cache
|
|
1124
1124
|
is written without it, so the app still aborts on the schema that was dropped. Fix the
|
|
1125
|
-
file it names, or drop it from \`gjsify.ship.schemas\`.`)}}var
|
|
1125
|
+
file it names, or drop it from \`gjsify.ship.schemas\`.`)}}var OB,kB,AB,jB,MB=__esmMin(()=>{w_(),jn(),Md(),yu(),Vz(),OB=promisify(execFile),kB=`glib-compile-schemas`,AB="Fedora: `sudo dnf install glib2`, Debian/Ubuntu: `sudo apt install libglib2.0-bin`",jB=`${Bz.schemas}/gschemas.compiled`});function buildTimestamp(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;if(S!==void 0){let t=Number(S);if(!Number.isInteger(t)||t<0)throw Error(`gjsify ship: SOURCE_DATE_EPOCH must be a non-negative integer, got "${S}".`);return t}return Math.floor(statSync(t).mtimeMs/1e3)}function readPayloadFacts(t){let n=t.map(t=>t.path);return{hasDesktopEntry:n.some(t=>isUnder(t,Bz.applications)&&t.endsWith(`.desktop`)),hasIcons:n.some(t=>isUnder(t,Bz.icons)),hasSchemas:n.some(t=>isUnder(t,Bz.schemas)&&t.endsWith(`.gschema.xml`)),hasMimeTypes:n.some(t=>isUnder(t,Bz.mime)&&t.endsWith(`.xml`)),bundledTypelibs:n.filter(t=>t.endsWith(`.typelib`))}}function readLauncherInterpreters(t,n,S){let C=t.find(t=>t.path===launcherPath(n,S));if(C===void 0)return[];let N=new TextDecoder().decode(C.data),F=n.name===`windows`?`cmd`:`sh`,I=[];for(let t of F===`cmd`?batchCommands(N):shellExecLines(N)){let n=interpreterOf(t,F);n!==null&&I.push(n)}return[...new Set(I)]}function shellExecLines(t){return[...`\n${t}`.matchAll(/\n[ \t]*exec\s+([^\n]*)/g)].map(t=>t[1].trim())}function cmdTokens(t){let n=[],S=0;for(;S<t.length;){if(/\s/.test(t[S])){S+=1;continue}let C=S,N=!1;for(;S<t.length&&(N||!/\s/.test(t[S]));)t[S]===`"`&&(N=!N),S+=1;n.push({text:t.slice(C,S),end:S})}return n}function splitBatchBlock(t){let n=0,S=!1;for(let C=0;C<t.length;C++){let N=t[C];if(N===`"`)S=!S;else if(!S&&N===`(`)n+=1;else if(!S&&N===`)`&&(--n,n===0))return[t.slice(1,C).trim(),t.slice(C+1).trim()]}return null}function batchPrefix(t){if(t.startsWith(`(`)){let n=splitBatchBlock(t);return n===null?null:[n[0],n[1]]}let n=cmdTokens(t),word=t=>(n[t]?.text??``).toLowerCase(),after=S=>[t.slice(n[S]?.end??t.length).trim()];if(word(0)===`else`)return after(0);if(word(0)===`for`){let t=n.findIndex(t=>t.text.toLowerCase()===`do`);return t===-1?null:after(t)}if(word(0)!==`if`)return;let S=1;for(;word(S)===`not`||word(S)===`/i`;)S+=1;return PB.has(word(S))?after(S+1):word(S).includes(`==`)?after(S):FB.has(word(S+1))?after(S+2):null}function batchCommands(t){let n=[],S=t.split(/\r?\n/).map(t=>t.trim().replace(/^@+/,``).trim());for(let t=0;t<IB&&S.length>0;t++){let t=S.shift();if(t===``||t===`)`||t.startsWith(`::`))continue;let C=(cmdTokens(t)[0]?.text??``).toLowerCase();if(NB.has(C))continue;let N=batchPrefix(t);N===void 0?n.push(t):N!==null&&S.unshift(...N)}return n}function interpreterOf(t,n){if(n===`cmd`)return cmdProgramOf(t);let S=t.split(/\s+/).filter(t=>t.length>0);for(let t=0;t<2&&S.length>0;t++){let t=basenameOf(S[0]);if(t!==`env`)return t===``?null:t;S=S.slice(1).filter(t=>!t.startsWith(`-`)&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))}return null}function cmdProgramOf(t){let n=/^"([^"]*)"/.exec(t),S=((n===null?t.split(/\s+/)[0]??``:n[1]).replace(/^%[^%\s]*%/,``).split(/[/\\]/).pop()??``).replace(/\.exe$/i,``);return S===``?null:S}function basenameOf(t){let n=unquote(t).split(/[/\\]/);return n[n.length-1]??``}function unquote(t){let n=t[0];return(n===`"`||n===`'`)&&t.length>1&&t[t.length-1]===n?t.slice(1,-1):t}function assertLauncherMatchesInterpreter(t,n,S,C){let N=readLauncherInterpreters(t,n,S);if(N.length===0||N.includes(C))return;let F=C===`gjs`?`node`:`gjs`;if(N.includes(F))throw Error(`gjsify ship: the launcher ${launcherPath(n,S)} execs \`${F}\`, but this package would declare a dependency on \`${C}\`.\n An installed package that depends on one interpreter and runs another installs cleanly and fails
|
|
1126
1126
|
at first launch, on the user's machine.
|
|
1127
1127
|
Either set \`gjsify.ship.app.${n.os}\` to "${F}" in the project this was staged from — it overrides
|
|
1128
1128
|
\`gjsify.app\` for that target alone — or fix the launcher: if it comes from \`gjsify.ship.extraFiles\`,
|
|
1129
|
-
that override is what decides which interpreter runs and it must match the declaration.`)}function linuxInstallDependent(t){let n=[],S={hasCompiledSchemas:t.some(t=>t.path===
|
|
1130
|
-
`)[0]??``).trim().split(/\s+/)[0]??``;return n.startsWith(`/`)?n:null}function isArchIndependent(t){return!t.some(t=>isNativeBinary(t.data))}function readBinaryArch(t){if(t.byteLength<20)return null;let n=(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;if(n===2135247942){let n=t[5]===1?t[18]|t[19]<<8:t[18]<<8|t[19];return
|
|
1131
|
-
A package labelled ${n} installs on ${n} and then fails to load. Build the payload for ${n}\n (its own prebuild), or assemble the stage without \`--arch\` and label the payload you actually have.`)}}function classifyBinary(t){if(t.byteLength<4)return null;switch((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0){case 2135247942:return`elf`;case 4277009102:case 4277009103:case 3472551422:case 3489328638:case 3405691582:return`macho`;default:return t[0]===77&&t[1]===90?`pe`:null}}function isNativeBinary(t){return classifyBinary(t)!==null}var
|
|
1129
|
+
that override is what decides which interpreter runs and it must match the declaration.`)}function linuxInstallDependent(t){let n=[],S={hasCompiledSchemas:t.some(t=>t.path===jB)};for(let C of t){if(!isUnder(C.path,`share`)||RB.some(t=>C.path===t||isUnder(C.path,t)))continue;let t=LB.find(([t])=>isUnder(C.path,t));if(t===void 0){n.push({path:C.path,verdict:`unknown`,why:`nothing here classifies this directory — it may need an install step no non-Linux layout runs, or it may be inert; say which before shipping it`});continue}let[N,F]=t[1](S);n.push({path:C.path,verdict:N,why:F})}let C={aborts:0,unknown:1,inert:2};return n.sort((t,n)=>C[t.verdict]-C[n.verdict]||(t.path<n.path?-1:1))}function readShebangInterpreters(t){let n=new Set;for(let S of t){if(!(S.mode&73))continue;let t=readShebang(S.data);t!==null&&n.add(t)}return[...n].sort()}function readShebang(t){if(t[0]!==35||t[1]!==33)return null;let n=(new TextDecoder().decode(t.subarray(2,Math.min(t.byteLength,256))).split(`
|
|
1130
|
+
`)[0]??``).trim().split(/\s+/)[0]??``;return n.startsWith(`/`)?n:null}function isArchIndependent(t){return!t.some(t=>isNativeBinary(t.data))}function readBinaryArch(t){if(t.byteLength<20)return null;let n=(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;if(n===2135247942){let n=t[5]===1?t[18]|t[19]<<8:t[18]<<8|t[19];return zB[n]??null}if(n===4277009102||n===4277009103)return BB[(t[4]<<24|t[5]<<16|t[6]<<8|t[7])>>>0]??null;if(n===3472551422||n===3489328638)return BB[(t[7]<<24|t[6]<<16|t[5]<<8|t[4])>>>0]??null;if(t[0]===77&&t[1]===90&&t.byteLength>=64){let n=(t[60]|t[61]<<8|t[62]<<16|t[63]<<24)>>>0;return n+6>t.byteLength||(t[n]|t[n+1]<<8|t[n+2]<<16)>>>0!=17744||t[n+3]!==0?null:VB[t[n+4]|t[n+5]<<8]??null}return null}function assertPayloadMatchesArch(t,n){for(let S of t){let t=readBinaryArch(S.data);if(!(t===null||t===n))throw Error(`gjsify ship: the payload is ${t}, but the package would be labelled ${n} — ${S.path} is built for ${t}.\n \`--arch\` names the architecture the PAYLOAD was built for; it does not cross-compile anything.
|
|
1131
|
+
A package labelled ${n} installs on ${n} and then fails to load. Build the payload for ${n}\n (its own prebuild), or assemble the stage without \`--arch\` and label the payload you actually have.`)}}function classifyBinary(t){if(t.byteLength<4)return null;switch((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0){case 2135247942:return`elf`;case 4277009102:case 4277009103:case 3472551422:case 3489328638:case 3405691582:return`macho`;default:return t[0]===77&&t[1]===90?`pe`:null}}function isNativeBinary(t){return classifyBinary(t)!==null}var NB,PB,FB,IB,LB,RB,zB,BB,VB,HB=__esmMin(()=>{Md(),DB(),MB(),Vz(),NB=new Set([`rem`,`set`,`setlocal`,`endlocal`,`echo`,`goto`,`exit`,`title`,`pause`,`shift`,`cd`,`chdir`,`pushd`,`popd`,`color`,`cls`,`verify`,`prompt`]),PB=new Set([`exist`,`defined`,`errorlevel`]),FB=new Set([`equ`,`neq`,`lss`,`leq`,`gtr`,`geq`]),IB=32,LB=[[Bz.schemas,({hasCompiledSchemas:t})=>t?[`inert`,"the schema SOURCE; `gschemas.compiled` is staged beside it and that is what GSettings reads, so this file is carried and never opened"]:[`aborts`,"needs `glib-compile-schemas`, and the launcher points XDG_DATA_DIRS here — GSettings ABORTS on a schema directory with no `gschemas.compiled`"]],[Bz.mime,()=>[`inert`,"needs `update-mime-database`; detection runs off the compiled cache"]],[Bz.icons,()=>[`inert`,"needs `gtk-update-icon-cache`; neither OS reads the hicolor theme"]],[Bz.applications,()=>[`inert`,`a freedesktop desktop entry; neither OS reads one`]],[Bz.metainfo,()=>[`inert`,`an AppStream component; neither OS reads one`]]],RB=[Bz.locale,Bz.fonts,jB],zB={3:`ia32`,21:`ppc64`,22:`s390x`,40:`arm`,62:`x64`,183:`arm64`,243:`riscv64`},BB={7:`ia32`,12:`arm`,16777223:`x64`,16777228:`arm64`},VB={332:`ia32`,34404:`x64`,43620:`arm64`}});async function buildDeb(t){let{payload:n,mtime:S}=t,C=t.prefix.replace(/^\/+/,``),N=n.map(t=>({...t,tarPath:`./${un.join(C,t.path)}`})),F=ancestorDirectories(N.map(t=>t.tarPath)),I=await gzipDeterministic(createTarball([...F.map(t=>({name:t,mode:493,mtime:S,directory:!0})),...N.map(t=>({name:t.tarPath,body:t.data,mode:t.mode,mtime:S}))])),H=renderControl(t,N.reduce((t,n)=>t+Math.ceil(n.data.byteLength/1024),0)+F.length),W=N.map(t=>`${createHash(`md5`).update(t.data).digest(`hex`)} ${t.tarPath.slice(2)}\n`).join(``),q=[{name:`./`,mode:493,mtime:S,directory:!0},{name:`./control`,body:H,mode:420,mtime:S},{name:`./md5sums`,body:W,mode:420,mtime:S}],Y=renderDebScripts(readPayloadFacts(n),t.prefix);for(let[t,n]of Object.entries(Y))q.push({name:`./${t}`,body:n,mode:493,mtime:S});let X=await gzipDeterministic(createTarball(q));return createArArchive([{name:`debian-binary`,data:new TextEncoder().encode(`2.0
|
|
1132
1132
|
`),mtime:S},{name:`control.tar.gz`,data:X,mtime:S},{name:`data.tar.gz`,data:I,mtime:S}])}function singleLine(t){return t.replace(/[\r\n]+/g,` `).trim()}function ancestorDirectories(t){let n=new Set([`./`]);for(let S of t){let t=S.replace(/^\.\//,``).split(`/`);t.pop();let C=`.`;for(let S of t)C=`${C}/${S}`,n.add(`${C}/`)}return[...n].sort()}function renderControl(t,n){let{settings:S}=t,C=[[`Package`,S.binaryName],[`Version`,`${S.version}-${S.release}`],[`Architecture`,t.archLabel],[`Maintainer`,S.maintainer],[`Installed-Size`,String(n)]];t.depends.length>0&&C.push([`Depends`,t.depends.map(formatDebDepend).join(`, `)]),t.recommends!==void 0&&t.recommends.length>0&&C.push([`Recommends`,t.recommends.map(formatDebDepend).join(`, `)]),C.push([`Section`,S.section],[`Priority`,`optional`]),S.homepage&&C.push([`Homepage`,S.homepage]);let N=C.map(([t,n])=>`${t}: ${singleLine(n)}`);return N.push(`Description: ${singleLine(S.summary)}`),S.description.filter(t=>t!==S.summary).forEach((t,n)=>{n>0&&N.push(` .`),N.push(` ${t}`)}),`${N.join(`
|
|
1133
|
-
`)}\n`}var
|
|
1133
|
+
`)}\n`}var UB=__esmMin(()=>{Kc(),jn(),RI(),kz(),Rz(),zz(),Hz(),HB()});function xmlEscape(t){return t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var WB=__esmMin(()=>{});function validateMimeTypes(t){let n=new Set;for(let S of t){if(!GB.test(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` has an invalid type "${S.type}". Expected \`<media>/<subtype>\`, e.g. \`application/x-bauplan\` — update-mime-database ignores a malformed name, so the type would install and never resolve.`);if(n.has(S.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` defines ${S.type} twice. Which comment and glob set win would depend on document order.`);if(n.add(S.type),S.comment.trim()===``)throw Error(`gjsify ship: ${S.type} has an empty \`comment\`. A file manager then shows the user the raw type string instead of a name.`);for(let t of S.globs??[])if(!t.includes(`*`)&&!t.includes(`?`)&&!t.includes(`[`))throw Error(`gjsify ship: ${S.type} has the glob "${t}", which matches only a file named exactly that. A suffix pattern is written \`*.${t.replace(/^\.+/,``)}\`.`);if((S.globs??[]).length===0&&S.subClassOf===void 0)throw Error(`gjsify ship: ${S.type} declares neither \`globs\` nor \`subClassOf\`, so nothing can ever match it. The type would be registered and then never assigned to a file.`)}}function renderMimePackage(t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1134
1134
|
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
|
1135
1135
|
${t.map(t=>{let n=[` <mime-type type="${xmlEscape(t.type)}">`,` <comment>${xmlEscape(t.comment)}</comment>`];t.subClassOf!==void 0&&n.push(` <sub-class-of type="${xmlEscape(t.subClassOf)}"/>`);for(let S of t.globs??[])n.push(` <glob pattern="${xmlEscape(S)}"/>`);return t.genericIcon!==void 0&&n.push(` <generic-icon name="${xmlEscape(t.genericIcon)}"/>`),n.push(` </mime-type>`),n.join(`
|
|
1136
1136
|
`)}).join(`
|
|
1137
1137
|
`)}
|
|
1138
1138
|
</mime-info>
|
|
1139
|
-
`}var WB,GB=__esmMin(()=>{UB(),WB=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/});function normaliseVersion(t){let n=[],S=t.trim();S.startsWith(`v`)&&(S=S.slice(1));let C=S.indexOf(`+`);C!==-1&&(n.push(`gjsify ship: dropped the build metadata "${S.slice(C)}" from version ${t} — neither dpkg nor rpm has a field for it. Set \`gjsify.ship.version\` to pin an exact package version.`),S=S.slice(0,C));let N=S.indexOf(`-`);if(N!==-1){let t=S.slice(N+1).replace(/-/g,`.`);S=`${S.slice(0,N)}~${t}`}if(!KB.test(S))throw Error(`gjsify ship: "${t}" is not a usable package version (normalised to "${S}"). It must start with a digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.version\` in package.json to override it.`);return{version:S,warnings:n}}function assertRelease(t){if(!qB.test(t))throw Error(`gjsify ship: "${t}" is not a usable package release. It must start with a letter or digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.release\` in package.json.`);return t}var KB,qB,JB=__esmMin(()=>{KB=/^\d[A-Za-z0-9.+~]*$/,qB=/^[A-Za-z0-9][A-Za-z0-9.+~]*$/});function resolveShipApp(t){let n=t.perTarget??{};for(let t of Object.keys(n))if(!Object.hasOwn(YB,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(YB).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. A runtime under a key nothing reads leaves that target on \`gjsify.app\` with nothing to say so.`);let S=n[t.layoutOs],C=S!==void 0,N=C?`gjsify.ship.app.${t.layoutOs}`:`gjsify.app`,F=C?S:t.project;if(F!==void 0&&F!==`gjs`&&F!==`node`)throw Error(`gjsify ship: \`${N}\` is "${F}", and only \`gjs\` and \`node\` can be packaged. A browser bundle has no process to launch, and a NativeScript app ships as an APK/IPA through a different pipeline. ADR 0024 § 4 has the runtime-per-OS table.`);return{app:F===`node`?`node`:`gjs`,key:N,overridden:C}}function resolveShipKind(t,n){return t.kind??n.kind??`app`}function resolveShipSettings(t){let n=[],{pkg:S,ship:C,flatpak:N,discovered:F}=t,I={...N,...definedOnly(C)},H=C.mimeTypes??[];if(H.length>0){validateMimeTypes(H);let t=new Set([...I.provides?.mimetypes??[],...H.map(t=>t.type)]);I.provides={...I.provides,mimetypes:[...t]}}let W=C.binaryName??deriveBinaryName(S.name),q=C.appId??N.appId??reverseDnsOrThrow(S.name,W),Y=I.name??titleCase(W),X=resolveShipKind(C,N),Z=t.app,te=C.version??S.version;if(!te)throw Error("gjsify ship: no version — set `version` in package.json or `gjsify.ship.version`.");let ne=normaliseVersion(te);n.push(...ne.warnings);let re=I.license?.project??S.license;if(!re)throw Error('gjsify ship: no licence — set `license` in package.json (an SPDX id, e.g. "MIT") or `gjsify.ship.license.project`. Both deb and rpm carry it as a required field.');I.license={...I.license,project:re};let ie=C.maintainer??formatAuthor(S.author)??formatDeveloper(I);if(!ie)throw Error('gjsify ship: no maintainer — set `author` in package.json ("Name <you@example.com>"), `gjsify.ship.maintainer`, or `gjsify.ship.developer`. dpkg refuses a package without one.');let ae=I.summary??S.description??Y,oe=descriptionParagraphs(I.description)??[ae],Q=sectionsFor(I.categories);X===`app`&&F.iconFiles.length===0&&n.push("gjsify ship: no icon found — the installed app will show a placeholder in menus and app stores on Linux, and the darwin and windows layouts refuse to stage without one. Point `gjsify.ship.icon` at an SVG (or a directory of sized PNGs).");let se=resolveShipFlatpakSettings({ship:C,flatpak:N,kind:X});return n.push(...se.warnings),{settings:{projectDir:t.projectDir,appId:q,name:Y,binaryName:W,version:ne.version,release:assertRelease(C.release??`1`),maintainer:ie,summary:ae,description:oe,license:re,licenseFile:F.licenseFile,changelogFile:F.changelogFile,homepage:I.homepageUrl??S.homepage,section:C.section??Q.section,group:C.group??Q.group,kind:X,mimeTypes:H,extraDepends:{deb:C.depends?.deb??[],rpm:C.depends?.rpm??[]},typelibPackages:C.typelibPackages??{},bundlePath:F.bundlePath,bundleDir:F.bundleDir,iconFiles:F.iconFiles,schemaFiles:F.schemaFiles,typelibFiles:F.typelibFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],outDir:t.cli.outDir??C.outDir??`ship`,arch:t.cli.arch??process.arch,app:Z,layoutOs:t.cli.layoutOs,minGjsVersion:C.minGjsVersion??`1.86`,minNodeVersion:C.minNodeVersion??`24`,flatpak:se.settings},metadata:I,warnings:n}}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(YB,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(YB).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. An entry under a key nothing reads leaves that target on \`gjsify.main\` with nothing to say so.`);let C=typeof n==`string`?n:void 0,N=t.pkg.gjsify?.main??t.pkg.main,entryFor=t=>S[t]??C??N,F=S[t.layoutOs],I=entryFor(t.layoutOs),H=F===void 0?C===void 0?t.pkg.gjsify?.main===void 0?`main`:`gjsify.main`:`gjsify.ship.bundle`:`gjsify.ship.bundle.${t.layoutOs}`,W=[...new Set(Object.keys(YB).filter(n=>n!==t.layoutOs).map(entryFor).filter(t=>t!==void 0&&t!==I))];return{declared:I,key:H,overridden:F!==void 0,foreign:W}}function deriveBinaryName(t){if(!t)throw Error("gjsify ship: no package name — set `name` in package.json or `gjsify.ship.binaryName`.");let n=(t.includes(`/`)?t.split(`/`).pop():t).toLowerCase().replace(/[^a-z\d+.-]+/g,`-`).replace(/^-+|-+$/g,``);if(!/^[a-z\d][a-z\d+.-]+$/.test(n))throw Error(`gjsify ship: cannot derive a package name from "${t}" (got "${n}"). Set \`gjsify.ship.binaryName\` to something matching \`[a-z0-9][a-z0-9+.-]+\`.`);return n}function reverseDnsOrThrow(t,n){if(t&&/^[A-Za-z][\w-]*(\.[A-Za-z][\w-]*){2,}$/.test(t))return t;throw Error(`gjsify ship: no application id. Set \`gjsify.ship.appId\` (or \`gjsify.flatpak.appId\`) to a reverse-DNS id such as "io.github.you.${titleCase(n).replace(/\s+/g,``)}". It names the desktop entry, the AppStream component and the installed icon, so it cannot be guessed.`)}function definedOnly(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>t!==void 0))}function titleCase(t){return t.split(/[-_.]+/).filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(` `)}function sectionsFor(t){for(let[n,S]of XB)if(t?.includes(n))return S;return{section:`misc`,group:`Applications/System`}}function formatAuthor(t){if(typeof t==`string`)return t.replace(/\s*\([^)]*\)\s*$/,``).trim()||void 0;if(t?.name)return t.email?`${t.name} <${t.email}>`:t.name}function formatDeveloper(t){let n=t.developer;if(n?.name)return n.email?`${n.name} <${n.email}>`:n.name}function descriptionParagraphs(t){if(t===void 0)return;if(typeof t==`string`){let n=t.trim().split(/\n\n+/).map(t=>t.trim().replace(/\s+/g,` `)).filter(t=>t.length>0);return n.length>0?n:void 0}let n=[];for(let S of t)if(typeof S==`string`){let t=S.trim().replace(/\s+/g,` `);t&&n.push(t)}else if(`p`in S)n.push(S.p.trim().replace(/\s+/g,` `));else for(let t of S.ul)n.push(`* ${(typeof t==`string`?t:t.item).trim().replace(/\s+/g,` `)}`);return n.length>0?n:void 0}var YB,XB,ZB,QB,$B=__esmMin(()=>{GB(),jn(),Lz(),WR(),JB(),YB={linux:!0,darwin:!0,win32:!0},XB=[[`Development`,{section:`devel`,group:`Development/Tools`}],[`Education`,{section:`education`,group:`Applications/Education`}],[`Game`,{section:`games`,group:`Amusements/Games`}],[`Graphics`,{section:`graphics`,group:`Applications/Multimedia`}],[`AudioVideo`,{section:`sound`,group:`Applications/Multimedia`}],[`Network`,{section:`net`,group:`Applications/Internet`}],[`Office`,{section:`text`,group:`Applications/Productivity`}],[`Science`,{section:`science`,group:`Applications/Engineering`}],[`System`,{section:`admin`,group:`Applications/System`}],[`Utility`,{section:`utils`,group:`Applications/System`}]],ZB=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],QB=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=vn(C,`..`),F=discoverLocales(n,S.localeDir);return{bundlePath:C,bundleDir:N,bundleFiles:withoutForeignEntries(withoutLocaleTree(listFilesRecursive(N),N,n,S.localeDir),N,n,t.foreignBundles??[],C),iconFiles:discoverIcons(n,S.icon??t.flatpakIcon),schemaFiles:discoverSchemas(n,S.schemas),typelibFiles:discoverTypelibs(n,S.bundledTypelibs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=vn(t,C);if(!existsSync(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs\` names ${C}, which does not exist. A missing directory here means the package would install without the typelib it promises.`);for(let t of listFilesRecursive(n))(/\.(typelib|dylib|dll)$/i.test(t)||/\.so(\.\d+)*$/.test(t))&&S.push(xn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Sn(n,vn(S,C));if(N===``||N.startsWith(`..`)||bn(N))return t;let F=`${N.split(On).join(un.sep)}${un.sep}`;return t.filter(t=>!`${t}${un.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: \`gjsify.ship.localeDir\` names ${n}, which does not exist. Compile the catalogues first (msgfmt, or @gjsify/vite-plugin-gettext) — a missing directory here means the package would install without the translations it promises.`);let C=[],N=[];for(let t of listFilesRecursive(S)){if(t.endsWith(`.po`)||t.endsWith(`.pot`)){N.push(`${t} (a .po source; bindtextdomain reads .mo only)`);continue}if(!t.endsWith(`.mo`))continue;let n=t.split(un.sep);if(n.length!==3||n[1]!==`LC_MESSAGES`){N.push(`${t} (expected <lang>/LC_MESSAGES/<domain>.mo)`);continue}C.push({rel:n.join(`/`),abs:xn(S,t)})}if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) holds files no catalogue lookup will find:\n`+N.map(t=>` ${t}`).join(`
|
|
1139
|
+
`}var GB,KB=__esmMin(()=>{WB(),GB=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/});function normaliseVersion(t){let n=[],S=t.trim();S.startsWith(`v`)&&(S=S.slice(1));let C=S.indexOf(`+`);C!==-1&&(n.push(`gjsify ship: dropped the build metadata "${S.slice(C)}" from version ${t} — neither dpkg nor rpm has a field for it. Set \`gjsify.ship.version\` to pin an exact package version.`),S=S.slice(0,C));let N=S.indexOf(`-`);if(N!==-1){let t=S.slice(N+1).replace(/-/g,`.`);S=`${S.slice(0,N)}~${t}`}if(!qB.test(S))throw Error(`gjsify ship: "${t}" is not a usable package version (normalised to "${S}"). It must start with a digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.version\` in package.json to override it.`);return{version:S,warnings:n}}function assertRelease(t){if(!JB.test(t))throw Error(`gjsify ship: "${t}" is not a usable package release. It must start with a letter or digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.release\` in package.json.`);return t}var qB,JB,YB=__esmMin(()=>{qB=/^\d[A-Za-z0-9.+~]*$/,JB=/^[A-Za-z0-9][A-Za-z0-9.+~]*$/});function resolveShipApp(t){let n=t.perTarget??{};for(let t of Object.keys(n))if(!Object.hasOwn(XB,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(XB).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. A runtime under a key nothing reads leaves that target on \`gjsify.app\` with nothing to say so.`);let S=n[t.layoutOs],C=S!==void 0,N=C?`gjsify.ship.app.${t.layoutOs}`:`gjsify.app`,F=C?S:t.project;if(F!==void 0&&F!==`gjs`&&F!==`node`)throw Error(`gjsify ship: \`${N}\` is "${F}", and only \`gjs\` and \`node\` can be packaged. A browser bundle has no process to launch, and a NativeScript app ships as an APK/IPA through a different pipeline. ADR 0024 § 4 has the runtime-per-OS table.`);return{app:F===`node`?`node`:`gjs`,key:N,overridden:C}}function resolveShipKind(t,n){return t.kind??n.kind??`app`}function resolveShipSettings(t){let n=[],{pkg:S,ship:C,flatpak:N,discovered:F}=t,I={...N,...definedOnly(C)},H=C.mimeTypes??[];if(H.length>0){validateMimeTypes(H);let t=new Set([...I.provides?.mimetypes??[],...H.map(t=>t.type)]);I.provides={...I.provides,mimetypes:[...t]}}let W=C.binaryName??deriveBinaryName(S.name),q=C.appId??N.appId??reverseDnsOrThrow(S.name,W),Y=I.name??titleCase(W),X=resolveShipKind(C,N),Z=t.app,te=C.version??S.version;if(!te)throw Error("gjsify ship: no version — set `version` in package.json or `gjsify.ship.version`.");let ne=normaliseVersion(te);n.push(...ne.warnings);let re=I.license?.project??S.license;if(!re)throw Error('gjsify ship: no licence — set `license` in package.json (an SPDX id, e.g. "MIT") or `gjsify.ship.license.project`. Both deb and rpm carry it as a required field.');I.license={...I.license,project:re};let ie=C.maintainer??formatAuthor(S.author)??formatDeveloper(I);if(!ie)throw Error('gjsify ship: no maintainer — set `author` in package.json ("Name <you@example.com>"), `gjsify.ship.maintainer`, or `gjsify.ship.developer`. dpkg refuses a package without one.');let ae=I.summary??S.description??Y,oe=descriptionParagraphs(I.description)??[ae],Q=sectionsFor(I.categories);X===`app`&&F.iconFiles.length===0&&n.push("gjsify ship: no icon found — the installed app will show a placeholder in menus and app stores on Linux, and the darwin and windows layouts refuse to stage without one. Point `gjsify.ship.icon` at an SVG (or a directory of sized PNGs).");let se=resolveShipFlatpakSettings({ship:C,flatpak:N,kind:X});return n.push(...se.warnings),{settings:{projectDir:t.projectDir,appId:q,name:Y,binaryName:W,version:ne.version,release:assertRelease(C.release??`1`),maintainer:ie,summary:ae,description:oe,license:re,licenseFile:F.licenseFile,changelogFile:F.changelogFile,homepage:I.homepageUrl??S.homepage,section:C.section??Q.section,group:C.group??Q.group,kind:X,mimeTypes:H,extraDepends:{deb:C.depends?.deb??[],rpm:C.depends?.rpm??[]},typelibPackages:C.typelibPackages??{},bundlePath:F.bundlePath,bundleDir:F.bundleDir,iconFiles:F.iconFiles,schemaFiles:F.schemaFiles,typelibFiles:F.typelibFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],outDir:t.cli.outDir??C.outDir??`ship`,arch:t.cli.arch??process.arch,app:Z,layoutOs:t.cli.layoutOs,minGjsVersion:C.minGjsVersion??`1.86`,minNodeVersion:C.minNodeVersion??`24`,flatpak:se.settings},metadata:I,warnings:n}}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(XB,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(XB).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. An entry under a key nothing reads leaves that target on \`gjsify.main\` with nothing to say so.`);let C=typeof n==`string`?n:void 0,N=t.pkg.gjsify?.main??t.pkg.main,entryFor=t=>S[t]??C??N,F=S[t.layoutOs],I=entryFor(t.layoutOs),H=F===void 0?C===void 0?t.pkg.gjsify?.main===void 0?`main`:`gjsify.main`:`gjsify.ship.bundle`:`gjsify.ship.bundle.${t.layoutOs}`,W=[...new Set(Object.keys(XB).filter(n=>n!==t.layoutOs).map(entryFor).filter(t=>t!==void 0&&t!==I))];return{declared:I,key:H,overridden:F!==void 0,foreign:W}}function deriveBinaryName(t){if(!t)throw Error("gjsify ship: no package name — set `name` in package.json or `gjsify.ship.binaryName`.");let n=(t.includes(`/`)?t.split(`/`).pop():t).toLowerCase().replace(/[^a-z\d+.-]+/g,`-`).replace(/^-+|-+$/g,``);if(!/^[a-z\d][a-z\d+.-]+$/.test(n))throw Error(`gjsify ship: cannot derive a package name from "${t}" (got "${n}"). Set \`gjsify.ship.binaryName\` to something matching \`[a-z0-9][a-z0-9+.-]+\`.`);return n}function reverseDnsOrThrow(t,n){if(t&&/^[A-Za-z][\w-]*(\.[A-Za-z][\w-]*){2,}$/.test(t))return t;throw Error(`gjsify ship: no application id. Set \`gjsify.ship.appId\` (or \`gjsify.flatpak.appId\`) to a reverse-DNS id such as "io.github.you.${titleCase(n).replace(/\s+/g,``)}". It names the desktop entry, the AppStream component and the installed icon, so it cannot be guessed.`)}function definedOnly(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>t!==void 0))}function titleCase(t){return t.split(/[-_.]+/).filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(` `)}function sectionsFor(t){for(let[n,S]of ZB)if(t?.includes(n))return S;return{section:`misc`,group:`Applications/System`}}function formatAuthor(t){if(typeof t==`string`)return t.replace(/\s*\([^)]*\)\s*$/,``).trim()||void 0;if(t?.name)return t.email?`${t.name} <${t.email}>`:t.name}function formatDeveloper(t){let n=t.developer;if(n?.name)return n.email?`${n.name} <${n.email}>`:n.name}function descriptionParagraphs(t){if(t===void 0)return;if(typeof t==`string`){let n=t.trim().split(/\n\n+/).map(t=>t.trim().replace(/\s+/g,` `)).filter(t=>t.length>0);return n.length>0?n:void 0}let n=[];for(let S of t)if(typeof S==`string`){let t=S.trim().replace(/\s+/g,` `);t&&n.push(t)}else if(`p`in S)n.push(S.p.trim().replace(/\s+/g,` `));else for(let t of S.ul)n.push(`* ${(typeof t==`string`?t:t.item).trim().replace(/\s+/g,` `)}`);return n.length>0?n:void 0}var XB,ZB,QB,$B,eV=__esmMin(()=>{KB(),jn(),Rz(),GR(),YB(),XB={linux:!0,darwin:!0,win32:!0},ZB=[[`Development`,{section:`devel`,group:`Development/Tools`}],[`Education`,{section:`education`,group:`Applications/Education`}],[`Game`,{section:`games`,group:`Amusements/Games`}],[`Graphics`,{section:`graphics`,group:`Applications/Multimedia`}],[`AudioVideo`,{section:`sound`,group:`Applications/Multimedia`}],[`Network`,{section:`net`,group:`Applications/Internet`}],[`Office`,{section:`text`,group:`Applications/Productivity`}],[`Science`,{section:`science`,group:`Applications/Engineering`}],[`System`,{section:`admin`,group:`Applications/System`}],[`Utility`,{section:`utils`,group:`Applications/System`}]],QB=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],$B=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=vn(C,`..`),F=discoverLocales(n,S.localeDir);return{bundlePath:C,bundleDir:N,bundleFiles:withoutForeignEntries(withoutLocaleTree(listFilesRecursive(N),N,n,S.localeDir),N,n,t.foreignBundles??[],C),iconFiles:discoverIcons(n,S.icon??t.flatpakIcon),schemaFiles:discoverSchemas(n,S.schemas),typelibFiles:discoverTypelibs(n,S.bundledTypelibs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=vn(t,C);if(!existsSync(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs\` names ${C}, which does not exist. A missing directory here means the package would install without the typelib it promises.`);for(let t of listFilesRecursive(n))(/\.(typelib|dylib|dll)$/i.test(t)||/\.so(\.\d+)*$/.test(t))&&S.push(xn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Sn(n,vn(S,C));if(N===``||N.startsWith(`..`)||bn(N))return t;let F=`${N.split(On).join(un.sep)}${un.sep}`;return t.filter(t=>!`${t}${un.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: \`gjsify.ship.localeDir\` names ${n}, which does not exist. Compile the catalogues first (msgfmt, or @gjsify/vite-plugin-gettext) — a missing directory here means the package would install without the translations it promises.`);let C=[],N=[];for(let t of listFilesRecursive(S)){if(t.endsWith(`.po`)||t.endsWith(`.pot`)){N.push(`${t} (a .po source; bindtextdomain reads .mo only)`);continue}if(!t.endsWith(`.mo`))continue;let n=t.split(un.sep);if(n.length!==3||n[1]!==`LC_MESSAGES`){N.push(`${t} (expected <lang>/LC_MESSAGES/<domain>.mo)`);continue}C.push({rel:n.join(`/`),abs:xn(S,t)})}if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) holds files no catalogue lookup will find:\n`+N.map(t=>` ${t}`).join(`
|
|
1140
1140
|
`)+`
|
|
1141
|
-
A misplaced catalogue installs and then shows nothing, which reads exactly like having no translation at all. Lay them out as <lang>/LC_MESSAGES/<domain>.mo.`);if(C.length===0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) contains no \`.mo\` catalogue. Declaring a locale directory that ships nothing is a promise the package does not keep.`);return C}function withoutForeignEntries(t,n,S,C,N){if(C.length===0)return t;let F=new Set;for(let t of C){let C=bn(t)?t:vn(S,t);if(C===N)continue;let I=Sn(n,C);I===``||I.startsWith(`..`)||bn(I)||F.add(I.split(On).join(un.sep))}return t.filter(t=>!F.has(t))}function resolveBundle(t){let n=t.declaredBundle;if(n===void 0)throw Error("gjsify ship: no bundle to ship. Set `gjsify.main` (or `main`) in package.json to the built bundle, or `gjsify.ship.bundle` to override it.");let S=bn(n)?n:vn(t.projectDir,n);if(!existsSync(S))throw Error(`gjsify ship: the bundle ${n} does not exist. Build it first (\`gjsify run build\`), or drop \`--skip-build\`.`);return S}function discoverIcons(t,n){if(n!==void 0){let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured icon path ${n} does not exist.`);return statSync(S).isDirectory()?listIcons(S):[S]}for(let n of[`data/icons`,`data/icons/hicolor`]){let S=xn(t,n);if(existsSync(S)&&statSync(S).isDirectory()){let t=listIcons(S);if(t.length>0)return t}}return[]}function listIcons(t){return listFilesRecursive(t).filter(t=>
|
|
1142
|
-
`)){let n=/^[*-][ \t]+(.*\S)\s*$/.exec(t);n!==null&&H.push(n[1].replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s+/g,` `).trim())}return H}function wrapEntry(t){let n=[],S=` *`;for(let C of t.split(/\s+/))C!==``&&(S.length+1+C.length>
|
|
1143
|
-
`)}var
|
|
1141
|
+
A misplaced catalogue installs and then shows nothing, which reads exactly like having no translation at all. Lay them out as <lang>/LC_MESSAGES/<domain>.mo.`);if(C.length===0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) contains no \`.mo\` catalogue. Declaring a locale directory that ships nothing is a promise the package does not keep.`);return C}function withoutForeignEntries(t,n,S,C,N){if(C.length===0)return t;let F=new Set;for(let t of C){let C=bn(t)?t:vn(S,t);if(C===N)continue;let I=Sn(n,C);I===``||I.startsWith(`..`)||bn(I)||F.add(I.split(On).join(un.sep))}return t.filter(t=>!F.has(t))}function resolveBundle(t){let n=t.declaredBundle;if(n===void 0)throw Error("gjsify ship: no bundle to ship. Set `gjsify.main` (or `main`) in package.json to the built bundle, or `gjsify.ship.bundle` to override it.");let S=bn(n)?n:vn(t.projectDir,n);if(!existsSync(S))throw Error(`gjsify ship: the bundle ${n} does not exist. Build it first (\`gjsify run build\`), or drop \`--skip-build\`.`);return S}function discoverIcons(t,n){if(n!==void 0){let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured icon path ${n} does not exist.`);return statSync(S).isDirectory()?listIcons(S):[S]}for(let n of[`data/icons`,`data/icons/hicolor`]){let S=xn(t,n);if(existsSync(S)&&statSync(S).isDirectory()){let t=listIcons(S);if(t.length>0)return t}}return[]}function listIcons(t){return listFilesRecursive(t).filter(t=>tV.some(n=>t.toLowerCase().endsWith(n))).map(n=>xn(t,n.split(`/`).join(On))).sort()}function discoverFonts(t,n){let S=n??`data/fonts`,C=n===void 0?xn(t,`data`,`fonts`):vn(t,n);if(!existsSync(C)){if(n===void 0)return[];throw Error(`gjsify ship: the configured font path ${n} does not exist.`)}if(!statSync(C).isDirectory()){if(assertNotWebFont(C,S),!nV.some(t=>C.toLowerCase().endsWith(t)))throw Error(`gjsify ship: \`gjsify.ship.fonts\` names ${n}, which is not a font face fontconfig will open (${nV.join(`, `)}). A file it cannot read installs and is never found, and Pango substitutes a fallback family rather than reporting anything.`);return[C]}let N=[];for(let t of listFilesRecursive(C))assertNotWebFont(t,S),nV.some(n=>t.toLowerCase().endsWith(n))&&N.push(xn(C,t.split(`/`).join(On)));if(N.length===0&&n!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${n}) holds no font face (${nV.join(`, `)}). Declaring fonts that ship nothing is a promise the package does not keep — and its symptom is a substituted family, not an error.`);return N.sort()}function assertNotWebFont(t,n){let S=t.toLowerCase(),C=rV.find(t=>S.endsWith(t));if(C!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${n}) carries ${t}, and \`${C}\` is a web-font wrapper whose support is a FreeType BUILD option — brotli for woff2, zlib for woff. Whether it opens is therefore a property of the FreeType the SHIPPED artifact loads (inside \`@gjsify/gtk-runtime-<target>\` for a \`.app\` or a Windows program directory), not of the machine that packaged it. Ship the desktop face instead (${nV.join(`, `)}); a font that fails to open is not an error, it is Pango quietly substituting a different typeface.`)}function discoverSchemas(t,n){let S=n===void 0?[xn(t,`data`)]:[vn(t,n)];for(let t of S){if(!existsSync(t)){if(n!==void 0)throw Error(`gjsify ship: the configured schema path ${n} does not exist.`);continue}if(!statSync(t).isDirectory())return[t];let S=listFilesRecursive(t).filter(t=>t.endsWith(`.gschema.xml`)).map(n=>xn(t,n.split(`/`).join(On))).sort();if(S.length>0)return S}return[]}function discoverLicense(t,n){if(n!==void 0){let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured licence file ${n} does not exist.`);return S}for(let n of licenseSearchDirs(t))for(let t of QB){let S=xn(n,t);if(existsSync(S))return S}}function discoverChangelog(t,n){if(n!==void 0){let S=vn(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured changelog file ${n} does not exist.`);return S}for(let n of licenseSearchDirs(t))for(let t of $B){let S=xn(n,t);if(existsSync(S))return S}}function licenseSearchDirs(t){let n=[];for(let S=t;;){if(n.push(S),isProjectRoot(S))return n;let C=wn(S);if(C===S)return[t];S=C}}function isProjectRoot(t){if(existsSync(xn(t,`.git`)))return!0;let n=xn(t,`package.json`);if(!existsSync(n))return!1;try{return JSON.parse(readFileSync(n,`utf-8`)).workspaces!==void 0}catch{return!1}}function listFilesRecursive(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let N=xn(S,C.name);if(C.isDirectory())walk(N);else if(C.isSymbolicLink())throw Error(`gjsify ship: ${N} is a symlink. The payload has to be self-contained — replace it with the file it points at, or exclude it from the bundle directory.`);else C.isFile()&&n.push(un.join(...Sn(t,N).split(On)))}};return walk(t),n.sort()}var tV,nV,rV,iV=__esmMin(()=>{Md(),jn(),eV(),tV=[`.svg`,`.png`],nV=[`.ttf`,`.otf`,`.ttc`,`.otc`],rV=[`.woff`,`.woff2`,`.eot`]});function isNodeRuntimeTarget(t){return aV.includes(t)}function nodeRuntimePackageName(t){return`@gjsify/node-runtime-${t}`}function nodeRuntimeBinaryName(t){return t.startsWith(`win32-`)?`node.exe`:`node`}function resolveNodeRuntime(t,n={}){let S=n.env??process.env,C=nodeRuntimeBinaryName(t),N=S.GJSIFY_NODE_RUNTIME;if(N){let t=complete(`GJSIFY_NODE_RUNTIME`,N,C);if(t)return t}let F=nodeRuntimePackageName(t),I=resolveInstalledPackage(F,{cwd:n.cwd,bundleUrl:import.meta.url});return I===null?null:complete(F,xn(wn(I),`bin`),C)}function complete(t,n,S){let C=xn(n,S),N=xn(n,`LICENSE`);return!existsSync(C)||!existsSync(N)?null:{source:t,binDir:n,nodePath:C,licensePath:N}}var aV,oV=__esmMin(()=>{Md(),jn(),MP(),aV=[`darwin-arm64`,`darwin-x64`,`win32-x64`]});function rfc822(t){let n=new Date(t*1e3),pad=t=>String(t).padStart(2,`0`);return`${sV[n.getUTCDay()]}, ${pad(n.getUTCDate())} ${cV[n.getUTCMonth()]} ${n.getUTCFullYear()} ${pad(n.getUTCHours())}:${pad(n.getUTCMinutes())}:${pad(n.getUTCSeconds())} +0000`}function changelogEntriesFor(t,n){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),C=RegExp(`^##+[ \\t]+\\[?${S}\\]?[^\\n]*$`,`m`).exec(n);if(C===null)return[];let N=n.slice(C.index+C[0].length),F=/^##[ \t]+\[?\d/m.exec(N),I=F===null?N:N.slice(0,F.index),H=[];for(let t of I.split(`
|
|
1142
|
+
`)){let n=/^[*-][ \t]+(.*\S)\s*$/.exec(t);n!==null&&H.push(n[1].replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s+/g,` `).trim())}return H}function wrapEntry(t){let n=[],S=` *`;for(let C of t.split(/\s+/))C!==``&&(S.length+1+C.length>lV&&S!==` *`&&S!==` `&&(n.push(S),S=` `),S+=` ${C}`);return n.push(S),n}function renderDebianChangelog(t,n,S){let C=n===void 0?[]:changelogEntriesFor(t.version,n),N=t.homepage?`Release ${t.version}. See ${t.homepage} for the upstream changes.`:`Release ${t.version}.`,F=(C.length>0?C:[N]).flatMap(wrapEntry);return[`${t.binaryName} (${t.version}-${t.release}) unstable; urgency=medium`,``,...F,``,` -- ${t.maintainer} ${rfc822(S)}`,``].join(`
|
|
1143
|
+
`)}var sV,cV,lV,uV=__esmMin(()=>{sV=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],cV=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],lV=80});function planStage(t,n){let S=[],C=`lib/${t.binaryName}`;S.push({path:`bin/${t.binaryName}`,mode:493,source:{kind:`text`,text:n.launcher}});for(let N of n.bundleFiles)S.push({path:un.join(C,N),mode:isExecutableAsset(N)?493:420,source:{kind:`file`,path:un.join(t.bundleDir,N)}});if(S.push({path:`${Bz.metainfo}/${t.appId}.metainfo.xml`,mode:420,source:{kind:`text`,text:n.metainfo}}),t.kind===`app`){if(n.desktopEntry===void 0)throw Error('gjsify ship: internal error — a desktop entry is required for `kind: "app"`.');S.push({path:`${Bz.applications}/${t.appId}.desktop`,mode:420,source:{kind:`text`,text:n.desktopEntry}});for(let n of planIcons(t))S.push(n)}for(let n of t.schemaFiles){let C=Tn(n);if(!C.startsWith(t.appId))throw Error(`gjsify ship: the GSettings schema ${C} must be named \`${t.appId}[.…].gschema.xml\`. Every installed schema shares one system directory, so the app id is what keeps it unique.`);S.push({path:`${Bz.schemas}/${C}`,mode:420,source:{kind:`file`,path:n}})}for(let n of t.typelibFiles)S.push({path:un.join(C,`gi`,Tn(n)),mode:493,source:{kind:`file`,path:n}});t.mimeTypes.length>0&&S.push({path:`${Bz.mime}/${t.appId}.xml`,mode:420,source:{kind:`text`,text:renderMimePackage(t.mimeTypes)}});for(let n of t.localeFiles)S.push({path:un.join(Bz.locale,n.rel),mode:420,source:{kind:`file`,path:n.abs}});for(let n of planFonts(t))S.push(n);for(let[n,C]of Object.entries(t.extraFiles))S.push({path:assertInsidePrefix(n),mode:420,source:{kind:`file`,path:C}});return normalise(S)}function planFonts(t){let n=[],S=new Map;for(let C of t.fontFiles){let N=`${Bz.fonts}/${t.appId}/${Tn(C)}`,F=S.get(N);if(F!==void 0)throw Error(`gjsify ship: ${C} and ${F} both install as ${N}. Two faces cannot share one filename — one would silently not ship, and a missing face is a substituted typeface rather than an error. Rename one, or point \`gjsify.ship.fonts\` at a directory holding only the faces you mean to ship.`);S.set(N,C),n.push({path:N,mode:420,source:{kind:`file`,path:C}})}return n}async function planOverlay(t,n,S){if(S.licenseText===void 0)throw Error(`gjsify ship: no licence file found, so the ${n.id} package would ship no ${n.licenseDest(t.binaryName)}. Debian Policy § 12.5 requires it and lintian errors without it, and neither dpkg nor rpm will tell you it is missing. Add a LICENSE file to ${t.projectDir} or to the root of its repository, or point \`gjsify.ship.licenseFile\` at the one this package ships under.`);let C=n.licenseKind===`debian-copyright`?renderDebianCopyright(t,S.licenseText):S.licenseText,N=[{path:n.licenseDest(t.binaryName),mode:420,source:{kind:`text`,text:C}}];if(n.changelogDest!==void 0){let C=renderDebianChangelog(t,S.changelogText,S.mtime);N.push({path:n.changelogDest(t.binaryName),mode:420,source:{kind:`bytes`,data:await gzipDeterministic(new TextEncoder().encode(C),9)}})}return N}function assertOverlayIsLicensed(t,n,S){if(!(S.length>0))throw Error(`gjsify ship: this stage carries no ${t} licence overlay, so the package would ship no licence file for ${n} — Debian Policy § 12.5 requires one and lintian errors without it. The fix is on the assembling host, not this one: give that project a LICENSE (or set \`gjsify.ship.licenseFile\`) and re-run the \`--stage\` phase.`)}function renderDebianCopyright(t,n){let S=n.trimEnd().split(`
|
|
1144
1144
|
`).map(t=>t.trim()===``?` .`:` ${t}`).join(`
|
|
1145
1145
|
`);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(`
|
|
1146
|
-
`)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=$(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${
|
|
1147
|
-
`)}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=un.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 ${vV}/runtime-${t} (or point ${_V} 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(SV.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${zz.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=`${zz.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 ${zz.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 ${zz.schemas}/ and no ${AB} 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 ${AB}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${zz.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:bV,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:xV,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,[gV]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${hV} 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: ${hV} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${hV} 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 ${gV}=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(` `)} ${hV} ${n.join(` `)}`);let C=await spawnToCompletion(hV,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${hV} 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 \`${hV}\`. \`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: ${hV} 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(xn(t,C.split(`/`).join(On)),S,S);utimesSync(t,S,S)}var hV,gV,_V,vV,yV,bV,xV,SV,CV=__esmMin(()=>{_e(),Md(),jn(),j_(),Tz(),Lz(),EB(),jB(),Bz(),hV=`appimagetool`,gV=`APPIMAGE_EXTRACT_AND_RUN`,_V=`GJSIFY_APPIMAGE_RUNTIME_DIR`,vV=`/usr/local/share/gjsify/appimage-runtime`,yV=`AppDir`,bV=`AppRun`,xV=`.DirIcon`,SV=[`.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(TV.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] ${wV} ${n.join(` `)}`);let S=await spawnToCompletion(wV,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${wV} 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: ${wV} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return xn(t,`dmg`,`volume`)}var wV,TV,EV=__esmMin(()=>{_e(),jn(),j_(),wV=`hdiutil`,TV=/[/:]/});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};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=xn(S,`${n.appId}.json`),F=xn(S,`build`),I=xn(S,`repo`),H=xn(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 DV=__esmMin(()=>{_e(),Md(),jn(),j_(),__name$1(run$1,`run`)});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=xn(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(xn(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=xn(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,xn(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 OV=__esmMin(()=>{w_(),Md(),Dg(),jn(),AR()});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(kV,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(AV,t,`RPM`)}function flatpakArch(t,n){return lookupArch(jV,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(MV,t,`AppImage`)}function macosArch(t,n){return lookupArch(NV,t,`macOS`)}function windowsArch(t,n){return lookupArch(PV,t,`Windows`)}function windowsNameIsUnusable(t){return FV.test(t)||IV.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.
|
|
1146
|
+
`)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=$(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${Bz.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=un.normalize(t);if(un.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 dV=__esmMin(()=>{uV(),zz(),qz(),KB(),Vz(),jn()});function isGtkRuntimeTarget(t){return fV.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:`${mV}/prebuilds/${t}`,dir:xn(I,`prebuilds`,t,`gtk`)}),N.push({source:`${mV} sibling`,dir:xn(I,`..`,`gtk-runtime-${t}`,`gtk`)}));let H=gtkRuntimePackageName(t),W=resolveStagedPackage(H,n);W!==null&&N.push({source:H,dir:xn(wn(W),`gtk`)});for(let t of N){let n=xn(t.dir,C),S=xn(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=xn(S,`prebuilds`,t,pV);return existsSync(C)?{source:mV,addonPath:C}:null}function resolveNodeGiRoot(t){let n=resolveStagedPackage(mV,t);return n===null?null:wn(n)}function resolveStagedPackage(t,n){let S={bundleUrl:import.meta.url};return n.cwd!==void 0&&(S.cwd=n.cwd),n.resolve!==void 0&&(S.resolve=n.resolve),resolveInstalledPackage(t,S)}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=xn(n,`overrides`);if(existsSync(C))for(let t of listFilesRecursive(C))S.push(un.join(`overrides`,t));return S.length>1?{source:mV,root:n,files:S.sort()}:null}function appRuntimePaths(t,n,S){let C=t.dirs(n),N=un.join(C.native,`node-gi`),F=un.join(N,`prebuilds`,S);return{nodeGiRoot:N,nodeGiPackageDir:un.join(C.bundle,`node_modules`,mV),prebuildDir:F,gtkDir:un.join(F,`gtk`),addonPath:un.join(F,pV),interpreterPath:un.join(C.launcher,nodeRuntimeBinaryName(S)),interpreterLicensePath:un.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=xn(I.dir,t.split(`/`).join(On));S.push({path:un.join(n.gtkDir,t),mode:stagedMode(t,C),source:{kind:`file`,path:C}})}C.gtkRuntimeDir=n.gtkDir,N.push(`GTK closure from ${I.source}`)}else{let n=t.target.startsWith(`win32-`)?`bin`:`lib`;F.push(`no GTK closure — install \`${gtkRuntimePackageName(t.target)}\` (or point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${n}/\` and \`girepository-1.0/\`)`)}let H=resolveNodeGiPackage(discoveryOptions(t));if(H!==null){for(let t of H.files)S.push({path:un.join(n.nodeGiPackageDir,t),mode:420,source:{kind:`file`,path:xn(H.root,t.split(`/`).join(On))}});N.push(`node-gi runtime (${H.files.length} file(s)) from ${H.source}`)}else F.push(`no node-gi JavaScript — install \`${mV}\`; 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 \`${mV}\`, whose \`prebuilds/${t.target}/${pV}\` 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 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),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 fV,pV,mV,hV=__esmMin(()=>{Md(),jn(),iV(),oV(),dV(),MP(),fV=[`darwin-arm64`,`darwin-x64`,`win32-x64`],pV=`node_gi.node`,mV=`@gjsify/node-gi`});function appDirFor(t){return xn(t,`appimage`,bV)}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=wB.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(`
|
|
1147
|
+
`)}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=un.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 ${yV}/runtime-${t} (or point ${vV} 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(CV.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${Bz.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=`${Bz.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 ${Bz.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 ${Bz.schemas}/ and no ${jB} 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 ${jB}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${Bz.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:xV,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:SV,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,[_V]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${gV} 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: ${gV} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${gV} 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 ${_V}=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(` `)} ${gV} ${n.join(` `)}`);let C=await spawnToCompletion(gV,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${gV} 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 \`${gV}\`. \`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: ${gV} 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(xn(t,C.split(`/`).join(On)),S,S);utimesSync(t,S,S)}var gV,_V,vV,yV,bV,xV,SV,CV,wV=__esmMin(()=>{_e(),Md(),jn(),j_(),Ez(),Rz(),DB(),MB(),Vz(),gV=`appimagetool`,_V=`APPIMAGE_EXTRACT_AND_RUN`,vV=`GJSIFY_APPIMAGE_RUNTIME_DIR`,yV=`/usr/local/share/gjsify/appimage-runtime`,bV=`AppDir`,xV=`AppRun`,SV=`.DirIcon`,CV=[`.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(EV.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] ${TV} ${n.join(` `)}`);let S=await spawnToCompletion(TV,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${TV} 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: ${TV} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return xn(t,`dmg`,`volume`)}var TV,EV,DV=__esmMin(()=>{_e(),jn(),j_(),TV=`hdiutil`,EV=/[/:]/});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};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=xn(S,`${n.appId}.json`),F=xn(S,`build`),I=xn(S,`repo`),H=xn(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 OV=__esmMin(()=>{_e(),Md(),jn(),j_(),__name$1(run$1,`run`)});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=xn(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(xn(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=xn(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,xn(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 kV=__esmMin(()=>{w_(),Md(),Dg(),jn(),jR()});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(AV,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(jV,t,`RPM`)}function flatpakArch(t,n){return lookupArch(MV,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(NV,t,`AppImage`)}function macosArch(t,n){return lookupArch(PV,t,`macOS`)}function windowsArch(t,n){return lookupArch(FV,t,`Windows`)}function windowsNameIsUnusable(t){return IV.test(t)||LV.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.
|
|
1148
1148
|
The artifact would assemble here and be unextractable — or extract under a different name than
|
|
1149
|
-
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 VV.filter(n=>BV[n].layoutOs===t&&BV[n].host.finishOn===`any`)}function formatIdsFor(t){return VV.filter(n=>BV[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(BV,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${VV.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${VV.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>BV[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>BV[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 ${HV[t]??t} --target ${C.filter(n=>BV[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>BV[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>BV[t].layoutOs===n.os).map(t=>BV[t]),dropped:S.filter(t=>BV[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`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var kV,AV,jV,MV,NV,PV,FV,IV,LV,RV,zV,SHARE_LICENSE_DEST,WRITTEN_HERE,BV,VV,HV,UV=__esmMin(()=>{qP(),CV(),EV(),EB(),jB(),kV={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},AV={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},jV={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},MV={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},NV={x64:`x86_64`,arm64:`arm64`},PV={x64:`x64`},FV=/[<>:"/\\|?*]/,IV=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,LV=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,RV='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',zV="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}}),BV={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:LV,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:LV,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:[hV,OB],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: ${kB}`,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},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[OB],installHint:kB,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:RV,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:[OB],installHint:kB,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:RV,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:[wV],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:RV,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:[OB],installHint:kB,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:zV,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:[OB],installHint:kB,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:zV,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:[OB,`wixl`],win32:[OB,`candle.exe`,`light.exe`]},installHint:`${kB}; 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:zV,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},VV=Object.keys(BV),HV=Object.fromEntries(wB.map(t=>[CB[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(WV,`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(WV,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(WV,`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.
|
|
1149
|
+
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 HV.filter(n=>VV[n].layoutOs===t&&VV[n].host.finishOn===`any`)}function formatIdsFor(t){return HV.filter(n=>VV[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(VV,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${HV.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${HV.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>VV[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>VV[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 ${UV[t]??t} --target ${C.filter(n=>VV[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>VV[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>VV[t].layoutOs===n.os).map(t=>VV[t]),dropped:S.filter(t=>VV[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`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var AV,jV,MV,NV,PV,FV,IV,LV,RV,zV,BV,SHARE_LICENSE_DEST,WRITTEN_HERE,VV,HV,UV,WV=__esmMin(()=>{JP(),wV(),DV(),DB(),MB(),AV={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},jV={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},MV={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},NV={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},PV={x64:`x86_64`,arm64:`arm64`},FV={x64:`x64`},IV=/[<>:"/\\|?*]/,LV=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,RV=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,zV='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',BV="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}}),VV={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:RV,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:RV,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:[gV,kB],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: ${AB}`,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},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[kB],installHint:AB,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:zV,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:[kB],installHint:AB,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:zV,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:[TV],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:zV,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:[kB],installHint:AB,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:BV,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:[kB],installHint:AB,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:BV,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:[kB,`wixl`],win32:[kB,`candle.exe`,`light.exe`]},installHint:`${AB}; 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:BV,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},HV=Object.keys(VV),UV=Object.fromEntries(TB.map(t=>[wB[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(GV,`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(GV,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(GV,`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.
|
|
1150
1150
|
Dropping the suffix is not an option this command will take silently: \`1.2.0~rc.1\` and \`1.2.0\` would
|
|
1151
1151
|
become the same version, \`MajorUpgrade\` could not tell them apart, and installing one over the other
|
|
1152
1152
|
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
|
|
1153
|
-
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||
|
|
1153
|
+
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||KV.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
|
|
1154
1154
|
\`.\` 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=msiProductVersion(n.version),F=n.maintainer.replace(/\s*<[^>]*>\s*$/,``).trim()||n.maintainer,I=windowsGuiLauncherPath(n),H=new Map,claim=(t,n)=>{let S=H.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 H.set(t,n),t},W=claim(msiIdentifier(`i`,I,`.exe`),`the launcher icon`),q=[],Y=[],X=!1,Z,emitDir=(t,S)=>{for(let C of t.files){let t=claim(msiIdentifier(`c`,C.path),C.path),N=claim(msiIdentifier(`f`,C.path),C.path);Y.push(t);let F=msiComponentGuid(n,C.path),H=xmlEscape(un.basename(C.path));q.push(`${S}<Component Id="${t}" Guid="${F}">`),C.path===I?(X=!0,Z=C.source,q.push(`${S} <File Id="${N}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes">`),q.push(`${S} <Shortcut Id="${claim(`s_startmenu`,`the Start-Menu shortcut`)}" Directory="ProgramMenuFolder" Name="${xmlEscape(n.name)}" WorkingDirectory="INSTALLDIR" Description="${xmlEscape(n.summary)}" Icon="${W}" IconIndex="0" Advertise="yes" />`),q.push(`${S} </File>`)):q.push(`${S} <File Id="${N}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes" />`),q.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}`);q.push(`${S}<Directory Id="${t}" Name="${xmlEscape(n.name)}">`),emitDir(n,`${S} `),q.push(`${S}</Directory>`)}};if(emitDir(directoryTree(t.files),` `),Y.length===0)throw Error("gjsify ship: the windows payload is empty, so there is nothing for an `.msi` to install.");if(!X||Z===void 0)throw Error(`gjsify ship: the windows payload carries no "${I}" 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
|
|
1155
1155
|
cannot start. \`windows-dir\` puts the launcher there; a payload without one is a stage assembled for another layout.`);let te=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="${N}" Manufacturer="${xmlEscape(F)}" UpgradeCode="${msiUpgradeCode(n)}">`,` <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Manufacturer="${xmlEscape(F)}" 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="${W}" SourceFile="${xmlEscape(Z)}" />`,` <Property Id="ARPPRODUCTICON" Value="${W}" />`,...te,` <Directory Id="TARGETDIR" Name="SourceDir">`,` <Directory Id="ProgramFiles64Folder">`,` <Directory Id="INSTALLDIR" Name="${xmlEscape(S)}">`,...q,` </Directory>`,` </Directory>`,` <Directory Id="ProgramMenuFolder" />`,` </Directory>`,` <Feature Id="Main" Title="${xmlEscape(n.name)}" Level="1">`,...Y.map(t=>` <ComponentRef Id="${t}" />`),` </Feature>`,` </Product>`,`</Wix>`,``].join(`
|
|
1156
|
-
`)}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=xn(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=xn(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,xn(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
|
|
1157
|
-
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 rH,iH=__esmMin(()=>{nH(),rH=new Set([`system`,`gettext`])});function scanGiRequirements(t){let n=new Set,S=new Set,C=new Set,N=new Set,F=[];walkModuleAst(t,t=>{let S=importedSpecifier(t);if(S!==null){let F=parseGiSpecifier(S);F!==null&&n.add(F),t.type===`ImportDeclaration`&&S===aH&&collectNodeGiBindings(t,C,N);return}if(t.type===`VariableDeclarator`&&loadsNodeGiModule(t.init)){let n=t.id;n?.type===`Identifier`&&typeof n.name==`string`&&N.add(n.name);return}t.type===`CallExpression`&&F.push(t)});for(let t of F){let F=optionalMarkerNamespace(t);if(F!==null){S.add(F);continue}let I=requireGiNamespace(t,C,N);I!==null&&n.add(I)}return{namespaces:[...n].sort(),optional:[...S].filter(t=>n.has(t)).sort()}}function optionalMarkerNamespace(t){let n=t.callee;if(n?.type!==`MemberExpression`||n.computed!==!0)return null;let S=n.property;if(S?.type!==`CallExpression`)return null;let C=S.callee,N=C?.type===`MemberExpression`?C.object:void 0,F=C?.type===`MemberExpression`?C.property:void 0;if(N?.type!==`Identifier`||N.name!==`Symbol`||F?.type!==`Identifier`||F.name!==`for`||staticStringValue((S.arguments??[])[0])!==`gjsify.optionalGi`)return null;let I=n.object;if(I?.type!==`Identifier`||I.name!==`globalThis`)return null;let H=t.arguments??[],W=staticStringValue(H[0]);if(W===null||!oH.test(W))return null;let q=staticStringValue(H[1]);return q===null||q===``?W:`${W}-${q}`}function parseGiSpecifier(t){if(!t.startsWith(`gi://`))return null;let[n,S]=t.slice(5).split(`?`,2);if(n===void 0||!oH.test(n))return null;if(S===void 0)return n;let C=/(?:^|&)version=([^&]+)/.exec(S)?.[1];return C===void 0?n:`${n}-${C}`}function collectNodeGiBindings(t,n,S){let C=t.specifiers??[];for(let t of C){let C=t.local;if(C?.type!==`Identifier`||typeof C.name!=`string`)continue;let N=t.imported;t.type===`ImportNamespaceSpecifier`?S.add(C.name):(t.type===`ImportDefaultSpecifier`||N?.type===`Identifier`&&N.name===`requireGi`)&&n.add(C.name)}}function loadsNodeGiModule(t){if(!t||typeof t!=`object`)return!1;let n=t;return n.type===`CallExpression`?staticStringValue((n.arguments??[])[0])===aH:!1}function requireGiNamespace(t,n,S){let C=t.callee,N=!1;if(C?.type===`Identifier`)N=typeof C.name==`string`&&n.has(C.name);else if(C?.type===`MemberExpression`&&C.computed!==!0){let t=C.property;if(t?.type!==`Identifier`||t.name!==`requireGi`)return null;let n=C.object;N=loadsNodeGiModule(n)||n?.type===`Identifier`&&typeof n.name==`string`&&S.has(n.name)}if(!N)return null;let F=t.arguments??[],I=staticStringValue(F[0]);if(I===null||!oH.test(I))return null;let H=staticStringValue(F[1]);return H===null?I:`${I}-${H}`}var aH,oH,sH=__esmMin(()=>{Bj(),nH(),aH=`@gjsify/node-gi/gi`,oH=/^[A-Za-z][A-Za-z\d_]*$/});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 cH=__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,flatpak:t.flatpak}}function stageManifestPath(t){return xn(t,lH)}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(xn(t.stageDir,n.path.split(`/`).join(On))).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 ${lH}, 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(!VV.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${VV.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=wB.map(t=>CB[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`))}}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 lH,uH=__esmMin(()=>{Md(),jn(),cH(),Xm(),UV(),EB(),lH=`.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 \`${lH}\` — 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=xn(t,S.path.split(`/`).join(On));mkdirSync(wn(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: ${xn(n,t.split(`/`).join(On))} 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(xn(n,t.split(`/`).join(On))));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=xn(t,N.path.slice(C.length).split(`/`).join(On));mkdirSync(wn(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(xn(t,S.split(`/`).join(On))).size;return n}var dH=__esmMin(()=>{Md(),jn(),rV(),uH()});function resolveSignPlan(t){let n=fH[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.sealPrefix;return{sealed:N===void 0?[]:C.filter(t=>t.startsWith(N)),unexpected:N===void 0?C:C.filter(t=>!t.startsWith(N)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t;writePayload(C,n,``);let N=t.identity===`-`,F,I=S.entitlements(N);I.length>0&&(mkdirSync(wn(t.entitlementsPath),{recursive:!0}),writeFileSync(t.entitlementsPath,renderEntitlements(I)),F=t.entitlementsPath);let run=async(n,I)=>{let H=S.args({identity:t.identity,file:n,adhoc:N,...F?{entitlements:F}:{}});t.verbose&&t.log(`${S.tool} ${H.join(` `)}`);let W=await spawnToCompletion(S.tool,H,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(W.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${I} with ${describeExit(W)}. 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.`)},H=n.filter(t=>classifyBinary(t.data)===S.signs);if(H.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 H)await run(xn(C,t.path.split(`/`).join(On)),t.path);let W;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.`);W=S.sealAddPrefix(t.bundleRoot),await run(xn(C,t.bundleRoot.split(`/`).join(On)),`${t.bundleRoot} (bundle seal)`)}let q=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),...W===void 0?{}:{sealPrefix:W}});if(q.unexpected.length>0||q.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${q.unexpected.length} added (${q.unexpected.slice(0,3).join(`, `)||`—`}), ${q.removed.length} removed (${q.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly the seal's own directory${W===void 0?``:` (\`${W}\`)`}.`);let Y=q.sealed;t.log(`${S.tool} signed ${H.length} of ${n.length} payload file(s) as ${N?"ad-hoc (`-`)":`\`${t.identity}\``}${W===void 0?``:` and sealed ${t.bundleRoot} (${Y.length} seal file(s))`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(xn(C,t.split(`/`).join(On))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...Y.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=pH[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 fH,pH,mH=__esmMin(()=>{Md(),jn(),qP(),j_(),rV(),VB(),xB(),dH(),fH={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})=>[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],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, and no run in this repository has ever held the named one"},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)`}},pH={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}/${un.basename(zz.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}`)}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(`
|
|
1156
|
+
`)}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=xn(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=xn(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,xn(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 GV,KV,qV,JV=__esmMin(()=>{_e(),Kc(),Md(),jn(),j_(),DB(),WB(),GV=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,KV=/[<>:"/\\|?*;]/,qV=`root`});function getCrcTable(){if(tH!==null)return tH;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 tH=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(YV),I.u16(eH),I.u16(2048),I.u16(QV),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(XV),H.u16($V),H.u16(eH),H.u16(2048),H.u16(QV),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(ZV),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 YV,XV,ZV,QV,$V,eH,tH,Writer,nH=__esmMin(()=>{YV=67324752,XV=33639248,ZV=101010256,QV=0,$V=788,eH=20,tH=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 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 staticStringValue(t){if(t?.type===`Literal`)return typeof t.value==`string`?t.value:null;if(t?.type===`TemplateLiteral`&&t.expressions?.length===0){let n=t.quasis?.[0]?.value?.cooked;return typeof n==`string`?n:null}return null}function walkModuleAst(t,n){let S;try{S=parse$2(t,{ecmaVersion:`latest`,sourceType:`module`,allowHashBang:!0})}catch{return}let descend=t=>{if(!t||typeof t!=`object`)return;if(Array.isArray(t)){for(let n of t)descend(n);return}let S=t;n(S);for(let[t,n]of Object.entries(S))t===`type`||t===`start`||t===`end`||t===`loc`||descend(n)};descend(S)}function importedSpecifier(t){return t.type!==`ImportDeclaration`&&t.type!==`ExportNamedDeclaration`&&t.type!==`ExportAllDeclaration`&&t.type!==`ImportExpression`?null:staticStringValue(t.source)}function moduleSpecifiers$1(t){let n=[];return walkModuleAst(t,t=>{let S=importedSpecifier(t);S!==null&&n.push(S)}),n}function resolveRelative(t,n){let S=vn(wn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,xn(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=vn(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(xn(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?vn(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 rH=__esmMin(()=>{Ax(),Md(),jn(),Xm(),__name$1(moduleSpecifiers$1,`moduleSpecifiers`)});function entryEvidence(t){let n=new Set,S=new Set;return walkModuleAst(t,t=>{let C=importedSpecifier(t);C!==null&&(C.startsWith(`gi://`)||iH.has(C)?n.add(C):C.startsWith(`node:`)&&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.
|
|
1157
|
+
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 iH,aH=__esmMin(()=>{rH(),iH=new Set([`system`,`gettext`])});function scanGiRequirements(t){let n=new Set,S=new Set,C=new Set,N=new Set,F=[];walkModuleAst(t,t=>{let S=importedSpecifier(t);if(S!==null){let F=parseGiSpecifier(S);F!==null&&n.add(F),t.type===`ImportDeclaration`&&S===oH&&collectNodeGiBindings(t,C,N);return}if(t.type===`VariableDeclarator`&&loadsNodeGiModule(t.init)){let n=t.id;n?.type===`Identifier`&&typeof n.name==`string`&&N.add(n.name);return}t.type===`CallExpression`&&F.push(t)});for(let t of F){let F=optionalMarkerNamespace(t);if(F!==null){S.add(F);continue}let I=requireGiNamespace(t,C,N);I!==null&&n.add(I)}return{namespaces:[...n].sort(),optional:[...S].filter(t=>n.has(t)).sort()}}function optionalMarkerNamespace(t){let n=t.callee;if(n?.type!==`MemberExpression`||n.computed!==!0)return null;let S=n.property;if(S?.type!==`CallExpression`)return null;let C=S.callee,N=C?.type===`MemberExpression`?C.object:void 0,F=C?.type===`MemberExpression`?C.property:void 0;if(N?.type!==`Identifier`||N.name!==`Symbol`||F?.type!==`Identifier`||F.name!==`for`||staticStringValue((S.arguments??[])[0])!==`gjsify.optionalGi`)return null;let I=n.object;if(I?.type!==`Identifier`||I.name!==`globalThis`)return null;let H=t.arguments??[],W=staticStringValue(H[0]);if(W===null||!sH.test(W))return null;let q=staticStringValue(H[1]);return q===null||q===``?W:`${W}-${q}`}function parseGiSpecifier(t){if(!t.startsWith(`gi://`))return null;let[n,S]=t.slice(5).split(`?`,2);if(n===void 0||!sH.test(n))return null;if(S===void 0)return n;let C=/(?:^|&)version=([^&]+)/.exec(S)?.[1];return C===void 0?n:`${n}-${C}`}function collectNodeGiBindings(t,n,S){let C=t.specifiers??[];for(let t of C){let C=t.local;if(C?.type!==`Identifier`||typeof C.name!=`string`)continue;let N=t.imported;t.type===`ImportNamespaceSpecifier`?S.add(C.name):(t.type===`ImportDefaultSpecifier`||N?.type===`Identifier`&&N.name===`requireGi`)&&n.add(C.name)}}function loadsNodeGiModule(t){if(!t||typeof t!=`object`)return!1;let n=t;return n.type===`CallExpression`?staticStringValue((n.arguments??[])[0])===oH:!1}function requireGiNamespace(t,n,S){let C=t.callee,N=!1;if(C?.type===`Identifier`)N=typeof C.name==`string`&&n.has(C.name);else if(C?.type===`MemberExpression`&&C.computed!==!0){let t=C.property;if(t?.type!==`Identifier`||t.name!==`requireGi`)return null;let n=C.object;N=loadsNodeGiModule(n)||n?.type===`Identifier`&&typeof n.name==`string`&&S.has(n.name)}if(!N)return null;let F=t.arguments??[],I=staticStringValue(F[0]);if(I===null||!sH.test(I))return null;let H=staticStringValue(F[1]);return H===null?I:`${I}-${H}`}var oH,sH,cH=__esmMin(()=>{Vj(),rH(),oH=`@gjsify/node-gi/gi`,sH=/^[A-Za-z][A-Za-z\d_]*$/});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 lH=__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,flatpak:t.flatpak}}function stageManifestPath(t){return xn(t,uH)}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(xn(t.stageDir,n.path.split(`/`).join(On))).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 ${uH}, 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(!HV.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${HV.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=TB.map(t=>wB[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`))}}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 uH,dH=__esmMin(()=>{Md(),jn(),lH(),Xm(),WV(),DB(),uH=`.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 \`${uH}\` — 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=xn(t,S.path.split(`/`).join(On));mkdirSync(wn(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: ${xn(n,t.split(`/`).join(On))} 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(xn(n,t.split(`/`).join(On))));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=xn(t,N.path.slice(C.length).split(`/`).join(On));mkdirSync(wn(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(xn(t,S.split(`/`).join(On))).size;return n}var fH=__esmMin(()=>{Md(),jn(),iV(),dH()});function resolveSignPlan(t){let n=pH[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.sealPrefix;return{sealed:N===void 0?[]:C.filter(t=>t.startsWith(N)),unexpected:N===void 0?C:C.filter(t=>!t.startsWith(N)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t;writePayload(C,n,``);let N=t.identity===`-`,F,I=S.entitlements(N);I.length>0&&(mkdirSync(wn(t.entitlementsPath),{recursive:!0}),writeFileSync(t.entitlementsPath,renderEntitlements(I)),F=t.entitlementsPath);let run=async(n,I)=>{let H=S.args({identity:t.identity,file:n,adhoc:N,...F?{entitlements:F}:{}});t.verbose&&t.log(`${S.tool} ${H.join(` `)}`);let W=await spawnToCompletion(S.tool,H,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(W.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${I} with ${describeExit(W)}. 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.`)},H=n.filter(t=>classifyBinary(t.data)===S.signs);if(H.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 H)await run(xn(C,t.path.split(`/`).join(On)),t.path);let W;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.`);W=S.sealAddPrefix(t.bundleRoot),await run(xn(C,t.bundleRoot.split(`/`).join(On)),`${t.bundleRoot} (bundle seal)`)}let q=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),...W===void 0?{}:{sealPrefix:W}});if(q.unexpected.length>0||q.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${q.unexpected.length} added (${q.unexpected.slice(0,3).join(`, `)||`—`}), ${q.removed.length} removed (${q.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly the seal's own directory${W===void 0?``:` (\`${W}\`)`}.`);let Y=q.sealed;t.log(`${S.tool} signed ${H.length} of ${n.length} payload file(s) as ${N?"ad-hoc (`-`)":`\`${t.identity}\``}${W===void 0?``:` and sealed ${t.bundleRoot} (${Y.length} seal file(s))`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(xn(C,t.split(`/`).join(On))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...Y.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=mH[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 pH,mH,hH=__esmMin(()=>{Md(),jn(),JP(),j_(),iV(),HB(),SB(),fH(),pH={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})=>[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],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, and no run in this repository has ever held the named one"},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)`}},mH={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}/${un.basename(Bz.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}`)}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(`
|
|
1158
1158
|
`)}function renderAppBundleLauncher(t,n,S,C){let N=`${S.root(t)}/Contents`,F=S.dirs(t),under=t=>un.relative(N,t),beside=t=>un.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(`
|
|
1159
1159
|
`)}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
|
|
1160
|
-
`)}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
|
|
1160
|
+
`)}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 gH=__esmMin(()=>{jn(),Vz()});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=_H+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!==vH)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${vH}.`);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 _H,vH,yH,bH,xH=__esmMin(()=>{Ez(),_H=`070701`,vH=110,yH=32768,bH=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=TH[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,-(CH*H),wH)),F+=CH;let W=new Uint8Array(SH.byteLength+8+H*CH+F),q=new DataView(W.buffer);W.set(SH,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,wH),Y),Y+=CH;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=CH;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(CH),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 SH,CH,wH,TH,EH=__esmMin(()=>{SH=Uint8Array.from([142,173,232,1,0,0,0,0]),CH=16,wH=16,TH={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:OH.SHA1HEADER,type:6,value:hashHex(`sha1`,I)},{tag:OH.SHA256HEADER,type:6,value:hashHex(`sha256`,I)},{tag:OH.SIZE,type:4,value:[H.byteLength]},{tag:OH.MD5,type:7,value:hashBytes(`md5`,H)},{tag:OH.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:yH|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}`,MH.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:bH|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:DH.HEADERI18NTABLE,type:8,value:[`C`]},{tag:DH.NAME,type:6,value:N.binaryName},{tag:DH.VERSION,type:6,value:N.version},{tag:DH.RELEASE,type:6,value:N.release},{tag:DH.SUMMARY,type:9,value:[N.summary]},{tag:DH.DESCRIPTION,type:9,value:[N.description.join(`
|
|
1161
1161
|
|
|
1162
|
-
`)]},{tag:EH.BUILDTIME,type:4,value:[t.mtime]},{tag:EH.BUILDHOST,type:6,value:`localhost`},{tag:EH.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:EH.LICENSE,type:6,value:N.license},{tag:EH.GROUP,type:9,value:[N.group]},{tag:EH.OS,type:6,value:`linux`},{tag:EH.ARCH,type:6,value:t.archLabel},{tag:EH.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:EH.RPMVERSION,type:6,value:`4.20.0`},{tag:EH.ENCODING,type:6,value:`utf-8`},{tag:EH.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:EH.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:EH.FILERDEVS,type:3,value:n.map(()=>0)},{tag:EH.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:EH.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:EH.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:EH.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:EH.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:EH.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:EH.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:EH.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:EH.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:EH.FILELANGS,type:8,value:n.map(()=>``)},{tag:EH.FILEDIGESTALGO,type:4,value:[kH]},{tag:EH.DIRINDEXES,type:4,value:H},{tag:EH.BASENAMES,type:8,value:W},{tag:EH.DIRNAMES,type:8,value:I},{tag:EH.PROVIDENAME,type:8,value:[N.binaryName]},{tag:EH.PROVIDEFLAGS,type:4,value:[OH.EQUAL]},{tag:EH.PROVIDEVERSION,type:8,value:[F]},{tag:EH.REQUIRENAME,type:8,value:Y.names},{tag:EH.REQUIREFLAGS,type:4,value:Y.flags},{tag:EH.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:EH.RECOMMENDNAME,type:8,value:X.names},{tag:EH.RECOMMENDFLAGS,type:4,value:X.flags},{tag:EH.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:EH.PAYLOADFORMAT,type:6,value:`cpio`},{tag:EH.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:EH.PAYLOADFLAGS,type:6,value:`9`},{tag:EH.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:EH.PAYLOADDIGESTALGO,type:4,value:[kH]},{tag:EH.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:EH.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:EH.POSTIN,type:6,value:q.post}),Z.push({tag:EH.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:EH.POSTUN,type:6,value:q.postun}),Z.push({tag:EH.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([EH.FILESIZES,EH.FILEMODES,EH.FILERDEVS,EH.FILEMTIMES,EH.FILEDIGESTS,EH.FILELINKTOS,EH.FILEFLAGS,EH.FILEUSERNAME,EH.FILEGROUPNAME,EH.FILEVERIFYFLAGS,EH.FILEDEVICES,EH.FILEINODES,EH.FILELANGS,EH.DIRINDEXES,EH.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(OH.INTERP|OH.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(OH.INTERP|OH.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(OH.FIND_REQUIRES),F.push(``);for(let[t,n]of AH)C.push(t),N.push(OH.RPMLIB|OH.LESS|OH.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 OH.GREATER|OH.EQUAL;case`>`:return OH.GREATER;case`<=`:return OH.LESS|OH.EQUAL;case`<`:return OH.LESS;case`=`:return OH.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 EH,DH,OH,kH,AH,jH,MH=__esmMin(()=>{Kc(),Tz(),bH(),Lz(),VB(),TH(),Rz(),Vz(),Bz(),EH={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},DH={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},OH={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},kH=8,AH=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],jH=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${zz.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${zz.metainfo}`,`/usr/share/glib-2.0`,`/usr/${zz.schemas}`,`/usr/${zz.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(`${NH} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(xn(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(`${NH} \`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=>BV[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${NH} ${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);t[`skip-build`]||await runProjectBuild(n);let te=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});te.overridden&&ge.log(`${NH} entry for ${S.name}: ${te.declared} — \`${te.key}\` overrides \`gjsify.main\`.`);let ne=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:te.declared,foreignBundles:te.foreign}),{settings:re,metadata:ie,warnings:ae}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ne,app:H});for(let t of ae)ge.warn(`${NH} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,re.app);let oe=readFileSync(re.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:re.app,source:oe,entry:Sn(n,re.bundlePath)||re.bundlePath,appKey:I.key,bundleKey:te.key,layoutOs:S.os});let Q=buildTimestamp(re.bundlePath),se={appId:re.appId,name:re.name,command:re.binaryName,kind:re.kind,metadata:ie,configKey:`gjsify.ship`,copyrightYear:new Date(Q*1e3).getUTCFullYear()};for(let t of validateAppMetadata(se))ge.warn(`${NH} ${t.field} is not set — ${t.hint}`);re.licenseFile!==void 0&&wn(re.licenseFile)!==n&&ge.log(`${NH} licence text from ${Sn(n,re.licenseFile)} (this package carries none of its own)`);let ce=localizeMetadata({metainfo:re.kind===`app`?renderMetainfoApp$1(se):renderMetainfoCli$1(se),desktopEntry:re.kind===`app`?renderDesktopEntry(se):void 0},re.localeFiles),le=resolveCarriedRuntime(S,re,n),ue={bundleFiles:ne.bundleFiles,launcher:renderLauncher(re,Tn(re.bundlePath),S,le.launcher),metainfo:ce.metainfo,desktopEntry:ce.desktopEntry,licenseText:re.licenseFile===void 0?void 0:readFileSync(re.licenseFile,`utf-8`),changelogText:re.changelogFile===void 0?void 0:readFileSync(re.changelogFile,`utf-8`),mtime:Q},de=vn(n,re.outDir),fe=xn(de,`stage`),pe=[...planStage(re,ue),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:re.schemaFiles,workDir:xn(de,`schemas`)})],me=re.kind===`app`&&S.icon!==void 0?await resolveAppIcon({iconFiles:re.iconFiles,appId:re.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;me!==void 0&&ge.log(`${NH} icon: ${iconSizes(me).join(`/`)} px, ${me.source}`);let he=placeStage(S,{...re,icon:me},pe,le.files);if(writeStage(fe,he),ge.log(`${NH} staged ${he.length} file(s) for ${S.name} in ${Sn(n,fe)}/`),t.verbose)for(let t of he)ge.log(`${NH} ${t.path}`);if(assertPayloadMatchesArch(readStage([fe],he),re.arch),S.os!==`linux`){let t=linuxInstallDependent(pe);if(t.length>0){ge.warn(`${NH} 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(`${NH} ${n[C]??``}${S} — ${N}`)}for(let t of le.found)ge.log(`${NH} carries its own ${t}`);for(let t of le.missing)ge.warn(`${NH} ${t}`);le.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${NH} ${S.runtimeGap}`),S.fontGap!==void 0&&pe.some(t=>isUnder(t.path,zz.fonts))&&ge.warn(`${NH} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(re.arch)&&ge.warn(`${NH} this stage is labelled ${re.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 _e=scanGiRequirements(oe),ve=_e.namespaces,ye=_e.optional;if(t.verbose){let t=ve.filter(t=>!ye.includes(t));ge.log(`${NH} gi namespaces: ${ve.join(`, `)||`(none)`}`),ye.length>0&&(ge.log(`${NH} gi optional namespaces: ${ye.join(`, `)}`),ge.log(`${NH} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let be=new Map;for(let t of q)be.set(t.id,(await planOverlay(re,t,ue)).map(t=>({...t,path:place(S,re,t.path)})));let xe=readPayloadFacts(pe);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:ve,optionalNamespaces:ye,hasIcons:xe.hasIcons,hasSchemas:xe.hasSchemas,interpreter:re.app,extra:re.extraDepends[t.depends],typelibPackages:re.typelibPackages,bundledTypelibs:xe.bundledTypelibs,minGjsVersion:re.minGjsVersion,minNodeVersion:re.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${NH} 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=re.app===`node`?warnAboutNodeFloor(t.depends,re.minNodeVersion):warnAboutGjsFloor(t.depends,re.minGjsVersion);for(let t of S)ge.warn(`${NH} ${t}`)}let Se=writeStageManifest({stageDir:fe,settings:re,formats:q,mtime:Q,namespaces:ve,optionalNamespaces:ye,staged:he,overlay:be});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=Se.formats.join(`, `)||t;ge.log(`${NH} stage manifest: ${formatTarget(Se.target)}, formats ${n}`);return}let Ce=[];for(let n of q)Ce.push(await packOne({format:n,settings:re,arch:re.arch,staged:he,overlay:be.get(n.id)??[],stageDir:fe,outRoot:de,namespaces:ve,optionalNamespaces:ye,mtime:Q,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,Ce)}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(`${NH} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${NH} ${n.message}`)}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}`;return isGtkRuntimeTarget(N)?stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null}):C}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=vn(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=>BV[t]),F,`stage`,defaultFormatIds(F.os).map(t=>BV[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(`${NH} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${NH} ${t}`);if(ge.log(`${NH} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Sn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${NH} ${t.path}`);ge.log(`${NH} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${NH} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?wn(C):vn(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(`${NH} ${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=xn(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);let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:xn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:xn(N,`signed`,`${n.id}.entitlements.plist`),verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}):H,ne=n.archName(t.arch,isArchIndependent(te)),re={settings:S,payload:te,prefix:n.prefix,depends:Y,recommends:X,archLabel:ne,mtime:F},ie=xn(N,`out`);mkdirSync(ie,{recursive:!0});let ae=xn(ie,n.fileName(S,ne));switch(n.id){case`deb`:writeFileSync(ae,await buildDeb(re));break;case`rpm`:writeFileSync(ae,await buildRpm(re));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:lH,workDir:xn(N,`flatpak`),target:ae,archLabel:ne,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,te,n,await compileSchemasForPayload({payload:te,workDir:xn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${NH} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(ne);ge.log(`${NH} ${appImageRuntimeNotice(ne,H)}`),await buildAppImage({appDir:C,target:ae,archLabel:ne,runtimeFile:H,workDir:wn(C),verbose:t.verbose});break}case`macos-app`:case`windows-dir`:writePayload(ae,te,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);writePayload(n,te,``),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:ae,workDir:wn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te),F));break;case`windows-dir-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te,windowsProgramDirName(S)),F));break;case`msi`:{let n=xn(N,`msi`);writePayload(xn(n,KV),te,Z.root(S)),await buildMsi({settings:S,files:te.map(t=>({path:t.path,source:`${KV}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:ne,workDir:n,target:ae,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let oe=n.artifactKind===`directory`?directorySize(ae):statSync(ae).size;return t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${NH} ${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:ae,verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}),canCarryTicket(n.id)?await stapleArtifact({notary:t.notarize.notary,artifact:ae,verbose:t.verbose,log:t=>ge.log(`${NH} ${t}`)}):ge.warn(`${NH} ${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.`))),{format:n.id,path:ae,size:oe}}function printArtifacts(t,n){for(let S of n)ge.log(`${NH} ${S.format}: ${Sn(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.
|
|
1162
|
+
`)]},{tag:DH.BUILDTIME,type:4,value:[t.mtime]},{tag:DH.BUILDHOST,type:6,value:`localhost`},{tag:DH.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:DH.LICENSE,type:6,value:N.license},{tag:DH.GROUP,type:9,value:[N.group]},{tag:DH.OS,type:6,value:`linux`},{tag:DH.ARCH,type:6,value:t.archLabel},{tag:DH.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:DH.RPMVERSION,type:6,value:`4.20.0`},{tag:DH.ENCODING,type:6,value:`utf-8`},{tag:DH.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:DH.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:DH.FILERDEVS,type:3,value:n.map(()=>0)},{tag:DH.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:DH.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:DH.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:DH.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:DH.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:DH.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:DH.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:DH.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:DH.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:DH.FILELANGS,type:8,value:n.map(()=>``)},{tag:DH.FILEDIGESTALGO,type:4,value:[AH]},{tag:DH.DIRINDEXES,type:4,value:H},{tag:DH.BASENAMES,type:8,value:W},{tag:DH.DIRNAMES,type:8,value:I},{tag:DH.PROVIDENAME,type:8,value:[N.binaryName]},{tag:DH.PROVIDEFLAGS,type:4,value:[kH.EQUAL]},{tag:DH.PROVIDEVERSION,type:8,value:[F]},{tag:DH.REQUIRENAME,type:8,value:Y.names},{tag:DH.REQUIREFLAGS,type:4,value:Y.flags},{tag:DH.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:DH.RECOMMENDNAME,type:8,value:X.names},{tag:DH.RECOMMENDFLAGS,type:4,value:X.flags},{tag:DH.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:DH.PAYLOADFORMAT,type:6,value:`cpio`},{tag:DH.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:DH.PAYLOADFLAGS,type:6,value:`9`},{tag:DH.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:DH.PAYLOADDIGESTALGO,type:4,value:[AH]},{tag:DH.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:DH.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:DH.POSTIN,type:6,value:q.post}),Z.push({tag:DH.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:DH.POSTUN,type:6,value:q.postun}),Z.push({tag:DH.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([DH.FILESIZES,DH.FILEMODES,DH.FILERDEVS,DH.FILEMTIMES,DH.FILEDIGESTS,DH.FILELINKTOS,DH.FILEFLAGS,DH.FILEUSERNAME,DH.FILEGROUPNAME,DH.FILEVERIFYFLAGS,DH.FILEDEVICES,DH.FILEINODES,DH.FILELANGS,DH.DIRINDEXES,DH.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(kH.INTERP|kH.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(kH.INTERP|kH.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(kH.FIND_REQUIRES),F.push(``);for(let[t,n]of jH)C.push(t),N.push(kH.RPMLIB|kH.LESS|kH.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 kH.GREATER|kH.EQUAL;case`>`:return kH.GREATER;case`<=`:return kH.LESS|kH.EQUAL;case`<`:return kH.LESS;case`=`:return kH.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 DH,OH,kH,AH,jH,MH,NH=__esmMin(()=>{Kc(),Ez(),xH(),Rz(),HB(),EH(),zz(),Hz(),Vz(),DH={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},OH={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},kH={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},AH=8,jH=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],MH=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${Bz.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${Bz.metainfo}`,`/usr/share/glib-2.0`,`/usr/${Bz.schemas}`,`/usr/${Bz.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(`${PH} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(xn(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(`${PH} \`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=>VV[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${PH} ${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);t[`skip-build`]||await runProjectBuild(n);let te=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});te.overridden&&ge.log(`${PH} entry for ${S.name}: ${te.declared} — \`${te.key}\` overrides \`gjsify.main\`.`);let ne=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:te.declared,foreignBundles:te.foreign}),{settings:re,metadata:ie,warnings:ae}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ne,app:H});for(let t of ae)ge.warn(`${PH} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,re.app);let oe=readFileSync(re.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:re.app,source:oe,entry:Sn(n,re.bundlePath)||re.bundlePath,appKey:I.key,bundleKey:te.key,layoutOs:S.os});let Q=buildTimestamp(re.bundlePath),se={appId:re.appId,name:re.name,command:re.binaryName,kind:re.kind,metadata:ie,configKey:`gjsify.ship`,copyrightYear:new Date(Q*1e3).getUTCFullYear()};for(let t of validateAppMetadata(se))ge.warn(`${PH} ${t.field} is not set — ${t.hint}`);re.licenseFile!==void 0&&wn(re.licenseFile)!==n&&ge.log(`${PH} licence text from ${Sn(n,re.licenseFile)} (this package carries none of its own)`);let ce=localizeMetadata({metainfo:re.kind===`app`?renderMetainfoApp$1(se):renderMetainfoCli$1(se),desktopEntry:re.kind===`app`?renderDesktopEntry(se):void 0},re.localeFiles),le=resolveCarriedRuntime(S,re,n),ue={bundleFiles:ne.bundleFiles,launcher:renderLauncher(re,Tn(re.bundlePath),S,le.launcher),metainfo:ce.metainfo,desktopEntry:ce.desktopEntry,licenseText:re.licenseFile===void 0?void 0:readFileSync(re.licenseFile,`utf-8`),changelogText:re.changelogFile===void 0?void 0:readFileSync(re.changelogFile,`utf-8`),mtime:Q},de=vn(n,re.outDir),fe=xn(de,`stage`),pe=[...planStage(re,ue),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:re.schemaFiles,workDir:xn(de,`schemas`)})],me=re.kind===`app`&&S.icon!==void 0?await resolveAppIcon({iconFiles:re.iconFiles,appId:re.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;me!==void 0&&ge.log(`${PH} icon: ${iconSizes(me).join(`/`)} px, ${me.source}`);let he=placeStage(S,{...re,icon:me},pe,le.files);if(writeStage(fe,he),ge.log(`${PH} staged ${he.length} file(s) for ${S.name} in ${Sn(n,fe)}/`),t.verbose)for(let t of he)ge.log(`${PH} ${t.path}`);if(assertPayloadMatchesArch(readStage([fe],he),re.arch),S.os!==`linux`){let t=linuxInstallDependent(pe);if(t.length>0){ge.warn(`${PH} 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(`${PH} ${n[C]??``}${S} — ${N}`)}for(let t of le.found)ge.log(`${PH} carries its own ${t}`);for(let t of le.missing)ge.warn(`${PH} ${t}`);le.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${PH} ${S.runtimeGap}`),S.fontGap!==void 0&&pe.some(t=>isUnder(t.path,Bz.fonts))&&ge.warn(`${PH} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(re.arch)&&ge.warn(`${PH} this stage is labelled ${re.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 _e=scanGiRequirements(oe),ve=_e.namespaces,ye=_e.optional;if(t.verbose){let t=ve.filter(t=>!ye.includes(t));ge.log(`${PH} gi namespaces: ${ve.join(`, `)||`(none)`}`),ye.length>0&&(ge.log(`${PH} gi optional namespaces: ${ye.join(`, `)}`),ge.log(`${PH} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let be=new Map;for(let t of q)be.set(t.id,(await planOverlay(re,t,ue)).map(t=>({...t,path:place(S,re,t.path)})));let xe=readPayloadFacts(pe);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:ve,optionalNamespaces:ye,hasIcons:xe.hasIcons,hasSchemas:xe.hasSchemas,interpreter:re.app,extra:re.extraDepends[t.depends],typelibPackages:re.typelibPackages,bundledTypelibs:xe.bundledTypelibs,minGjsVersion:re.minGjsVersion,minNodeVersion:re.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${PH} 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=re.app===`node`?warnAboutNodeFloor(t.depends,re.minNodeVersion):warnAboutGjsFloor(t.depends,re.minGjsVersion);for(let t of S)ge.warn(`${PH} ${t}`)}let Se=writeStageManifest({stageDir:fe,settings:re,formats:q,mtime:Q,namespaces:ve,optionalNamespaces:ye,staged:he,overlay:be});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=Se.formats.join(`, `)||t;ge.log(`${PH} stage manifest: ${formatTarget(Se.target)}, formats ${n}`);return}let Ce=[];for(let n of q)Ce.push(await packOne({format:n,settings:re,arch:re.arch,staged:he,overlay:be.get(n.id)??[],stageDir:fe,outRoot:de,namespaces:ve,optionalNamespaces:ye,mtime:Q,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,Ce)}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(`${PH} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${PH} ${n.message}`)}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}`;return isGtkRuntimeTarget(N)?stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null}):C}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=vn(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=>VV[t]),F,`stage`,defaultFormatIds(F.os).map(t=>VV[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(`${PH} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${PH} ${t}`);if(ge.log(`${PH} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Sn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${PH} ${t.path}`);ge.log(`${PH} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${PH} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?wn(C):vn(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(`${PH} ${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=xn(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);let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:xn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:xn(N,`signed`,`${n.id}.entitlements.plist`),verbose:t.verbose,log:t=>ge.log(`${PH} ${t}`)}):H,ne=n.archName(t.arch,isArchIndependent(te)),re={settings:S,payload:te,prefix:n.prefix,depends:Y,recommends:X,archLabel:ne,mtime:F},ie=xn(N,`out`);mkdirSync(ie,{recursive:!0});let ae=xn(ie,n.fileName(S,ne));switch(n.id){case`deb`:writeFileSync(ae,await buildDeb(re));break;case`rpm`:writeFileSync(ae,await buildRpm(re));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:uH,workDir:xn(N,`flatpak`),target:ae,archLabel:ne,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,te,n,await compileSchemasForPayload({payload:te,workDir:xn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${PH} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(ne);ge.log(`${PH} ${appImageRuntimeNotice(ne,H)}`),await buildAppImage({appDir:C,target:ae,archLabel:ne,runtimeFile:H,workDir:wn(C),verbose:t.verbose});break}case`macos-app`:case`windows-dir`:writePayload(ae,te,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);writePayload(n,te,``),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:ae,workDir:wn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te),F));break;case`windows-dir-zip`:writeFileSync(ae,buildZip(zipEntriesFromPayload(te,windowsProgramDirName(S)),F));break;case`msi`:{let n=xn(N,`msi`);writePayload(xn(n,qV),te,Z.root(S)),await buildMsi({settings:S,files:te.map(t=>({path:t.path,source:`${qV}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:ne,workDir:n,target:ae,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let oe=n.artifactKind===`directory`?directorySize(ae):statSync(ae).size;return t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${PH} ${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:ae,verbose:t.verbose,log:t=>ge.log(`${PH} ${t}`)}),canCarryTicket(n.id)?await stapleArtifact({notary:t.notarize.notary,artifact:ae,verbose:t.verbose,log:t=>ge.log(`${PH} ${t}`)}):ge.warn(`${PH} ${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.`))),{format:n.id,path:ae,size:oe}}function printArtifacts(t,n){for(let S of n)ge.log(`${PH} ${S.format}: ${Sn(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.
|
|
1163
1163
|
\`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,
|
|
1164
1164
|
so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
|
|
1165
|
-
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){if(typeof readPackageJson$2(xn(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(`${NH} running the project's build script`);let n=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,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 NH,PH,FH=__esmMin(()=>{_e(),Md(),jn(),JF(),KR(),OP(),j_(),HB(),Lz(),mV(),rV(),CV(),EV(),WR(),DV(),Kz(),OV(),UV(),EB(),aV(),Bz(),jB(),qV(),tH(),iH(),sH(),VB(),uV(),mH(),hH(),MH(),$B(),uH(),dH(),NH=`[gjsify ship]`,PH={command:`ship [os]`,description:`Build installable artifacts (${VV.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${wB.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(`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)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var IH=__esmMin(()=>{t_()});function workspaceLinkTarget(t,n){return LH===`junction`?vn(n):Sn(wn(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===BH&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=wn(vn(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==wn(t);n++){let n=readCliVersionFrom(xn(t,`package.json`));if(n)return n;t=wn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(xn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[BH];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(xn(t,`node_modules`,BH,`package.json`));if(n)return n}return readCliVersionFrom(xn(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(xn(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=xn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(xn(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=xn(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)+`
|
|
1166
|
-
`)}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(()=>(hd(),fd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=xn(C.location,`node_modules`,t.depName);n.add(wn(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,
|
|
1167
|
-
`+(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?xn(t,n):null,F=S?xn(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(xn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${
|
|
1168
|
-
gjsify install ${
|
|
1165
|
+
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){if(typeof readPackageJson$2(xn(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(`${PH} running the project's build script`);let n=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,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 PH,FH,IH=__esmMin(()=>{_e(),Md(),jn(),YF(),qR(),kP(),j_(),UB(),Rz(),hV(),iV(),wV(),DV(),GR(),OV(),qz(),kV(),WV(),DB(),oV(),Vz(),MB(),JV(),nH(),aH(),cH(),HB(),dV(),hH(),gH(),NH(),eV(),dH(),fH(),PH=`[gjsify ship]`,FH={command:`ship [os]`,description:`Build installable artifacts (${HV.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${TB.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(`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)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var LH=__esmMin(()=>{t_()});function workspaceLinkTarget(t,n){return RH===`junction`?vn(n):Sn(wn(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===VH&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=wn(vn(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==wn(t);n++){let n=readCliVersionFrom(xn(t,`package.json`));if(n)return n;t=wn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(xn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[VH];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(xn(t,`node_modules`,VH,`package.json`));if(n)return n}return readCliVersionFrom(xn(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(xn(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=xn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(xn(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=xn(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)+`
|
|
1166
|
+
`)}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(()=>(hd(),fd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=xn(C.location,`node_modules`,t.depName);n.add(wn(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,RH)};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=xn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=xn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(wn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,RH),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=xn(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=xn(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?xn(t,n):null,H=S?xn(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
|
|
1167
|
+
`+(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?xn(t,n):null,F=S?xn(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(xn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${EL} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
|
|
1168
|
+
gjsify install ${EL}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let F=readCliVersionFrom(xn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ge.log(`\n${EL} 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(`
|
|
1169
1169
|
--- 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:
|
|
1170
1170
|
`);for(let t of S)ge.warn(` ✗ ${t.name}`);let t=buildInstallCommand(detectPackageManager$1(),S);t&&ge.warn(`\nInstall with:\n ${t}`)}else ge.log(`System dependencies OK.`);await ensureProjectGjsEngine(t,n.find(t=>t.id===`gjs`)?.found??!1);let C=detectNativePackages(process.cwd());if(C.length>0){ge.log(`\nDetected ${C.length} @gjsify/* package(s) with native prebuilds:`);for(let t of C)ge.log(` • ${t.name}`);ge.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.");let t=muslPrebuildFallbacks(detectHostLibc(process.platform),C);if(t.length>0){ge.warn(`\nWarning: musl host — ${t.length} of ${C.length} package(s) ship no \`-musl\` prebuild, so the
|
|
1171
1171
|
default (glibc) build was used:`);for(let n of t)ge.warn(` ${n}`);ge.warn(` Most of these run anyway: a bridge that links only GLib records no libc at all.
|
|
@@ -1175,22 +1175,24 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
|
|
|
1175
1175
|
A bridge lost that way is silently absent from the next build rather than
|
|
1176
1176
|
reported, so the first symptom can be an unrelated-looking bundler error
|
|
1177
1177
|
(\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
|
|
1178
|
-
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=xn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(xn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var LH,RH,zH,BH,VH=__esmMin(()=>{_e(),Md(),jn(),Hn(),w_(),IH(),DP(),qP(),QP(),uI(),CL(),OI(),JI(),bI(),j_(),kP(),oz(),DL(),cL(),uL(),EI(),pL(),LH=process.platform===`win32`?`junction`:void 0,RH=18e5,zH={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:RH}).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)}}},BH=`@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 HH,UH,WH=__esmMin(()=>{_e(),Md(),jn(),pL(),HH={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually depends on are ever linked.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=vn(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} depends on${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Sn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${dL} 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 ${dL} 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`.")}},UH={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 ${dL}).`);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 ${dL} 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(`
|
|
1179
|
-
`)+`\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 ${
|
|
1180
|
-
`)),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(),qH).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,GH.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&&GH.delete(N)}}var GH,KH,qH,JH,YH=__esmMin(()=>{_e(),j_(),RI(),Dg(),DP(),kP(),nH(),BL(),nI(),WL(),qL(),GH=new Set,KH=5e3,qH=15e3,JH={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[xn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(xn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var XH=__esmMin(()=>{jn(),j_(),kP()});async function packWorkspace(t,n={}){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1178
|
+
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=xn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(xn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var RH,zH,BH,VH,HH=__esmMin(()=>{_e(),Md(),jn(),Hn(),w_(),LH(),OP(),JP(),$P(),dI(),wL(),kI(),YI(),xI(),j_(),AP(),sz(),OL(),lL(),dL(),DI(),mL(),RH=process.platform===`win32`?`junction`:void 0,zH=18e5,BH={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:zH}).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)}}},VH=`@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 UH,WH,GH=__esmMin(()=>{_e(),Md(),jn(),mL(),UH={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually depends on are ever linked.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=vn(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} depends on${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Sn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${fL} 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 ${fL} 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`.")}},WH={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 ${fL}).`);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 ${fL} 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(`
|
|
1179
|
+
`)+`\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 ${fL} 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(()=>($G(),QG));await Y([`install`])}}});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of KH){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of KH){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},qH).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
|
|
1180
|
+
`)),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(),JH).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,KH.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&&KH.delete(N)}}var KH,qH,JH,YH,XH=__esmMin(()=>{_e(),j_(),zI(),Dg(),OP(),AP(),rH(),VL(),rI(),GL(),JL(),KH=new Set,qH=5e3,JH=15e3,YH={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[xn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(xn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(kn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var ZH=__esmMin(()=>{jn(),j_(),AP()});async function packWorkspace(t,n={}){let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1181
1181
|
`,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(xn(t,n)));let C=statSync(xn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?vn(n.destination):t,ce=xn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(xn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=xn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
|
|
1182
1182
|
`)+`
|
|
1183
|
-
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?xn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(
|
|
1184
|
-
`);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
|
|
1183
|
+
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?xn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if($H.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=xn(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=xn(t,`.npmignore`),S=xn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
|
|
1184
|
+
`);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 eU){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=xn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=vn(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 eU){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 QH,$H,eU,tU=__esmMin(()=>{Md(),Kc(),jn(),RI(),OP(),AP(),kP(),ZH(),QH={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(vn(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`)}},$H=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`]),eU=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});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){let S=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,C=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!S||!C)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 N=`${S}${S.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${N.replace(C,`<bearer>`)}`);let F=await fetch(N,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${C}`}});if(!F.ok){let t=await F.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${F.status} ${F.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let I=await F.json().catch(()=>({}));if(!I.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return I.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=t.maxRetries??3,H=t.retryBaseMs??1e3;for(let t=0;;t++){let S;try{S=await fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(S){if(t<I){let S=Math.min(H*2**t,8e3);N?.(`gjsify oidc: network error for ${n} (attempt ${t+1}/${I+1}), retrying in ${S}ms`),await sleep(S);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${n} after ${t+1} attempt(s): ${S instanceof Error?S.message:String(S)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await S.text().catch(()=>``);if(!S.ok){if(nU.has(S.status)&&t<I){let C=Math.min(H*2**t,8e3);N?.(`gjsify oidc: transient ${S.status} ${S.statusText} for ${n} (attempt ${t+1}/${I+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${S.status} ${S.statusText} — ${W.slice(0,300)}`,S.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)}`,S.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,S.status,W,n);return q.token}}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var nU,sleep,OidcUnavailableError,OidcExchangeError,rU=__esmMin(()=>{nU=new Set([408,425,429,500,502,503,504]),sleep=t=>new Promise(n=>setTimeout(n,t)),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`}}});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(`
|
|
1185
1185
|
`)}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(`
|
|
1186
|
-
`)}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
|
|
1187
|
-
`)}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()}-${++
|
|
1186
|
+
`)}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 iU=__esmMin(()=>{Jm()});function backoffFor(t){return aU[Math.min(Math.max(t,0),aU.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,oU))}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(`
|
|
1187
|
+
`)}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()}-${++cU}`});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 aU,oU,sU,cU,lU=__esmMin(()=>{Xm(),aU=[2e3,4e3,8e3,15e3,3e4],oU=2e3,sU=6e5,cU=0});function collectWorkspacePins(t,n){let S=[];for(let C of uU){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 uU,dU,depsOf,fU=__esmMin(()=>{uU=[`dependencies`,`optionalDependencies`,`peerDependencies`],dU=`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`||!pU.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 pU,mU=__esmMin(()=>{Xm(),pU=[`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(`
|
|
1188
|
+
`))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:gU});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 renderLedgerSummary(t,n){let S=new Set(t.filter(t=>t.ev===`served`).map(t=>`${t.name}@${t.version}`)),C=t.filter(t=>t.ev===`unserved`&&!S.has(`${t.name}@${t.version}`)),N=t.filter(t=>t.ev===`held`);if(C.length===0&&N.length===0)return;let F=[`### npm versions that were accepted but are not installable`,``];if(C.length>0){F.push(`| Package | Version | State | Detail |`,`| --- | --- | --- | --- |`);for(let t of C)F.push(`| \`${t.name}\` | ${t.version} | ${describeClass(t.cls)} | ${t.detail} |`);F.push(``)}if(N.length>0){F.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 N)F.push(`| \`${t.name}\` | ${t.version} | ${summariseReasons(t.reasons)} |`);F.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(N.map(t=>t.name))].join(` `)}'`,"```"),t.some(t=>t.ev===`unserved`&&(t.cls===`blocked`||t.cls===`deleted`))&&F.push(``,"A `blocked` or `deleted` version is a spent number: re-running the release cannot serve it, the package needs a version bump.")}return F.join(`
|
|
1189
|
+
`)}var hU,gU,holdsPublish,_U=__esmMin(()=>{Md(),fU(),lU(),mU(),hU=3e5,gU=1,holdsPublish=t=>t.block===dU});function beginPrompt(){vU++}function endPrompt(t=defaultWrite){if(vU=Math.max(0,vU-1),vU>0||yU.length===0)return;let n=yU.splice(0,yU.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(vU>0){yU.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var vU,yU,bU=__esmMin(()=>{vU=0,yU=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
|
|
1188
1190
|
`?{buf:t,echo:`
|
|
1189
|
-
`,done:!0,interrupt:!1}:n===
|
|
1190
|
-
`,done:!1,interrupt:!0}:n===
|
|
1191
|
-
Enter OTP: `,
|
|
1192
|
-
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?
|
|
1193
|
-
`)}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=xn(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(()=>(Md(),Ad))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Md(),Ad))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=xn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(Md(),Ad));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(LI(),II)),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 wU,TU=__esmMin(()=>{_e(),Md(),Dg(),jn(),cH(),Jm(),Xm(),eU(),nU(),rU(),cU(),uU(),aR(),CU(),_U(),wU={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:oU/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(`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=vn(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;if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=xn(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)??Vm;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 re=!!(process.stdin.isTTY&&process.stdout.isTTY),ie=await loadNpmrc(n),ae;try{ae=JSON.parse(readFileSync(xn(n,`package.json`),`utf-8`)).name}catch{}let oe=process.env.npm_config_registry??(ae?registryFor(ae,ie):void 0)??ie.registry??Vm,Q=new OtpProvider(N,re?promptLine:async()=>``,{registry:oe});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:Q,seedOtpFirst:N!==void 0,verifyBudgetMs:W}),t.json===!0,q)}}}),EU,DU=__esmMin(()=>{Jm(),aR(),EU={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 ${Vm}).`,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??Vm,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(`
|
|
1191
|
+
`,done:!0,interrupt:!1}:n===xU?{buf:t,echo:`
|
|
1192
|
+
`,done:!1,interrupt:!0}:n===SU||n===CU?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 xU,SU,CU,wU=__esmMin(()=>{bU(),xU=``,SU=``,CU=`\b`});function isOtpCacheEnabled(){let t=process.env[TU];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 xn(n&&n.length>0?n:tmpdir(),EU)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return xn(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 TU,EU,DU=__esmMin(()=>{Md(),Dg(),jn(),TU=`GJSIFY_NO_OTP_CACHE`,EU=`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 OU,kU,OtpProvider,AU=__esmMin(()=>{wU(),DU(),OU=`This operation requires a one-time password.
|
|
1193
|
+
Enter OTP: `,kU=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
|
|
1194
|
+
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?kU:OU));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))}}});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(xn(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)??Vm,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),doPut=t=>{let n={...le};return t&&(n[`npm-otp`]=t,n[`npm-auth-type`]=`legacy`),fetch(Q,{method:`PUT`,headers:n,body:he})},_e=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${_e.status} ${_e.statusText}`);let t=await _e.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(!(n<=0))return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:n,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(_e))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:_e.status};if(_e.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:_e.status,putStatusText:_e.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)})}:{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 ve=await _e.text().catch(()=>`<no body>`);if((_e.status===409||_e.status===403&&/previously published/i.test(ve))&&F){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:_e.status,putStatusText:_e.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)})}:{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:_e.status,registry:oe,readback:t}}if(_e.status===404&&me===`token`&&is404DiagnosticCandidate(ve)){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:_e.status,statusText:_e.statusText,text:ve}}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
|
|
1195
|
+
`)}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=xn(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(()=>(Md(),Ad))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Md(),Ad))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=xn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(Md(),Ad));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(RI(),LI)),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 jU,MU=__esmMin(()=>{_e(),Md(),Dg(),jn(),lH(),Jm(),Xm(),tU(),rU(),iU(),lU(),fU(),_U(),mU(),oR(),AU(),wU(),jU={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:sU/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:hU/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(`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=vn(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;if(t[`report-ledger`]===!0){let n=renderLedgerSummary(readLedger(process.env.GJSIFY_PUBLISH_LEDGER),t.ref??`<tag>`);n&&process.stdout.write(`${n}\n`);return}let re=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(re)||re<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=xn(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)??Vm;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 ie=!!(process.stdin.isTTY&&process.stdout.isTTY),ae=await loadNpmrc(n),oe;try{oe=JSON.parse(readFileSync(xn(n,`package.json`),`utf-8`)).name}catch{}let Q=process.env.npm_config_registry??(oe?registryFor(oe,ae):void 0)??ae.registry??Vm,se=new OtpProvider(N,ie?promptLine:async()=>``,{registry:Q});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:se,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.round(re*1e3)}),t.json===!0,q)}}}),NU,PU=__esmMin(()=>{Jm(),oR(),NU={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 ${Vm}).`,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??Vm,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(`
|
|
1194
1196
|
`)+`
|
|
1195
1197
|
`),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(`
|
|
1196
1198
|
`)+`
|
|
@@ -1199,12 +1201,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
|
|
|
1199
1201
|
`)+`
|
|
1200
1202
|
`),S}function removeAuthToken(t){let n=userconfigNpmrcPath(),S=authTokenKey(t),C=readUserconfig(n);if(!C)return{path:n,removed:!1};let N=C.split(`
|
|
1201
1203
|
`),F=N.filter(t=>!t.replace(/\s+/g,``).startsWith(`${S}=`)),I=F.length!==N.length;return I&&writeUserconfig(n,F.join(`
|
|
1202
|
-
`)),{path:n,removed:I}}var
|
|
1203
|
-
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,
|
|
1204
|
-
`)[0].slice(0,200)}var
|
|
1204
|
+
`)),{path:n,removed:I}}var FU=__esmMin(()=>{Md(),Dg(),jn()});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)??Vm,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.
|
|
1205
|
+
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,IU,LU=__esmMin(()=>{_e(),Jm(),oR(),FU(),wU(),DU(),LoginError=class extends Error{constructor(t){super(t),this.name=`LoginError`}},IU={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: ${Vm} (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}}}}),RU,zU=__esmMin(()=>{Jm(),oR(),FU(),DU(),RU={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: ${Vm} (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)??Vm,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=BU[0];for(let t=0;t<8&&!existsSync(xn(n,...S));t++){let t=wn(n);if(t===n)return[];n=t}let C=[];for(let t of BU){let S=xn(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=xn(S,n.name),F=xn(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:xn(...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 BU,VU=__esmMin(()=>{Md(),jn(),BU=[[`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:[HU]}]}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 HU,UU=__esmMin(()=>{Xm(),HU=`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(`
|
|
1206
|
+
`)[0].slice(0,200)}var WU,GU=__esmMin(()=>{_e(),w_(),Md(),jn(),Jm(),OP(),VU(),oR(),AU(),UU(),WU={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 ${Vm}).`,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??Vm;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.
|
|
1205
1207
|
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=xn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??Vm,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);process.exit(1)}}}}});function resolveRepoRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,encoding:`utf8`});if(S.status===0){let t=S.stdout.trim();if(t&&existsSync(t))return t}return t}function assertEveryPatternMatches(t,n){let S=n.filter(n=>{try{return discoverWorkspaces(t,{patterns:[n]}).length===0}catch{return!0}});if(S.length===0)return;let C=[`gjsify onboard: --packages matched no package directory (${S.length} of ${n.length} pattern(s)) under ${t}:`];for(let t of S)C.push(` ${JSON.stringify(t)}`);throw C.push(" Patterns are DIRECTORY globs resolved against the repo root, and only `*` is supported",` (one path segment). A matched directory needs a package.json with a "name".`),Error(C.join(`
|
|
1206
1208
|
`))}function collectOnboardPackages(t,n,S={}){let C=[],N=[],F=new Set,take=(t,n,S)=>{let I=0;for(let t of n)!t.name||F.has(t.name)||(F.add(t.name),N.push(t),I++);C.push({kind:t,patterns:S,count:I})};if(existsSync(xn(t,`package.json`)))try{take(`workspaces`,discoverWorkspaces(t,{includeRoot:!0}))}catch{}return S.patterns&&S.patterns.length>0&&take(`packages`,discoverWorkspaces(t,{patterns:[...S.patterns]}),S.patterns),take(`scanned-dirs`,mergePublishables([],n)),{packages:N,sources:C}}function describeSources(t){return t.filter(t=>t.count>0).map(t=>t.patterns?`${t.kind}(${t.patterns.join(`,`)})=${t.count}`:`${t.kind}=${t.count}`).join(` + `)}function declaredRepository(t){let n=t.manifest.repository,S=typeof n==`string`?n:n?.url;return typeof S!=`string`||S.length===0?null:parseRepoFromGitRemote(S)}function assertRepositoryAgreement(t,n){let S=n.toLowerCase(),C=t.map(t=>({ws:t,declared:declaredRepository(t)})).filter(t=>t.declared!==null&&t.declared.toLowerCase()!==S);if(C.length===0)return;let N=new Map;for(let{ws:t,declared:n}of C){let S=N.get(n)??[];S.push(t.name),N.set(n,S)}let F=[`gjsify onboard: ${C.length} selected package(s) declare a DIFFERENT repository than ${n}:`];for(let[t,n]of N){let S=n.slice(0,5).join(`, `),C=n.length>5?`, … (+${n.length-5} more)`:``;F.push(` ${t}: ${n.length} package(s) — ${S}${C}`)}throw F.push(` A Trusted Publisher scoped to the wrong repository points that package's OIDC exchange`,` at a workflow that does not publish it, which breaks the release this sweep protects.`,` Either exclude them (--exclude), select only what belongs here (--include), or point`,` --repository at the repo that actually publishes them.`),Error(F.join(`
|
|
1207
|
-
`))}var zU=__esmMin(()=>{Md(),w_(),DP(),jn(),PU(),IU(),kP()});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,BU),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)??Vm,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 BU,RateLimitGate,VU=__esmMin(()=>{Jm(),IU(),BU=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`error`:return`HTTP ${t.status} ${t.statusText}`;default:return`unknown`}}var HU,UU,WU=__esmMin(()=>{_e(),w_(),Jm(),DP(),aR(),CU(),pU(),TU(),RU(),AU(),qL(),j_(),zU(),IU(),VU(),HU=4,UU={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 ${Vm}).`,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:HU}).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??Vm,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?fn:un}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,KU,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${KU}`,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`&&GU.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 GU,KU,qU=__esmMin(()=>{jn(),GU=[`/usr/`,`/opt/`,`/snap/`],KU=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?fn:un,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${JU}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return wn(vn(t));let n=fileURLToPath(import.meta.url),S=wn(vn(n));for(let t=0;t<8&&S!==wn(S);t++){if(existsSync(xn(S,`package.json`)))return S;S=wn(S)}return wn(vn(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===JU&&typeof n.version==`string`?n.version:null}let n=wn(vn(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==wn(n);t++){let t=xn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===JU&&typeof n.version==`string`)return n.version}n=wn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var JU,YU,XU,ZU=__esmMin(()=>{_e(),Md(),jn(),Hn(),Jm(),CL(),qU(),DL(),jL(),cL(),uL(),JU=`@gjsify/cli`,YU={command:`self-update`,description:`Update the installed ${JU} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=xn(xn(n.prefix,`node_modules`,JU),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${JU}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`),ge.log(`Fetching dist-tags for ${JU}@${t.tag} ...`);let I;try{I=await fetchPackument(JU)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let H=resolveTag(I,t.tag);if(!H)return ge.error(`Unknown dist-tag '${t.tag}' on ${JU}. Known tags: ${Object.keys(I[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${t.tag}: v${H}`);let W=N&&!hasBundlerEngineInstalled(n.prefix),q=W&&!t.skipDeps&&!t.check;if(C===H&&!t.force&&!q){ge.log(`Already up to date (v${H}).`),W&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(q&&C===H&&!t.force&&ge.log(`@gjsify/cli is at v${H} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${H}`:`Install required: → v${H}`),process.exit(1);let Y=!t.skipDeps,X=Y?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${JU}@${H}${X} ...`);let Z=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${JU}@${H}`],verbose:!1,skipDeps:!Y,progress:Z})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Y&&await installGjsEnginePackages(n.prefix,H,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let te=linkGlobalBins([JU],n);if(te.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of te)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:XU,binDir:n.binDir,resolvedBin:resolveBinOnPath(XU,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:H});if(!t.ok)return ge.error(`\nInstalled ${JU} v${H} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${JU} to v${H}.`),Y?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},XU=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1209
|
+
`))}var KU=__esmMin(()=>{Md(),w_(),OP(),jn(),VU(),UU(),AP()});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,qU),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)??Vm,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 qU,RateLimitGate,JU=__esmMin(()=>{Jm(),UU(),qU=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`error`:return`HTTP ${t.status} ${t.statusText}`;default:return`unknown`}}var YU,XU,ZU=__esmMin(()=>{_e(),w_(),Jm(),OP(),oR(),AU(),bU(),MU(),GU(),LU(),JL(),j_(),KU(),UU(),JU(),YU=4,XU={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 ${Vm}).`,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:YU}).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??Vm,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?fn:un}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,$U,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${$U}`,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`&&QU.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 QU,$U,eW=__esmMin(()=>{jn(),QU=[`/usr/`,`/opt/`,`/snap/`],$U=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?fn:un,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${tW}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return wn(vn(t));let n=fileURLToPath(import.meta.url),S=wn(vn(n));for(let t=0;t<8&&S!==wn(S);t++){if(existsSync(xn(S,`package.json`)))return S;S=wn(S)}return wn(vn(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===tW&&typeof n.version==`string`?n.version:null}let n=wn(vn(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==wn(n);t++){let t=xn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===tW&&typeof n.version==`string`)return n.version}n=wn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var tW,nW,rW,iW=__esmMin(()=>{_e(),Md(),jn(),Hn(),Jm(),wL(),eW(),OL(),ML(),lL(),dL(),tW=`@gjsify/cli`,nW={command:`self-update`,description:`Update the installed ${tW} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=xn(xn(n.prefix,`node_modules`,tW),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${tW}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`),ge.log(`Fetching dist-tags for ${tW}@${t.tag} ...`);let I;try{I=await fetchPackument(tW)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let H=resolveTag(I,t.tag);if(!H)return ge.error(`Unknown dist-tag '${t.tag}' on ${tW}. Known tags: ${Object.keys(I[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${t.tag}: v${H}`);let W=N&&!hasBundlerEngineInstalled(n.prefix),q=W&&!t.skipDeps&&!t.check;if(C===H&&!t.force&&!q){ge.log(`Already up to date (v${H}).`),W&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(q&&C===H&&!t.force&&ge.log(`@gjsify/cli is at v${H} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${H}`:`Install required: → v${H}`),process.exit(1);let Y=!t.skipDeps,X=Y?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${tW}@${H}${X} ...`);let Z=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${tW}@${H}`],verbose:!1,skipDeps:!Y,progress:Z})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Y&&await installGjsEnginePackages(n.prefix,H,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let te=linkGlobalBins([tW],n);if(te.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of te)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:rW,binDir:n.binDir,resolvedBin:resolveBinOnPath(rW,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:H});if(!t.ok)return ge.error(`\nInstalled ${tW} v${H} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${tW} to v${H}.`),Y?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},rW=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1208
1210
|
/**
|
|
1209
1211
|
* gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
|
|
1210
1212
|
* on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
|
|
@@ -1729,28 +1731,28 @@ async function main() {
|
|
|
1729
1731
|
}
|
|
1730
1732
|
|
|
1731
1733
|
await main();
|
|
1732
|
-
`}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
|
|
1733
|
-
`).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
|
|
1734
|
+
`}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 aW,oW,sW=__esmMin(()=>{_e(),Md(),jn(),aW=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,oW={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:t=>t.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:t=>{let n=vn(process.cwd(),t.output);if(existsSync(n)&&!t.force)return ge.error(`${t.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let S=vn(process.cwd(),`package.json`),C=null;if(existsSync(S))try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{}let N=t.target??C?.name;if(!N)return ge.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let F=t[`bin-name`]??pickDefaultBinName(C,N),I=t[`bootstrap-url`]??aW;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`)}}}),cW,lW=__esmMin(()=>{_e(),Md(),YI(),OL(),lL(),dL(),cW={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:t=>t.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async t=>{let n=t.global?defaultGlobalLayout():null,S=n?n.prefix:process.cwd();if(!existsSync(`${S}/node_modules`)){ge.log(`gjsify prune: nothing installed at ${S}`);return}let C=resolveHostPlatform({env:{...t.os?{npm_config_os:t.os}:{},...t.cpu?{npm_config_cpu:t.cpu}:{},...t.libc?{npm_config_libc:t.libc}:{}}}),N=await acquireInstallLock(S,{}),F;try{F=executePrune(planPrune({prefix:S,target:C}),{dryRun:t.dryRun})}finally{N.release()}if(ge.log(formatPruneReport(F,{dryRun:t.dryRun,verbose:t.verbose})),F.failed.length>0)return process.exit(1)}}});function isInside(t,n){let S=Sn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${On}`)&&!bn(S)}function findBinShimsForPackage(t,n,S){if(!existsSync(t))return[];let C=[],N;try{N=readdirSync(t)}catch{return[]}for(let F of N){let N=xn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
|
|
1735
|
+
`).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 uW,dW=__esmMin(()=>{_e(),Md(),jn(),OL(),uW={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:t=>t.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:t=>{if(!t.global)return ge.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let n=defaultGlobalLayout(),S=t[`dry-run`]??!1,C=t.verbose??!1,N=`gjsify uninstall${S?` (dry-run)`:``} --global`;ge.log(`${N} ← ${n.prefix}`),ge.log(`${` `.repeat(N.length)} bins ← ${n.binDir}`);let F=!1;for(let N of t.packages){let t=specToPackageName(N),I=xn(n.prefix,`node_modules`,t);if(!existsSync(I)){ge.warn(` ✗ ${t} — not installed at ${I}`);continue}let H=findBinShimsForPackage(n.binDir,I,C);if(S){ge.log(` • would remove ${I}`);for(let t of H)ge.log(` • would remove ${t}`)}else{rmSync(I,{recursive:!0,force:!0}),ge.log(` • removed ${I}`);for(let t of H)unlinkSync(t),ge.log(` • removed ${t}`)}F=!0}F||(ge.error(`
|
|
1734
1736
|
No packages removed.`),process.exit(1))}}});function globToRegexSource(t){let n=``,S=0;for(;S<t.length;){let C=t[S];if(C===`*`&&t[S+1]===`*`&&(S===0||t[S-1]===`/`)){if(S+2===t.length){n+=`.*`,S+=2;continue}if(t[S+2]===`/`){n+=`(?:.*/)?`,S+=3;continue}}if(C===`*`)for(n+=`[^/]*`;t[S+1]===`*`;)S++;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=findClassEnd(t,S);if(C===-1)n+=`\\[`;else{let N=t.slice(S+1,C),F=!1;(N.startsWith(`!`)||N.startsWith(`^`))&&(F=!0,N=N.slice(1)),N=N.replace(/\]/g,`\\]`),n+=`[${F?`^/`:``}${N}]`,S=C}}else C===`\\`&&S+1<t.length?(S++,n+=escapeRegex(t[S])):n+=escapeRegex(C);S++}return n}function findClassEnd(t,n){let S=n+1;for((t[S]===`!`||t[S]===`^`)&&S++,t[S]===`]`&&S++;S<t.length;S++)if(t[S]===`]`)return S;return-1}function escapeRegex(t){return/[.+^${}()|[\]\\*?]/.test(t)?`\\${t}`:t}function parseLine(t){let n=t.replace(/\r$/,``);if(n=n.replace(/(?<!\\)\s+$/,``),n===``||n.startsWith(`#`))return null;let S=!1;n.startsWith(`!`)?(S=!0,n=n.slice(1)):(n.startsWith(`\\!`)||n.startsWith(`\\#`))&&(n=n.slice(1));let C=!1;if(n.endsWith(`/`)&&!n.endsWith(`\\/`)&&(C=!0,n=n.slice(0,-1)),n===``)return null;let N=n.includes(`/`);n.startsWith(`/`)&&(n=n.slice(1));let F=globToRegexSource(n);return{re:RegExp(`^${N?``:`(?:.*/)?`}${F}$`),negate:S,dirOnly:C}}function compileGitignore(t,n){let S=[];for(let n of t){let t=parseLine(n);t&&S.push(t)}let relOf=t=>{let S=Sn(n,t);return S===``||S===`..`||S.startsWith(`..${On}`)||bn(S)?null:On===`/`?S:S.split(On).join(`/`)},decide=(t,n)=>{for(let C=S.length-1;C>=0;C--){let N=S[C];if(!(N.dirOnly&&!n)&&N.re.test(t))return N.negate?`whitelist`:`ignore`}return null};return{base:n,matched(t,n){if(S.length===0)return null;let C=relOf(t);return C===null?null:decide(C,n)},matchedPathOrAnyParents(t,n){if(S.length===0)return null;let C=relOf(t);if(C===null)return null;let N=n;for(;;){let t=decide(C,N);if(t!==null)return t;let n=C.lastIndexOf(`/`);if(n===-1)return null;C=C.slice(0,n),N=!0}}}}function readGitignoreFile(t,n=wn(t)){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}return compileGitignore(S.split(`
|
|
1735
|
-
`),n)}var
|
|
1736
|
-
`,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,
|
|
1737
|
-
`);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}}}}),
|
|
1738
|
-
[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
|
|
1739
|
-
Select upgrades: comma- or space-separated indices, `+
|
|
1737
|
+
`),n)}var fW=__esmMin(()=>{Md(),jn()});function externalParserFor(t,n=!1){if(hW.has(t))return null;let S=$(t).slice(1),C=mW[t]??(S?pW[S]:void 0)??null;return C===`svelte`&&!n?null:C}function scanForNativeSkips(t,n=process.cwd(),S={}){let C=[],N=0,F=t.filter(t=>t.startsWith(`!`)).map(t=>t.slice(1)),I=[],H=readGitignoreFile(xn(n,`.prettierignore`));H&&I.push(H),F.length&&I.push(compileGitignore(F,n));let globallyIgnored=(t,n,S)=>I.some(C=>(S?C.matchedPathOrAnyParents(t,n):C.matched(t,n))===`ignore`),W=S.configPath?vn(n,S.configPath):null,q=loadScope(W??discoverConfig(n)),Y=W===null,scopeFor=t=>Y?nearestScope(t,q):q,expandBraces=t=>{let n=/\{([^{}]*)\}/.exec(t);return n?n[1].split(`,`).flatMap(S=>expandBraces(t.slice(0,n.index)+S+t.slice(n.index+n[0].length))):[t]},X=[],Z=new Set;for(let S of t){if(S.startsWith(`!`))continue;let t=vn(n,S);if(/[*?[{]/.test(S)&&!existsSync(t))for(let t of expandBraces(S))X.push(RegExp(`^${globToRegexSource(t.includes(`/`)?t:`**/${t}`)}$`));else Z.add(t)}(X.length||Z.size===0)&&Z.add(vn(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Tn(t),n?.svelte)&&C.push(t))},te=[];for(let t of Z){let n;try{n=statSync(t)}catch{continue}globallyIgnored(t,n.isDirectory(),!0)||(n.isDirectory()?te.push(t):n.isFile()&&record(t,scopeFor(wn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Sn(n,t).split(On).join(`/`);return X.some(t=>t.test(S))},ne=new Set,walk=(t,n,S)=>{if(ne.has(t))return;ne.add(t);let C=readGitignoreFile(xn(t,`.gitignore`)),N=C?[C,...n]:n;Y&&t!==S?.dir&&(S=scopeAt(t)??S);let F;try{F=readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of F){let C=xn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(gW.has(n.name)||n.name===`node_modules`)||globallyIgnored(C,F,!1)||gitIgnored(N,C,F)||(F?walk(C,N,S):matchesGlob(C)&&record(C,S))}},re=te.every(t=>repoRootOf(t)!==null);for(let t of te)walk(t,parentGitignores(t,re?repoRootOf(t):null,re),scopeFor(t));return{skipped:C,total:N}}function gitIgnored(t,n,S){for(let C of t){let t=C.matched(n,S);if(t!==null)return t===`ignore`}return!1}function parentGitignores(t,n,S){if(S&&n===null)return[];let C=[];for(let S=t;S!==n;){let t=wn(S);if(t===S)break;S=t;let n=readGitignoreFile(xn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(xn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=wn(n)){if(existsSync(xn(n,`.git`))||existsSync(xn(n,`.jj`)))return n;if(wn(n)===n)return null}}function configIn(t){for(let n of _W){let S=xn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=vn(t);;n=wn(n)){let t=configIn(n);if(t)return t;if(wn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=wn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(wn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=wn(t),S={};try{S=parseJsonc(readFileSync(t,`utf-8`))}catch{S={}}let C=Array.isArray(S.ignorePatterns)?S.ignorePatterns.filter(t=>typeof t==`string`):[];return{dir:n,ignore:C.length?compileGitignore(C,n):null,svelte:S.svelte!==void 0&&S.svelte!==null&&S.svelte!==!1}}function parseJsonc(t){let pass=(t,n)=>{let S=``;for(let C=0;C<t.length;){if(t[C]===`"`){let n=C+1;for(;n<t.length&&t[n]!==`"`;)n+=t[n]===`\\`?2:1;S+=t.slice(C,n+1),C=n+1;continue}let N=n(t,C);N>0?C+=N:S+=t[C++]}return S},n=pass(t,(t,n)=>{if(t.startsWith(`//`,n)){let S=t.indexOf(`
|
|
1738
|
+
`,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,pW,mW,hW,gW,_W,vW=__esmMin(()=>{Md(),jn(),fW(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),pW={...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`},mW={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},hW=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`]),gW=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),_W=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=vn(t,S);if(existsSync(N)&&!n){ge.log(`[gjsify format] ${S} exists at ${N} — pass --force to overwrite.`);return}writeFileSync(N,C,`utf-8`),ge.log(`[gjsify format] wrote ${N}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ge.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var yW,bW=__esmMin(()=>{_e(),Md(),jn(),ZR(),vW(),yW={command:`format [paths..]`,description:`Format source files via oxfmt (Markdown/YAML/HTML/Vue need the napi build).`,builder:t=>t.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();if(t.init){handleInit({cwd:n,force:t.force??!1});return}let S=t.paths?.length?t.paths:[`.`],C=[];t.check?C.push(`--check`):t.write===!1?C.push(`--list-different`):C.push(`--write`);let N=t.configPath??findOxfmtConfig(n)??void 0;if(N&&C.push(`--config`,vn(N)),C.push(...S),t.check&&await shouldUseNativeOxfmt()){let t=scanForNativeSkips(S,n,{configPath:N});if(t.skipped.length>0){let S=t.skipped.map(t=>` ${Sn(n,t)||t}`).join(`
|
|
1739
|
+
`);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}}}}),xW,SW=__esmMin(()=>{jn(),ZR(),xW={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:t=>t.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=[];t.fix&&C.push(`--fix`);let N=t.configPath??findOxlintConfig(n)??void 0;N&&C.push(`--config`,vn(N)),C.push(...S);try{setOxcExitCode(await runOxlint(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),CW,wW=__esmMin(()=>{jn(),ZR(),CW={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:t=>t.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=t.verbose??!1,N=t.write!==!1;try{let F=[N?`--write`:`--list-different`],I=t.configPath??findOxfmtConfig(n)??void 0;I&&F.push(`--config`,vn(I)),F.push(...S);let H=await runOxfmt(F,{cwd:n,verbose:C}),W=[];N&&W.push(`--fix`);let q=t.configPath??findOxlintConfig(n)??void 0;q&&W.push(`--config`,vn(q)),W.push(...S);let Y=await runOxlint(W,{cwd:n,verbose:C});setOxcExitCode(H||Y)}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}});function createInterface(t,n){return typeof t==`object`&&t&&!(`read`in t&&typeof t.read==`function`)?new Interface(t):new Interface({input:t,output:n})}var Interface,TW=__esmMin(()=>{wd(),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 EW=__esmMin(()=>{EP()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=xn(t,`package.json`);if(!existsSync(S))throw Error(`[gjsify upgrade] no package.json at ${S}`);let C=JSON.parse(readFileSync(S,`utf-8`));return{root:t,workspaces:[{name:C.name??`<root>`,location:t,relativeLocation:`.`,version:C.version??`0.0.0`,manifest:C,private:C.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(t,n,S){let C=n?.split(`,`).map(t=>t.trim()).filter(Boolean),N=S?.split(`,`).map(t=>t.trim()).filter(Boolean);return(!C||C.length===0)&&(!N||N.length===0)?t:filterWorkspaces(t,{include:C,exclude:N})}function parseFilterList(t){return t?t.split(`,`).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(t,n){let S=[];for(let C of t)for(let t of collectFromWorkspace(C,n))S.push(t);return S}function collectFromWorkspace(t,n){let S=[],C=t.manifest;for(let N of OW){let F=C[N];if(!(!F||typeof F!=`object`))for(let[C,I]of Object.entries(F)){if(typeof I!=`string`||n.length&&!n.some(t=>C.toLowerCase().includes(t))||I.startsWith(`workspace:`)||I.startsWith(`file:`)||I.startsWith(`link:`)||I.startsWith(`git+`)||I.startsWith(`git:`)||I.startsWith(`http:`)||I.startsWith(`https:`)||I.startsWith(`npm:`)||I.startsWith(`portal:`))continue;let{prefix:F,version:H}=splitRange(I);S.push({workspace:t.name,workspaceLocation:t.location,name:C,field:N,currentRange:I,currentVersion:H,prefix:F})}}return S}function splitRange(t){let n=t.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!n)return{prefix:``,version:null};let S=n[1]??``,C=n[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:S,version:(C?parse(C):null)?.version??null}}function reportInexactRanges(t){let n=t.map(t=>({name:t.name,loose:t.occurrences.filter(t=>t.prefix!==``)})).filter(t=>t.loose.length>0);if(n.length===0)return 0;let S=n.reduce((t,n)=>t+n.loose.length,0);ge.error(`gjsify upgrade --check --exact: FAIL. ${S} declaration(s) across ${n.length} dep(s) carry a range operator:\n`);for(let t of n){let n=new Map;for(let S of t.loose){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${kW.bold}${t.name}${kW.reset}`);for(let[t,S]of n.entries()){let n=S.length>6?`${S.slice(0,6).join(`, `)} … +${S.length-6}`:S.join(`, `);ge.error(` ${t.padEnd(16)} — ${n}`)}}return S}function checkLockfileRangeViolations(t,n){let S=xn(n,`gjsify-lock.json`);if(!existsSync(S))return 0;let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{return 0}if(!C.packages)return 0;let N=new Map;for(let n of t){let t=N.get(n.name)??new Set;for(let S of n.occurrences)t.add(S.currentRange);N.set(n.name,t)}let F=0;for(let[t,n]of Object.entries(C.packages)){if(!n.version)continue;let S=t.split(`node_modules/`);if(S.length!==2)continue;let C=S[1],I=N.get(C);if(!I||I.size===0)continue;let H=!1;for(let t of I)try{if(n.version&&satisfies(n.version,t)){H=!0;break}}catch{}H||(ge.error(` ${C}: lockfile has ${n.version}, but declared ranges are ${[...I].join(`, `)}`),F++)}return F>0&&ge.error(`gjsify upgrade --check: FAIL. ${F} lockfile entr${F===1?`y`:`ies`} violate declared ranges:\n`),F}function runCheckMode(t,n=!1,S=process.cwd()){checkLockfileRangeViolations(t,S);let C=n?reportInexactRanges(t):0,N=findInconsistencies(t);if(N.length===0&&C>0)return ge.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ge.log(`gjsify upgrade --check: OK. ${t.length} dep(s) consistently declared across workspaces`+(n?`, every declaration pinned exactly.`:`.`));return}ge.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let t of N){let n=new Map;for(let S of t.occurrences){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${kW.bold}${t.name}${kW.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(` ${kW.bold}${n.name}${kW.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(`
|
|
1740
|
+
[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 kW.red;case`minor`:return kW.yellow;case`patch`:return kW.green;case`prerelease`:return kW.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)+kW.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+kW.reset;ge.log(I),ge.log(` `.repeat(F+2)+kW.dim+`─`.repeat(n+S+C+N+16)+kW.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${kW.magenta}⚠ ${kW.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+kW.dim+`${H.occurrences.length}`.padEnd(S)+kW.reset+` `+kW.dim+renderDeclaredCell(H).padEnd(C)+kW.reset+` `+Y+H.latestVersion.padEnd(N)+kW.reset+` `+Y+H.diff+kW.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${kW.magenta}⚠${kW.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(`
|
|
1741
|
+
Select upgrades: comma- or space-separated indices, `+kW.bold+`a`+kW.reset+` for all, ranges like `+kW.bold+`1-3`+kW.reset+`, or `+kW.bold+`ENTER`+kW.reset+` to skip:`);let S=(await n.question(`> `)).trim();if(!S)return[];if(S.toLowerCase()===`a`||S.toLowerCase()===`all`)return[...t];let C=new Set;for(let t of S.split(/[\s,]+/).filter(Boolean)){let n=t.match(/^(\d+)-(\d+)$/);if(n){let t=Number(n[1]),S=Number(n[2]);for(let n=Math.min(t,S);n<=Math.max(t,S);n++)C.add(n-1)}else/^\d+$/.test(t)&&C.add(Number(t)-1)}return[...C].filter(n=>n>=0&&n<t.length).map(n=>t[n])}finally{n.close()}}function targetRange(t,n,S){return S?n:`${t}${n}`}function applyToFiles(t,n=!1){let S=new Map;for(let n of t)for(let t of n.occurrences){let C=S.get(t.workspaceLocation)??[];C.push({...n,occurrences:[t]}),S.set(t.workspaceLocation,C)}let C=0;for(let[t,N]of S.entries()){let S=xn(t,`package.json`),F=readFileSync(S,`utf-8`),I=JSON.parse(F),H=!1,W=[];for(let t of N){let S=t.occurrences[0],C=I[S.field];if(!C)continue;let N=targetRange(S.prefix,t.latestVersion,n);C[t.name]!==N&&(C[t.name]=N,H=!0,W.push(t.name))}if(H){let t=detectIndent(F);writeFileSync(S,keepUntouchedLines(F,JSON.stringify(I,null,t)+(F.endsWith(`
|
|
1740
1742
|
`)?`
|
|
1741
1743
|
`:``),W),`utf-8`),C++}}return C}function keepUntouchedLines(t,n,S){let C=t.split(`
|
|
1742
1744
|
`),N=n.split(`
|
|
1743
1745
|
`);return C.length===N.length?N.map((t,n)=>S.some(n=>t.includes(`"${n}"`))?t:C[n]).join(`
|
|
1744
|
-
`):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:Vm,scopes:{},authTokens:{},basicAuth:{}};for(let S of[xn(homedir(),`.npmrc`),xn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var
|
|
1746
|
+
`):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:Vm,scopes:{},authTokens:{},basicAuth:{}};for(let S of[xn(homedir(),`.npmrc`),xn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var DW,OW,kW,AW=__esmMin(()=>{_e(),Md(),jn(),Dg(),TW(),EP(),Jm(),OP(),AP(),EW(),DW={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:t=>t.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:"Offline repair mode: find deps declared at multiple ranges across the workspace and align them to the highest. With `--exact`, also drop the range operator from declarations that already agree. No registry calls.",type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one; with `--align`, repairs exactly that. Pair with `--filter` — a repository-wide exactness run touches every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async t=>{let n=discoverContext(vn(t.cwd??process.cwd())),S=applyWorkspaceFilter(n.workspaces,t.workspace,t.excludeWorkspace);if(S.length===0){ge.log(`[gjsify upgrade] no matching workspaces.`);return}let C=collectAllDeclarations(S,parseFilterList(t.filter));if(C.length===0){ge.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let N=groupByDependency(C);if(t.check)return runCheckMode(N,t.exact);if(t.align)return runAlignMode(N,t);let F=await loadNpmrcLight(n.root),I=t.latest?`latest`:t.minor?`minor`:t.patch?`patch`:`interactive`;ge.log(`[gjsify upgrade] checking ${N.length} unique deps across ${S.length} workspace(s) against ${F.registry}…`);let H=await resolveCandidateGroups(N,F,t.verbose??!1,I);if(H.length===0){ge.log(`✅ all dependencies are up to date`);let t=findInconsistencies(N);t.length>0&&ge.log(`\n⚠ ${t.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(H);let W;if(I===`interactive`&&!t.yes?W=await promptSelection(H):(t.yes&&I===`interactive`&&ge.log(`[gjsify upgrade] -y / --yes: selecting all`),W=H),W.length===0){ge.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(t.dryRun){let n=uniqueLocations(W).length;ge.log(`[gjsify upgrade] --dry-run: would update ${W.length} deps across ${n} package.json file(s).`),printChangePlan(W,t.exact);return}let q=applyToFiles(W,t.exact);ge.log(`✏️ updated ${W.length} dep(s) across ${q} package.json file(s). Run \`gjsify install\` to apply.`)}},OW=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],kW={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function unscannableBarrelPaths(t,n){let S=[];for(let C of n){let n=vn(t,C);try{(await stat$1(n)).isDirectory()||S.push(`${n} is not a directory`)}catch(t){S.push(`${n}: ${t.message}`)}}return S}async function generateBarrels(t){let n=t.singleQuotes?`'`:`"`,S=t.noSemicolon?``:`;`,C=t.extension===`none`?``:`.${t.extension}`,N=0;for(let F of t.paths){let I=vn(t.baseDir,F),H=Tn(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>MW.test(t.name)).filter(t=>t.name!==`index.ts`).filter(n=>!t.exclude.some(t=>t.test(n.name))).sort((t,n)=>t.name.localeCompare(n.name))}catch(n){t.verbose&&ge.error(`[gjsify barrels] skip ${I}: ${n.message}`);continue}let q=W.map(t=>{let N=Tn(t.name,$(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
|
|
1745
1747
|
`)}\n`:`export {};
|
|
1746
|
-
`,X=`${t.header}\n\n${Y}`,Z=xn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var
|
|
1747
|
-
`).map(t=>t.trim()).filter(Boolean)}var
|
|
1748
|
+
`,X=`${t.header}\n\n${Y}`,Z=xn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var jW,MW,NW=__esmMin(()=>{_e(),hd(),jn(),jW=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],MW=/\.(ts|tsx|mts|cts)$/}),PW,FW=__esmMin(()=>{_e(),NW(),PW={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:[...jW],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)}}}),IW,LW=__esmMin(()=>{_e(),Al(),jn(),Hn(),$P(),JP(),Md(),LH(),xI(),AP(),j_(),IW={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:t=>t.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async t=>{let n=(t._??[]).slice(1).map(String),S=t.tscArgs??[],C=n.length>0?n:S,N=process.cwd(),F=[pathToFileURL(`${findWorkspaceRoot(N)??N}/__gjsify_tsc__.js`).href,import.meta.url],I;for(let t of F)try{I=createRequire(t).resolve(`@gjsify/tsc/bundle`);break}catch{}let H;for(let t of F)try{H=xn(wn(createRequire(t).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!I&&!H)return ge.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ge.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let W=buildNativeEnv(detectNativePackages(N)),q={...process.env,...W},runNodeTsc=async()=>{let t=nodeBinary();if(!(t.includes(`/`)||t.includes(`\\`)?existsSync(t):isOnPath(t)))return ge.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${t}\` cannot be run, so upstream \`typescript\` cannot run either.`),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ge.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((n,S)=>{spawnToCompletion(t,[H,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(S)})}catch(t){let n=t;return n.code===`ENOENT`?(ge.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ge.error(`gjsify tsc (node typescript): ${n.message}`),forceExit(1)}};if(I)try{await new Promise((t,n)=>{spawnToCompletion(`gjs`,[`-m`,I,...C],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(n)})}catch(t){let n=t;return n.code===`ENOENT`&&H?await runNodeTsc():(n.code===`ENOENT`?(ge.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ge.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ge.error(`gjsify tsc: ${n.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(t){return t.split(`
|
|
1749
|
+
`).map(t=>t.trim()).filter(Boolean)}var RW=__esmMin(()=>{Md()});function isResolvableScript(t){return UW.test(t)&&!zW.some(n=>n.test(t))&&!HW.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))BW.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)BW.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 zW)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 HW){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=>VW.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 zW,BW,VW,HW,UW,WW=__esmMin(()=>{OP(),zW=[/^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$/],BW=[/\.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$/],VW=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],HW=[{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`}],UW=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
|
|
1748
1750
|
`).filter(t=>!S.test(t)).join(`
|
|
1749
1751
|
`)}function scriptNamePattern(t){let n=un.basename(t),S=/^(.*?)(\.d)?\.[mc]?[jt]sx?$/.exec(n),C=S?`${escapeRe(S[1])}(\\.d)?\\.[mc]?[jt]sx?\\b`:`${escapeRe(n)}\\b`;return RegExp(`(^|[^\\w.-])${C}`)}function gatedJobs(t){let n=new Map,S=new Set;for(let{job:C,text:N}of t){if(!C)continue;n.has(C)||n.set(C,[]);let t=/^ {4}needs:\s*\[(.*)\]/.exec(N)??/^ {4}needs:\s*([A-Za-z0-9_-]+)\s*$/.exec(N);t&&n.set(C,t[1].split(`,`).map(t=>t.trim()).filter(Boolean)),(/needs\.changes\b/.test(N)||/^ {4}needs:\s*$/.test(N))&&S.add(C)}let C=new Set([`changes`,...S]),N=!0;for(;N;){N=!1;for(let[t,S]of n)!C.has(t)&&S.some(t=>C.has(t))&&(C.add(t),N=!0)}return C.delete(`changes`),C}function workflowLines(t){let n=t.split(`
|
|
1750
|
-
`),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===
|
|
1752
|
+
`),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===GW||S===KW||n.set(S,stripCommentLines(S,C));let S=t.get(GW),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(KW);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(JW.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(GW),manifestReads(S)&&C.push(KW),C.sort()}}function readTrackedTexts(t){let n=spawnSync(`git`,[`ls-files`,`-z`],{cwd:t,encoding:`utf8`});if(n.status!==0)throw Error(`git ls-files failed (${n.status}): ${String(n.stderr).trim()}`);let S=new Map;for(let C of n.stdout.split(`\0`)){if(!C||C.startsWith(`refs/`))continue;let n=xn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>qW)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var GW,KW,qW,JW,escapeRe,YW=__esmMin(()=>{w_(),Md(),jn(),GW=`.github/workflows/main.yml`,KW=`package.json`,qW=2*1024*1024,JW=/^(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(`
|
|
1751
1753
|
`).filter(Boolean)}function emit(t,n){if(t===`json`){process.stdout.write(JSON.stringify(n)+`
|
|
1752
1754
|
`);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:
|
|
1753
|
-
`),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(
|
|
1755
|
+
`),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(ZW.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 XW,ZW,QW=__esmMin(()=>{w_(),Md(),RW(),OP(),WW(),YW(),AP(),XW={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)}},ZW=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),$W=__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(()=>(xI(),bI));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(()=>(yI(),vI)),{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(()=>(xI(),bI));return spawnSupervised(t(),[n],I)}let[H,W]=N_[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=vn(t,S),N=vn(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=wn(N);return F===vn(t)?!1:C===F||C.startsWith(`${F}${On}`)}async function runWatchLoop(t){let{dir:n,label:S,prepare:C,build:N,spawnChild:F,output:I,ignore:H,debounceMs:W=200}=t;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{C&&await C(),q&&=(q.kill(),null),await N(),F&&(q=await F())}catch(t){ge.error(`[${S}] rebuild failed: ${t.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=(t.watch??[{path:n,recursive:!0}]).map(t=>watch(t.path,{recursive:t.recursive},(n,S)=>{let C=typeof S==`string`?S:null;isSelfWrite(t.path,I,C)||H&&C!==null&&H(vn(t.path,C))||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))}));holdMainLoop();let ne=!1,shutdown=()=>{if(!ne){ne=!0,Z&&clearTimeout(Z),q?.kill();for(let t of te)t.close();process.exit(0)}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ge.log(`[${S}] watching ${t.dirLabel??n} — press Ctrl+C to stop`)}var eG=__esmMin(()=>{_e(),Md(),jn(),Me(),PL(),j_(),P_()});function readPackage$4(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(t){let n=[];if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){if(S.name===`node_modules`||S.name.startsWith(`.`))continue;let C=xn(t,S.name);S.isDirectory()?n.push(...findStoryFiles(C)):/\.story\.(ts|js|mts|mjs)$/.test(S.name)&&n.push(C)}return n}function generateEntry$3(t,n,S){let C=t.map((t,n)=>`import * as m${n} from ${JSON.stringify(t)};`).join(`
|
|
1754
1756
|
`),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.
|
|
1755
1757
|
import { collectStoryModules, runStorybook } from '@gjsify/storybook';
|
|
1756
1758
|
${C}
|
|
@@ -1759,7 +1761,7 @@ await runStorybook({
|
|
|
1759
1761
|
applicationId: ${JSON.stringify(n)},${F}
|
|
1760
1762
|
stories: collectStoryModules([${N}]),
|
|
1761
1763
|
});
|
|
1762
|
-
`}var
|
|
1764
|
+
`}var tG,nG=__esmMin(()=>{_e(),Md(),jn(),t_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$3,`generateEntry`),tG={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=vn(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=xn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$3(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Sn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Sn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>($G(),QG)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(yI(),vI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(xI(),bI));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(xI(),bI));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(()=>(eG(),$W));await re({dir:N,dirLabel:Sn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??wn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var rG=__esmMin(()=>{jn(),zF()});function readPackage$3(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}var iG,aG=__esmMin(()=>{_e(),Md(),jn(),rG(),P_(),t_(),__name$1(readPackage$3,`readPackage`),iG={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:M_,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:vn(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=vn(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Sn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Sn(n,H);ge.log(`Watching ${Sn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>($G(),QG)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(eG(),$W));await X({dir:W,dirLabel:Sn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
|
|
1763
1765
|
import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
|
|
1764
1766
|
|
|
1765
1767
|
await runDevtoolsMcp(storybookProfile(${F}${I}));
|
|
@@ -1779,18 +1781,18 @@ await runDevtoolsMcp({
|
|
|
1779
1781
|
version: ${JSON.stringify(C)},
|
|
1780
1782
|
busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
|
|
1781
1783
|
});
|
|
1782
|
-
`}var
|
|
1784
|
+
`}var oG,sG=__esmMin(()=>{_e(),Md(),jn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),oG={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=xn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=xn(W,`entry.ts`),Y=t.out?vn(n,t.out):xn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>($G(),QG));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(()=>(yI(),vI));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
|
|
1783
1785
|
import system from 'system';
|
|
1784
1786
|
|
|
1785
1787
|
import { runDevtoolsCli } from '@gjsify/devtools-mcp';
|
|
1786
1788
|
|
|
1787
1789
|
system.exit(await runDevtoolsCli(system.programArgs));
|
|
1788
|
-
`}var
|
|
1790
|
+
`}var cG,lG=__esmMin(()=>{_e(),Md(),jn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),cG={command:`devtools`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=xn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=xn(F,`entry.ts`),H=t.out?vn(n,t.out):xn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>($G(),QG));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(()=>(yI(),vI));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(xn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
|
|
1789
1791
|
import { runBrowserDevtools } from '@gjsify/devtools-browser';
|
|
1790
1792
|
|
|
1791
1793
|
await runBrowserDevtools({
|
|
1792
1794
|
applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
|
|
1793
1795
|
});
|
|
1794
|
-
`}var rG,iG=__esmMin(()=>{_e(),Md(),jn(),rG={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=xn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?vn(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(KG(),GG));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(()=>(vI(),_I));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Tn(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Tn(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(xn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,xn(C,n));else for(let[n,S]of t.png)writeFileSync(xn(C,n),S)}var aG=__esmMin(()=>{Md(),jn(),Kz()});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(()=>(GF(),HF)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Tn(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=xn(wn(C),`manifest-${process.pid}-${++oG}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++oG}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(xn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(xn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(xn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var oG,sG=__esmMin(()=>{Md(),jn(),Hn(),t_(),__name$1(isRecord$1,`isRecord`),oG=0});function planPage(t,n,S){let C=wn(n),N=[],F=[],local=t=>{if(mG.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return bn(n)?n:vn(C,n)},I=S.replace(cG,n=>{let S=uG.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!hG.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:fG.test(n)?`esm`:`iife`,output:F}),n.replace(uG,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(lG,t=>{if(!pG.test(t))return t;let n=dG.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Tn(S);return F.push({source:S,output:C}),t.replace(dG,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var cG,lG,uG,dG,fG,pG,mG,hG,gG=__esmMin(()=>{jn(),cG=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,lG=/<link\b[^>]*>/gi,uG=/\bsrc\s*=\s*(["'])([^"']+)\1/i,dG=/\bhref\s*=\s*(["'])([^"']+)\1/i,fG=/\btype\s*=\s*["']module["']/i,pG=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,mG=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,hG=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=_G?n:_G}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=xn(S,C.name);C.isDirectory()?walk(N):n.push({path:Sn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=xn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:xn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:xn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,xn(H,t.output))}writeFileSync(xn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=xn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,xn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(xn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
|
|
1795
|
-
- `)}`);if(Z.folders.set(I.id,S),F(`built ${Sn(process.cwd(),S)||S}`),t.zip){let t=xn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Sn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var
|
|
1796
|
-
- `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var CG,wG,TG,EG=__esmMin(()=>{Md(),jn(),SG(),CG=[16,32,48,128],wG=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],TG=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return xn(S.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=wn(n)){let t=xn(n,`node_modules`,`.bin`);if(existsSync(xn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(kn)}};if(wn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var DG,OG=__esmMin(()=>{Md(),Dg(),jn(),qP(),SG(),DG="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(KG(),GG)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?vn(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=xn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+On)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var kG,AG,jG,MG,NG,PG,FG=__esmMin(()=>{_e(),Md(),jn(),vG(),EG(),OG(),kG={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},AG={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},jG={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},MG={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,kG).option(`out-dir`,AG).option(`define`,jG).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)},NG={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,kG).option(`out-dir`,AG).option(`define`,jG),handler:t=>runBuild(t,!0)},PG={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`,{...kG,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,jG).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?vn(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=xn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(DG);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?vn(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(wn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(qW(),KW));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(()=>(qW(),KW));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+On),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}}}),IG,LG=__esmMin(()=>{FG(),IG={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(MG.command,MG.description,MG.builder,MG.handler).command(NG.command,NG.description,NG.builder,NG.handler).command(PG.command,PG.description,PG.builder,PG.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())RG.has(S)||S.startsWith(`.`)||blueprintsUnder(xn(t,S),n);return n}var RG,zG,formatFor,BG,VG=__esmMin(()=>{_e(),Md(),jn(),xk(),Ok(),RG=new Set([`node_modules`,`dist`,`lib`,`.git`]),zG=new Map,formatFor=t=>{let n=zG.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return zG.set(t,S),S},BG={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>bn(t)?t:vn(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Tn(n),formatFor(wn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),HG,UG=__esmMin(()=>{VG(),HG={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(BG.command,BG.description,BG.builder,BG.handler).demandCommand(1).strict()}}),WG=__esmMin(()=>{XF(),QF(),tI(),aI(),SI(),TI(),FL(),LL(),zL(),YL(),cR(),ER(),kR(),NR(),IR(),wz(),FH(),iR(),VH(),WH(),YH(),qL(),eU(),TU(),DU(),AU(),MU(),RU(),WU(),ZU(),eW(),nW(),iW(),pW(),hW(),_W(),CW(),OW(),AW(),GW(),YW(),QW(),eG(),nG(),iG(),LG(),UG()}),GG=__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=Im(t);await n.scriptName(Zm).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(TR.command,TR.description,TR.builder,TR.handler).command(zH.command,zH.description,zH.builder,zH.handler).command(HH.command,HH.description,HH.builder,HH.handler).command(UH.command,UH.description,UH.builder,UH.handler).command(YF.command,YF.description,YF.builder,YF.handler).command(ZF.command,ZF.description,ZF.builder,ZF.handler).command(eI.command,eI.description,eI.builder,eI.handler).command(iI.command,iI.description,iI.builder,iI.handler).command(xI.command,xI.description,xI.builder,xI.handler).command(wI.command,wI.description,wI.builder,wI.handler).command(PL.command,PL.description,PL.builder,PL.handler).command(rR.command,rR.description,rR.builder,rR.handler).command(IL.command,IL.description,IL.builder,IL.handler).command(RL.command,RL.description,RL.builder,RL.handler).command(JL.command,JL.description,JL.builder,JL.handler).command(sR.command,sR.description,sR.builder,sR.handler).command(OR.command,OR.description,OR.builder,OR.handler).command(MR.command,MR.description,MR.builder,MR.handler).command(FR.command,FR.description,FR.builder,FR.handler).command(Cz.command,Cz.description,Cz.builder,Cz.handler).command(PH.command,PH.description,PH.builder,PH.handler).command(JH.command,JH.description,JH.builder,JH.handler).command(KL.command,KL.description,KL.builder,KL.handler).command(ZH.command,ZH.description,ZH.builder,ZH.handler).command(wU.command,wU.description,wU.builder,wU.handler).command(EU.command,EU.description,EU.builder,EU.handler).command(kU.command,kU.description,kU.builder,kU.handler).command(jU.command,jU.description,jU.builder,jU.handler).command(LU.command,LU.description,LU.builder,LU.handler).command(UU.command,UU.description,UU.builder,UU.handler).command(YU.command,YU.description,YU.builder,YU.handler).command($U.command,$U.description,$U.builder,$U.handler).command(rW.command,rW.description,rW.builder,rW.handler).command(tW.command,tW.description,tW.builder,tW.handler).command(bW.command,bW.description,bW.builder,bW.handler).command(fW.command,fW.description,fW.builder,fW.handler).command(mW.command,mW.description,mW.builder,mW.handler).command(gW.command,gW.description,gW.builder,gW.handler).command(DW.command,DW.description,DW.builder,DW.handler).command(kW.command,kW.description,kW.builder,kW.handler).command(UW.command,UW.description,UW.builder,UW.handler).command(JW.command,JW.description,JW.builder,JW.handler).command(ZW.command,ZW.description,ZW.builder,ZW.handler).command($W.command,$W.description,$W.builder,$W.handler).command(tG.command,tG.description,tG.builder,tG.handler).command(rG.command,rG.description,rG.builder,rG.handler).command(IG.command,IG.description,IG.builder,IG.handler).command(HG.command,HG.description,HG.builder,HG.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var KG=__esmMin(()=>{Lm(),Rm(),Xm(),WG(),Qm(),t_(),jL()});KG(),t_(),NL();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(),t_();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 qG=globalThis.process,JG=Number(qG?.exitCode);Number.isInteger(JG)&&JG!==0&&qG.exit(JG);
|
|
1796
|
+
`}var uG,dG=__esmMin(()=>{_e(),Md(),jn(),uG={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=xn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=xn(Y,`entry.ts`),Z=t.out?vn(n,t.out):xn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?vn(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>($G(),QG));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(()=>(yI(),vI));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Tn(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Tn(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(xn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,xn(C,n));else for(let[n,S]of t.png)writeFileSync(xn(C,n),S)}var fG=__esmMin(()=>{Md(),jn(),qz()});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(()=>(KF(),UF)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Tn(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=xn(wn(C),`manifest-${process.pid}-${++pG}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++pG}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(xn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(xn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(xn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var pG,mG=__esmMin(()=>{Md(),jn(),Hn(),t_(),__name$1(isRecord$1,`isRecord`),pG=0});function planPage(t,n,S){let C=wn(n),N=[],F=[],local=t=>{if(xG.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return bn(n)?n:vn(C,n)},I=S.replace(hG,n=>{let S=_G.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!SG.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:yG.test(n)?`esm`:`iife`,output:F}),n.replace(_G,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(gG,t=>{if(!bG.test(t))return t;let n=vG.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Tn(S);return F.push({source:S,output:C}),t.replace(vG,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var hG,gG,_G,vG,yG,bG,xG,SG,CG=__esmMin(()=>{jn(),hG=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,gG=/<link\b[^>]*>/gi,_G=/\bsrc\s*=\s*(["'])([^"']+)\1/i,vG=/\bhref\s*=\s*(["'])([^"']+)\1/i,yG=/\btype\s*=\s*["']module["']/i,bG=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,xG=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,SG=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=wG?n:wG}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=xn(S,C.name);C.isDirectory()?walk(N):n.push({path:Sn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=xn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:xn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:xn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,xn(H,t.output))}writeFileSync(xn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=xn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,xn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(xn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
|
|
1797
|
+
- `)}`);if(Z.folders.set(I.id,S),F(`built ${Sn(process.cwd(),S)||S}`),t.zip){let t=xn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Sn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var wG,TG=__esmMin(()=>{_e(),Md(),jn(),nH(),fG(),mG(),CG(),wG=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!EG.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${EG.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?OG.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 EG,DG,OG,kG=__esmMin(()=>{EG=[`chrome`,`edge`,`firefox`,`opera`,`safari`],DG=[`chrome-mv3`,`firefox-mv3`],OG=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>bn(t)?t:vn(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...DG];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=jG.find(t=>S(xn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${jG.join(`, `)} exists.`):W=xn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!MG.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??AG;(!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(!MG.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=xn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${xn(n,`package.json`)}:\n - ${C.join(`
|
|
1798
|
+
- `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var AG,jG,MG,NG=__esmMin(()=>{Md(),jn(),kG(),AG=[16,32,48,128],jG=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],MG=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return xn(S.XDG_CACHE_HOME||xn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=wn(n)){let t=xn(n,`node_modules`,`.bin`);if(existsSync(xn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(kn)}};if(wn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var PG,FG=__esmMin(()=>{Md(),Dg(),jn(),JP(),kG(),PG="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=xn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>($G(),QG)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?vn(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=xn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+On)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var IG,LG,RG,zG,BG,VG,HG=__esmMin(()=>{_e(),Md(),jn(),TG(),NG(),FG(),IG={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},LG={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},RG={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},zG={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,IG).option(`out-dir`,LG).option(`define`,RG).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)},BG={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,IG).option(`out-dir`,LG).option(`define`,RG),handler:t=>runBuild(t,!0)},VG={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`,{...IG,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,RG).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?vn(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=xn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(PG);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?vn(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(wn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(eG(),$W));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(()=>(eG(),$W));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+On),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}}}),UG,WG=__esmMin(()=>{HG(),UG={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(zG.command,zG.description,zG.builder,zG.handler).command(BG.command,BG.description,BG.builder,BG.handler).command(VG.command,VG.description,VG.builder,VG.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())GG.has(S)||S.startsWith(`.`)||blueprintsUnder(xn(t,S),n);return n}var GG,KG,formatFor,qG,JG=__esmMin(()=>{_e(),Md(),jn(),xk(),Ok(),GG=new Set([`node_modules`,`dist`,`lib`,`.git`]),KG=new Map,formatFor=t=>{let n=KG.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return KG.set(t,S),S},qG={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>bn(t)?t:vn(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Tn(n),formatFor(wn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),YG,XG=__esmMin(()=>{JG(),YG={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(qG.command,qG.description,qG.builder,qG.handler).demandCommand(1).strict()}}),ZG=__esmMin(()=>{ZF(),$F(),nI(),oI(),CI(),EI(),IL(),RL(),BL(),XL(),lR(),DR(),AR(),PR(),LR(),Tz(),IH(),aR(),HH(),GH(),XH(),JL(),tU(),MU(),PU(),LU(),zU(),GU(),ZU(),iW(),sW(),lW(),dW(),bW(),SW(),wW(),AW(),FW(),LW(),QW(),nG(),aG(),sG(),lG(),dG(),WG(),XG()}),QG=__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=Im(t);await n.scriptName(Zm).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(ER.command,ER.description,ER.builder,ER.handler).command(BH.command,BH.description,BH.builder,BH.handler).command(UH.command,UH.description,UH.builder,UH.handler).command(WH.command,WH.description,WH.builder,WH.handler).command(XF.command,XF.description,XF.builder,XF.handler).command(QF.command,QF.description,QF.builder,QF.handler).command(tI.command,tI.description,tI.builder,tI.handler).command(aI.command,aI.description,aI.builder,aI.handler).command(SI.command,SI.description,SI.builder,SI.handler).command(TI.command,TI.description,TI.builder,TI.handler).command(FL.command,FL.description,FL.builder,FL.handler).command(iR.command,iR.description,iR.builder,iR.handler).command(LL.command,LL.description,LL.builder,LL.handler).command(zL.command,zL.description,zL.builder,zL.handler).command(YL.command,YL.description,YL.builder,YL.handler).command(cR.command,cR.description,cR.builder,cR.handler).command(kR.command,kR.description,kR.builder,kR.handler).command(NR.command,NR.description,NR.builder,NR.handler).command(IR.command,IR.description,IR.builder,IR.handler).command(wz.command,wz.description,wz.builder,wz.handler).command(FH.command,FH.description,FH.builder,FH.handler).command(YH.command,YH.description,YH.builder,YH.handler).command(qL.command,qL.description,qL.builder,qL.handler).command(QH.command,QH.description,QH.builder,QH.handler).command(jU.command,jU.description,jU.builder,jU.handler).command(NU.command,NU.description,NU.builder,NU.handler).command(IU.command,IU.description,IU.builder,IU.handler).command(RU.command,RU.description,RU.builder,RU.handler).command(WU.command,WU.description,WU.builder,WU.handler).command(XU.command,XU.description,XU.builder,XU.handler).command(nW.command,nW.description,nW.builder,nW.handler).command(oW.command,oW.description,oW.builder,oW.handler).command(uW.command,uW.description,uW.builder,uW.handler).command(cW.command,cW.description,cW.builder,cW.handler).command(DW.command,DW.description,DW.builder,DW.handler).command(yW.command,yW.description,yW.builder,yW.handler).command(xW.command,xW.description,xW.builder,xW.handler).command(CW.command,CW.description,CW.builder,CW.handler).command(PW.command,PW.description,PW.builder,PW.handler).command(IW.command,IW.description,IW.builder,IW.handler).command(XW.command,XW.description,XW.builder,XW.handler).command(tG.command,tG.description,tG.builder,tG.handler).command(iG.command,iG.description,iG.builder,iG.handler).command(oG.command,oG.description,oG.builder,oG.handler).command(cG.command,cG.description,cG.builder,cG.handler).command(uG.command,uG.description,uG.builder,uG.handler).command(UG.command,UG.description,UG.builder,UG.handler).command(YG.command,YG.description,YG.builder,YG.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var $G=__esmMin(()=>{Lm(),Rm(),Xm(),ZG(),Qm(),t_(),ML()});$G(),t_(),PL();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(),t_();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 eK=globalThis.process,tK=Number(eK?.exitCode);Number.isInteger(tK)&&tK!==0&&eK.exit(tK);
|