@gjsify/cli 0.64.60 → 0.64.61
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 +98 -98
- package/lib/types/config-data.d.ts +14 -0
- package/lib/utils/app-metadata.d.ts +3 -1
- package/lib/utils/app-metadata.js +18 -0
- package/lib/utils/dev-link.js +23 -6
- package/package.json +20 -20
package/dist/cli.gjs.mjs
CHANGED
|
@@ -146,7 +146,7 @@ fi
|
|
|
146
146
|
`)}`:``;n.fail(N(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(C).length,Object.keys(C).join(`, `)+S))}},F.unknownArguments=function unknownArguments(S,C,I,H,W=!0){let q=t.getInternalMethods().getCommandInstance().getCommands(),Y=[],X=t.getInternalMethods().getContext();if(Object.keys(S).forEach(n=>{!Bp.includes(n)&&!Object.prototype.hasOwnProperty.call(I,n)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),n)&&!F.isValidAndSomeAliasIsNotNew(n,C)&&Y.push(n)}),W&&(X.commands.length>0||q.length>0||H)&&S._.slice(X.commands.length).forEach(t=>{q.includes(``+t)||Y.push(``+t)}),W){let n=t.getDemandedCommands()._?.max||0,C=X.commands.length+n;C<S._.length&&S._.slice(C).forEach(t=>{t=String(t),!X.commands.includes(t)&&!Y.includes(t)&&Y.push(t)})}Y.length&&n.fail(N(`Unknown argument: %s`,`Unknown arguments: %s`,Y.length,Y.map(t=>t.trim()?t:`"${t}"`).join(`, `)))},F.unknownCommands=function unknownCommands(S){let C=t.getInternalMethods().getCommandInstance().getCommands(),F=[],I=t.getInternalMethods().getContext();return(I.commands.length>0||C.length>0)&&S._.slice(I.commands.length).forEach(t=>{C.includes(``+t)||F.push(``+t)}),F.length>0?(n.fail(N(`Unknown command: %s`,`Unknown commands: %s`,F.length,F.join(`, `))),!0):!1},F.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(n,S){if(!Object.prototype.hasOwnProperty.call(S,n))return!1;let C=t.parsed.newAliases;return[n,...S[n]].some(t=>!Object.prototype.hasOwnProperty.call(C,t)||!C[n])},F.limitedChoices=function limitedChoices(S){let N=t.getOptions(),F={};if(!Object.keys(N.choices).length)return;Object.keys(S).forEach(t=>{Bp.indexOf(t)===-1&&Object.prototype.hasOwnProperty.call(N.choices,t)&&[].concat(S[t]).forEach(n=>{N.choices[t].indexOf(n)===-1&&n!==void 0&&(F[t]=(F[t]||[]).concat(n))})});let I=Object.keys(F);if(!I.length)return;let H=C(`Invalid values:`);I.forEach(t=>{H+=`\n ${C(`Argument: %s, Given: %s, Choices: %s`,t,n.stringifiedValues(F[t]),n.stringifiedValues(N.choices[t]))}`}),n.fail(H)};let I={};F.implies=function implies(n,C){argsert(`<string|object> [array|number|string]`,[n,C],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.implies(t,n[t])}):(t.global(n),I[n]||(I[n]=[]),Array.isArray(C)?C.forEach(t=>F.implies(n,t)):(assertNotStrictEqual(C,void 0,S),I[n].push(C)))},F.getImplied=function getImplied(){return I};function keyExists(t,n){let S=Number(n);return n=isNaN(S)?n:S,typeof n==`number`?n=t._.length>=n:n.match(/^--no-.+/)?(n=n.match(/^--no-(.+)/)[1],n=!Object.prototype.hasOwnProperty.call(t,n)):n=Object.prototype.hasOwnProperty.call(t,n),n}F.implications=function implications(t){let S=[];if(Object.keys(I).forEach(n=>{let C=n;(I[n]||[]).forEach(n=>{let N=C,F=n;N=keyExists(t,N),n=keyExists(t,n),N&&!n&&S.push(` ${C} -> ${F}`)})}),S.length){let t=`${C(`Implications failed:`)}\n`;S.forEach(n=>{t+=n}),n.fail(t)}};let H={};F.conflicts=function conflicts(n,S){argsert(`<string|object> [array|string]`,[n,S],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.conflicts(t,n[t])}):(t.global(n),H[n]||(H[n]=[]),Array.isArray(S)?S.forEach(t=>F.conflicts(n,t)):H[n].push(S))},F.getConflicting=()=>H,F.conflicting=function conflictingFn(N){Object.keys(N).forEach(t=>{H[t]&&H[t].forEach(S=>{S&&N[t]!==void 0&&N[S]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,S))})}),t.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(H).forEach(t=>{H[t].forEach(F=>{F&&N[S.Parser.camelCase(t)]!==void 0&&N[S.Parser.camelCase(F)]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,F))})})},F.recommendCommands=function recommendCommands(t,S){S=S.sort((t,n)=>n.length-t.length);let N=null,F=1/0;for(let n=0,C;(C=S[n])!==void 0;n++){let n=levenshtein(t,C);n<=3&&n<F&&(F=n,N=C)}N&&n.fail(C(`Did you mean %s?`,N))},F.reset=function reset(t){return I=objFilter(I,n=>!t[n]),H=objFilter(H,n=>!t[n]),F};let W=[];return F.freeze=function freeze(){W.push({implied:I,conflicting:H})},F.unfreeze=function unfreeze(){let t=W.pop();assertNotStrictEqual(t,void 0,S),{implied:I,conflicting:H}=t},F}var Bp,Vp=__esmMin(()=>{Dp(),Cp(),zp(),Mp(),Bp=[`$0`,`--`,`_`]});function YargsFactory(t){return(n=[],S=t.process.cwd(),C)=>{let N=new YargsInstance(n,S,C,t);return Object.defineProperty(N,"argv",{get:()=>N.parse(),enumerable:!0}),N.help(),N.version(),N}}function isYargsInstance(t){return!!t&&typeof t.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,YargsInstance,sh=__esmMin(()=>{_e(),jp(),Cp(),Ll(),Pp(),Dp(),Rp(),Vp(),Mp(),Bl(),Op(),wp(),kp(),Np(),__classPrivateFieldSet=function(t,n,S,C,N){if(C===`m`)throw TypeError(`Private method is not writable`);if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a setter`);if(typeof n==`function`?t!==n||!N:!n.has(t))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return C===`a`?N.call(t,S):N?N.value=S:n.set(t,S),S},__classPrivateFieldGet=function(t,n,S,C){if(S===`a`&&!C)throw TypeError(`Private accessor was defined without a getter`);if(typeof n==`function`?t!==n||!C:!n.has(t))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return S===`m`?C:S===`a`?C.call(t):C?C.value:n.get(t)},wm=Symbol(`copyDoubleDash`),Tm=Symbol(`copyDoubleDash`),Em=Symbol(`deleteFromParserHintObject`),Dm=Symbol(`emitWarning`),Om=Symbol(`freeze`),km=Symbol(`getDollarZero`),Am=Symbol(`getParserConfiguration`),jm=Symbol(`getUsageConfiguration`),Mm=Symbol(`guessLocale`),Nm=Symbol(`guessVersion`),Pm=Symbol(`parsePositionalNumbers`),Fm=Symbol(`pkgUp`),Im=Symbol(`populateParserHintArray`),Lm=Symbol(`populateParserHintSingleValueDictionary`),Rm=Symbol(`populateParserHintArrayDictionary`),zm=Symbol(`populateParserHintDictionary`),Bm=Symbol(`sanitizeKey`),Vm=Symbol(`setKey`),Hm=Symbol(`unfreeze`),Um=Symbol(`validateAsync`),Wm=Symbol(`getCommandInstance`),Gm=Symbol(`getContext`),Km=Symbol(`getHasOutput`),qm=Symbol(`getLoggerInstance`),Jm=Symbol(`getParseContext`),Ym=Symbol(`getUsageInstance`),Xm=Symbol(`getValidationInstance`),Zm=Symbol(`hasParseCallback`),Qm=Symbol(`isGlobalContext`),$m=Symbol(`postProcess`),eh=Symbol(`rebase`),th=Symbol(`reset`),nh=Symbol(`runYargsParserAndExecuteCommands`),rh=Symbol(`runValidation`),ih=Symbol(`setHasOutput`),ah=Symbol(`kTrackManuallySetKeys`),oh=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,Hp.set(this,void 0),Up.set(this,void 0),Wp.set(this,{commands:[],fullCommands:[]}),Gp.set(this,null),Kp.set(this,null),qp.set(this,`show-hidden`),Jp.set(this,null),Yp.set(this,!0),Xp.set(this,{}),Zp.set(this,!0),Qp.set(this,[]),$p.set(this,void 0),em.set(this,{}),tm.set(this,!1),nm.set(this,null),im.set(this,!0),am.set(this,void 0),om.set(this,``),sm.set(this,void 0),cm.set(this,void 0),lm.set(this,{}),um.set(this,null),dm.set(this,null),fm.set(this,{}),pm.set(this,{}),mm.set(this,void 0),hm.set(this,!1),gm.set(this,void 0),_m.set(this,!1),vm.set(this,!1),ym.set(this,!1),bm.set(this,void 0),xm.set(this,{}),Sm.set(this,null),Cm.set(this,void 0),__classPrivateFieldSet(this,gm,C,`f`),__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldSet(this,Up,n,`f`),__classPrivateFieldSet(this,cm,S,`f`),__classPrivateFieldSet(this,$p,new GlobalMiddleware(this),`f`),this.$0=this[km](),this[th](),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`),`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`),`f`),__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`),`f`),__classPrivateFieldGet(this,sm,`f`).showHiddenOpt=__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldSet(this,am,this[Tm](),`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(oh)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,nm,`f`)&&(this[Em](__classPrivateFieldGet(this,nm,`f`)),__classPrivateFieldSet(this,nm,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,nm,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,nm,`f`)),this.describe(__classPrivateFieldGet(this,nm,`f`),n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show help`)),this)}help(t,n){return this.addHelpOpt(t,n)}addShowHiddenOpt(t,n){if(argsert(`[string|boolean] [string]`,[t,n],arguments.length),t===!1&&n===void 0)return this;let S=typeof t==`string`?t:__classPrivateFieldGet(this,qp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,sm,`f`).showHiddenOpt=S,this}showHidden(t,n){return this.addShowHiddenOpt(t,n)}alias(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[Rm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`array`,t),this[ah](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`boolean`,t),this[ah](t),this}check(t,n){return argsert(`<function> [boolean]`,[t,n],arguments.length),this.middleware((n,S)=>maybeAsyncResult(()=>t(n,S.getOptions()),S=>(S?(typeof S==`string`||S instanceof Error)&&__classPrivateFieldGet(this,bm,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,bm,`f`).fail(__classPrivateFieldGet(this,gm,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,bm,`f`).fail(t.message?t.message:t.toString(),t),n)),!1,n),this}choices(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[Rm](this.choices.bind(this),`choices`,t,n),this}coerce(t,n){if(argsert(`<object|string|array> [function]`,[t,n],arguments.length),Array.isArray(t)){if(!n)throw new Il(`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 Il(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,sm,`f`).key[S]=!0,__classPrivateFieldGet(this,$p,`f`).addCoerceMiddleware((t,C)=>{let N=C.getAliases()[S]??[],F=[S,...N].filter(n=>Object.prototype.hasOwnProperty.call(t,n));return F.length===0?t:maybeAsyncResult(()=>n(t[F[0]]),n=>(F.forEach(S=>{t[S]=n}),t),t=>{throw new Il(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`f`).conflicts(t,n),this}config(t=`config`,n,S){return argsert(`[object|string] [string|function] [function]`,[t,n,S],arguments.length),typeof t==`object`&&!Array.isArray(t)?(t=applyExtends(t,__classPrivateFieldGet(this,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,sm,`f`).config[t]=S||!0}),this)}completion(t,n,S){return argsert(`[string] [string|boolean|function] [function]`,[t,n,S],arguments.length),typeof n==`function`&&(S=n,n=void 0),__classPrivateFieldSet(this,Kp,t||__classPrivateFieldGet(this,Kp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,Kp,`f`),n),S&&__classPrivateFieldGet(this,Gp,`f`).registerFunction(S),this}command(t,n,S,C,N,F){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[t,n,S,C,N,F],arguments.length),__classPrivateFieldGet(this,Hp,`f`).addHandler(t,n,S,C,N,F),this}commands(t,n,S,C,N,F){return this.command(t,n,S,C,N,F)}commandDir(t,n){argsert(`<string> [object]`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,cm,`f`)||__classPrivateFieldGet(this,gm,`f`).require;return __classPrivateFieldGet(this,Hp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,gm,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`count`,t),this[ah](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=__classPrivateFieldGet(this,bm,`f`).functionDescription(n)),n=n.call()),this[Lm](this.default.bind(this),`default`,t,n),this}defaults(t,n,S){return this.default(t,n,S)}demandCommand(t=1,n,S,C){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[t,n,S,C],arguments.length),typeof n!=`number`&&(S=n,n=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,sm,`f`).demandedCommands._={min:t,max:n,minMsg:S,maxMsg:C},this}demand(t,n,S){return Array.isArray(n)?(n.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`f`)),this.demandOption(t,S)}):typeof S==`string`?this.demandOption(t,S):(S===!0||S===void 0)&&this.demandOption(t),this}demandOption(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Lm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Vm](t,!0),__classPrivateFieldGet(this,bm,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,sm,`f`).envPrefix:__classPrivateFieldGet(this,sm,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).epilog(t),this}epilog(t){return this.epilogue(t)}example(t,n){return argsert(`<string|array> [string]`,[t,n],arguments.length),Array.isArray(t)?t.forEach(t=>this.example(...t)):__classPrivateFieldGet(this,bm,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldSet(this,Jp,n,`f`),__classPrivateFieldGet(this,Zp,`f`)&&__classPrivateFieldGet(this,gm,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Zp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new Il(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,bm,`f`).failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,n){return argsert(`<array> [function]`,[t,n],arguments.length),n?__classPrivateFieldGet(this,Gp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,Gp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Yp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Zp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,em,`f`),__classPrivateFieldGet(this,pm,`f`))}getHelp(){if(__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}let t=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,bm,`f`).help())}getOptions(){return __classPrivateFieldGet(this,sm,`f`)}getStrict(){return __classPrivateFieldGet(this,_m,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,vm,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,ym,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,sm,`f`).local.includes(t)||__classPrivateFieldGet(this,sm,`f`).local.push(t)}):__classPrivateFieldGet(this,sm,`f`).local=__classPrivateFieldGet(this,sm,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,pm,`f`)[n]||__classPrivateFieldGet(this,em,`f`)[n];__classPrivateFieldGet(this,pm,`f`)[n]&&delete __classPrivateFieldGet(this,pm,`f`)[n];let C={};return __classPrivateFieldGet(this,em,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,sm,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[Mm](),__classPrivateFieldGet(this,gm,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,$p,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[Lm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`number`,t),this[ah](t),this}option(t,n){if(argsert(`<string|object> [object]`,[t,n],arguments.length),typeof t==`object`)Object.keys(t).forEach(n=>{this.options(n,t[n])});else{typeof n!=`object`&&(n={}),this[ah](t),__classPrivateFieldGet(this,Sm,`f`)&&(t===`version`||n?.alias===`version`)&&this[Dm]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
147
147
|
`),void 0,`versionWarning`),__classPrivateFieldGet(this,sm,`f`).key[t]=!0,n.alias&&this.alias(t,n.alias);let S=n.deprecate||n.deprecated;S&&this.deprecateOption(t,S);let C=n.demand||n.required||n.require;C&&this.demand(t,C),n.demandOption&&this.demandOption(t,typeof n.demandOption==`string`?n.demandOption:void 0),n.conflicts&&this.conflicts(t,n.conflicts),`default`in n&&this.default(t,n.default),n.implies!==void 0&&this.implies(t,n.implies),n.nargs!==void 0&&this.nargs(t,n.nargs),n.config&&this.config(t,n.configParser),n.normalize&&this.normalize(t),n.choices&&this.choices(t,n.choices),n.coerce&&this.coerce(t,n.coerce),n.group&&this.group(t,n.group),(n.boolean||n.type===`boolean`)&&(this.boolean(t),n.alias&&this.boolean(n.alias)),(n.array||n.type===`array`)&&(this.array(t),n.alias&&this.array(n.alias)),(n.number||n.type===`number`)&&(this.number(t),n.alias&&this.number(n.alias)),(n.string||n.type===`string`)&&(this.string(t),n.alias&&this.string(n.alias)),(n.count||n.type===`count`)&&this.count(t),typeof n.global==`boolean`&&this.global(t,n.global),n.defaultDescription&&(__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,bm,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(F,t)||typeof N==`string`)&&this.describe(t,N),n.hidden&&this.hide(t),n.requiresArg&&this.requiresArg(t)}return this}options(t,n){return this.option(t,n)}parse(t,n,S){argsert(`[string|array] [function|boolean|object] [function]`,[t,n,S],arguments.length),this[Om](),t===void 0&&(t=__classPrivateFieldGet(this,mm,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,dm,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,um,n,`f`),n=!1),n||__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldSet(this,Zp,!1,`f`);let C=this[nh](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,Gp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),t,__classPrivateFieldGet(this,om,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,om,`f`)),t}).finally(()=>{this[Hm](),this.parsed=N}):(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),C,__classPrivateFieldGet(this,om,`f`)),this[Hm](),this.parsed=N,C)}parseAsync(t,n,S){let C=this.parse(t,n,S);return isPromise(C)?C:Promise.resolve(C)}parseSync(t,n,S){let C=this.parse(t,n,S);if(isPromise(C))throw new Il(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,lm,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[Fm](n||__classPrivateFieldGet(this,Up,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`f`).configObjects||[]).concat(S)),this}positional(t,n){argsert(`<string> <object>`,[t,n],arguments.length);let S=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];n=objFilter(n,(t,n)=>t===`type`&&![`string`,`number`,`boolean`].includes(n)?!1:S.includes(t));let C=__classPrivateFieldGet(this,Wp,`f`).fullCommands[__classPrivateFieldGet(this,Wp,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,Hp,`f`).cmdToParseOptions(C):{array:[],alias:{},default:{},demand:{}};return objectKeys(N).forEach(S=>{let C=N[S];Array.isArray(C)?C.indexOf(t)!==-1&&(n[S]=!0):C[t]&&!(S in n)&&(n[S]=C[t])}),this.group(t,__classPrivateFieldGet(this,bm,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,hm,t,`f`),this}required(t,n,S){return this.demand(t,n,S)}require(t,n,S){return this.demand(t,n,S)}requiresArg(t){return argsert(`<array|string|object> [number]`,[t],arguments.length),typeof t==`string`&&__classPrivateFieldGet(this,sm,`f`).narg[t]||this[Lm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,am,`f`).log(__classPrivateFieldGet(this,Gp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,Kp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,bm,`f`).showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,n){return argsert(`[boolean|string] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,bm,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,_m,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,vm,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,ym,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`string`,t),this[ah](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,gm,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`f`).y18n.updateLocale(t),this}usage(t,n,S,C){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[t,n,S,C],arguments.length),n!==void 0){if(assertNotStrictEqual(t,null,__classPrivateFieldGet(this,gm,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new Il(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,bm,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,xm,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Sm,`f`)&&(this[Em](__classPrivateFieldGet(this,Sm,`f`)),__classPrivateFieldGet(this,bm,`f`).version(void 0),__classPrivateFieldSet(this,Sm,null,`f`)),arguments.length===0)S=this[Nm](),t=C;else if(arguments.length===1){if(t===!1)return this;S=t,t=C}else arguments.length===2&&(S=n,n=void 0);return __classPrivateFieldSet(this,Sm,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,bm,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Sm,`f`)),this.describe(__classPrivateFieldGet(this,Sm,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).wrap(t),this}[(Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap,Xp=new WeakMap,Zp=new WeakMap,Qp=new WeakMap,$p=new WeakMap,em=new WeakMap,tm=new WeakMap,nm=new WeakMap,im=new WeakMap,am=new WeakMap,om=new WeakMap,sm=new WeakMap,cm=new WeakMap,lm=new WeakMap,um=new WeakMap,dm=new WeakMap,fm=new WeakMap,pm=new WeakMap,mm=new WeakMap,hm=new WeakMap,gm=new WeakMap,_m=new WeakMap,vm=new WeakMap,ym=new WeakMap,bm=new WeakMap,xm=new WeakMap,Sm=new WeakMap,Cm=new WeakMap,wm)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[Tm](){return{log:(...t)=>{this[Zm]()||ge.log(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
|
|
148
148
|
`,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Zm]()||ge.error(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
|
|
149
|
-
`,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Il(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Il(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Il)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Il(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.60`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):ph}function parseNpmrc(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var ph,mh=__esmMin(()=>{ph=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var hh=__esmMin(()=>{fh(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var gh=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var vh=__esmMin(()=>{dh(),fh(),mh(),hh()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var yh=__esmMin(()=>{dh(),fh(),hh(),gh()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Sh===void 0&&(Sh=`0.64.60`),Sh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=Hn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(Xl(),__toCommonJS(Kl)),N=(af(),__toCommonJS(nf)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),Ph=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),Fh=__commonJSMin(((t,n)=>{let S=Ph();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(eu(),__toCommonJS(Zl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(zu(),__toCommonJS(Fu)),C=Lh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
|
|
149
|
+
`,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Il(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Il(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Il)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Il(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.61`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):ph}function parseNpmrc(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var ph,mh=__esmMin(()=>{ph=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var hh=__esmMin(()=>{fh(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var gh=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var vh=__esmMin(()=>{dh(),fh(),mh(),hh()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var yh=__esmMin(()=>{dh(),fh(),hh(),gh()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return Sh===void 0&&(Sh=`0.64.61`),Sh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=Hn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(Xl(),__toCommonJS(Kl)),N=(af(),__toCommonJS(nf)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),Ph=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),Fh=__commonJSMin(((t,n)=>{let S=Ph();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(eu(),__toCommonJS(Zl)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(zu(),__toCommonJS(Fu)),C=Lh(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
|
|
150
150
|
`)},set:function(t){S=t}});var F=null,I=Object.getOwnPropertyDescriptor(this,`stack`),H=I.get,W=I.value;delete I.value,delete I.writable,I.set=function(t){F=t},I.get=function(){var t=(F||(H?H.call(this):W)).split(/\r?\n+/g);F||(t[0]=this.name+`: `+this.message);var S=1;for(var C in n)if(n.hasOwnProperty(C)){var N=n[C];if(`line`in N){var I=N.line(this[C]);I&&t.splice(S++,0,` `+I)}`stack`in N&&N.stack(this[C],t)}return t.join(`
|
|
151
151
|
`)},Object.defineProperty(this,"stack",I)};return Object.setPrototypeOf?(Object.setPrototypeOf(N.prototype,Error.prototype),Object.setPrototypeOf(N,Error)):S.inherits(N,Error),N};N.append=function(t,n){return{message:function(S,C){return S||=n,S&&(C[0]+=` `+t.replace(`%s`,S.toString())),C}}},N.line=function(t,n){return{line:function(S){return S||=n,S?t.replace(`%s`,S.toString()):null}}},n.exports=N})),zh=__commonJSMin(((t,n)=>{let hexify=t=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return`0x`+(n.length%2?`0`:``)+n},parseError=(t,n,S)=>{if(!n)return{message:t.message+` while parsing empty string`,position:0};let C=t.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),N=C?+C[2]:t.message.match(/^Unexpected end of JSON.*/i)?n.length-1:null,F=C?t.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(C[1])} (${hexify(C[1])})`):t.message;if(N!=null){let t=N<=S?0:N-S,C=N+S>=n.length?n.length:N+S,I=(t===0?``:`...`)+n.slice(t,C)+(C===n.length?``:`...`);return{message:F+` while parsing ${n===I?``:`near `}${JSON.stringify(I)}`,position:N}}else return{message:F+` while parsing '${n.slice(0,S*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(t,n,S,C){S||=20;let N=parseError(t,n,S);super(N.message),Object.assign(this,N),this.code=`EJSONPARSE`,this.systemError=t,Error.captureStackTrace(this,C||this.constructor)}get name(){return this.constructor.name}set name(t){}get[Symbol.toStringTag](){return this.constructor.name}};let S=Symbol.for(`indent`),C=Symbol.for(`newline`),N=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,F=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(t,n,I)=>{let H=stripBOM(t);I||=20;try{let[,t=`
|
|
152
152
|
`,I=` `]=H.match(F)||H.match(N)||[,``,``],W=JSON.parse(H,n);return W&&typeof W==`object`&&(W[C]=t,W[S]=I),W}catch(n){if(typeof t!=`string`&&!Buffer.isBuffer(t)){let S=Array.isArray(t)&&t.length===0;throw Object.assign(TypeError(`Cannot parse ${S?`an empty array`:String(t)}`),{code:`EJSONPARSE`,systemError:n})}throw new JSONParseError(n,H,I,parseJson)}},stripBOM=t=>String(t).replace(/^\uFEFF/,``);n.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(t,n)=>{try{return JSON.parse(stripBOM(t),n)}catch{}}})),Bh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
|
|
@@ -936,7 +936,7 @@ Add @gjsify/node-gi as a dependency to run it on Node, e.g.:
|
|
|
936
936
|
`)}function droppedInstallPaths(t,n){let S=new Set(n.map(t=>normalizePath(t.installPath))),C=[...new Set([...t].map(normalizePath))].filter(t=>t.startsWith(`node_modules/`)&&!S.has(t)).sort((t,n)=>t<n?-1:+(t>n)),N=[...S],F=[];for(let t of C){let n=F[F.length-1];n&&t.startsWith(`${n}/`)||N.some(n=>n.startsWith(`${t}/`))||F.push(t)}return F}var Cz=__esmMin(()=>{Xn()});function dirLinkTarget(t,n,S=wz){return S===`junction`?In(n):Bn(Hn(t),n)}function linkDirSync(t,n){assertAbsolute(n),symlinkSync(dirLinkTarget(t,n),t,Tz)}function replicateLinkSync(t,n){let S=readlinkSync(t);if(!dirLinksAreJunctions()){symlinkSync(S,n);return}let C=In(Hn(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(In(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 wz,Tz,dirLinksAreJunctions,Ez=__esmMin(()=>{af(),Vd(),Xn(),wz=process.platform===`win32`?`junction`:`symlink`,Tz=wz===`junction`?`junction`:void 0,dirLinksAreJunctions=()=>wz===`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(Dz);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=Oz){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 Az||=(kz=detectLibc(t,n),!0),kz}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 Dz,Oz,kz,Az,jz=__esmMin(()=>{af(),Dz=`/usr/bin/ldd`,Oz=[`/lib`,`/lib64`,`/usr/lib`],Az=!1});function isReservedEntry(t){return t.startsWith(`.`)}function readManifest$1(t){try{let n=JSON.parse(readFileSync(zn(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=zn(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(zn(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$1(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(zn(t,`node_modules`),n)}function scanPrefix(t){let n=[];return collect(zn(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=zn(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=zn(t,`node_modules`,`.bin`),S=[],C;try{C=readdirSync(n,{withFileTypes:!0})}catch{return S}for(let t of C){let C=zn(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(`
|
|
937
937
|
`);let N=n.verbose?S.entries:S.entries.slice(0,Mz);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(`
|
|
938
938
|
`)}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 Mz,Nz=__esmMin(()=>{_e(),af(),Xn(),jz(),__name$1(readManifest$1,`readManifest`),Mz=10});function devLinkPath(t){return zn(t,Pz)}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:Rn(C.checkout)?C.checkout:In(t,C.checkout),packages:Array.isArray(C.packages)?C.packages.filter(t=>typeof t==`string`):[],...Array.isArray(C.closure)?{closure:C.closure.filter(t=>typeof t==`string`)}:{}}}function writeDevLinkOverride(t,n){let S=devLinkPath(t),{closure:C,...N}=n;return writeFileSync(S,JSON.stringify(C&&C.length>0?{...N,closure:C}:N,null,2)+`
|
|
939
|
-
`),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 tscArgsUnderLink(t,n){return!n||t.some(t=>t.toLowerCase().split(`=`)[0]===`--preservesymlinks`)?[...t]:[...t,`--preserveSymlinks`]}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(zn(t,`package.json`));if(!S||S.workspaces===void 0)throw Error(`gjsify link: ${t} is not a gjsify workspace — ${zn(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(zn(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);for(let S of lockfileNames(t))n.add(S);return n}function lockfileNames(t){try{let n=JSON.parse(readFileSync(zn(t,`gjsify-lock.json`),`utf-8`)),S=[];for(let t of Object.keys(n.packages??{})){let n=t.lastIndexOf(`node_modules/`);n!==-1&&S.push(t.slice(n+13))}return S}catch{return[]}}function consumerNestedPlacements(t){let n=zn(t,`node_modules`)+qn,S=[];for(let C of scanPrefix(t))C.linked||(C.dir.startsWith(n)?C.dir.slice(n.length):``).includes(`${qn}node_modules${qn}`)&&S.push({name:C.name,dir:C.dir});return S}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:zn(t.consumerRoot,`node_modules`,C.name)});let C=S.map(t=>t.linkPath+qn),N=new Map(S.map(t=>[t.name,t]));for(let n of t.nested??[]){let t=N.get(n.name);t&&(C.some(t=>n.dir.startsWith(t))||S.push({name:n.name,target:t.target,linkPath:n.dir}))}return S.sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:t.linkPath<n.linkPath?-1:+(t.linkPath>n.linkPath)),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),nested:consumerNestedPlacements(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(Hn(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 missing(t){try{return lstatSync(t),!1}catch{return!0}}function syncDevLinkClosure(t,n,S){removeDevLinkClosure(S);let C=zn(n,`node_modules`);if(!existsSync(C))return[];let N=[],add=(t,n)=>{linkDirSync(t,n),N.push(t)};for(let n of t){let t=zn(n.target,`node_modules`);if(t!==C){if(missing(t)){add(t,C);continue}if(lstatSync(t).isDirectory())for(let n of readdirSync(C)){if(n.startsWith(`.`))continue;if(!n.startsWith(`@`)){missing(zn(t,n))&&add(zn(t,n),zn(C,n));continue}let S=zn(t,n);if(missing(S)){add(S,zn(C,n));continue}if(lstatSync(S).isDirectory())for(let t of readdirSync(zn(C,n)))missing(zn(S,t))&&add(zn(S,t),zn(C,n,t))}}}return N}function removeDevLinkClosure(t){let n=[];for(let S of t){try{if(!lstatSync(S).isSymbolicLink())continue}catch{continue}rmSync(S,{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=[];for(let n of scanPrefix(t)){if(!n.linked)continue;let N;try{N=realpathSync(n.dir)}catch{continue}S.some(t=>N===t||N.startsWith(t+qn))&&C.push({name:packageNameAt(t,n.dir),target:N,linkPath:n.dir})}return C.sort((t,n)=>t.linkPath<n.linkPath?-1:+(t.linkPath>n.linkPath)),C}function packageNameAt(t,n){let S=Bn(t,n).split(qn).join(`/`);return S.slice(S.lastIndexOf(`node_modules/`)+13)}function retireDevLinks(t,n,S){
|
|
939
|
+
`),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 tscArgsUnderLink(t,n){return!n||t.some(t=>t.toLowerCase().split(`=`)[0]===`--preservesymlinks`)?[...t]:[...t,`--preserveSymlinks`]}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(zn(t,`package.json`));if(!S||S.workspaces===void 0)throw Error(`gjsify link: ${t} is not a gjsify workspace — ${zn(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(zn(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);for(let S of lockfileNames(t))n.add(S);return n}function lockfileNames(t){try{let n=JSON.parse(readFileSync(zn(t,`gjsify-lock.json`),`utf-8`)),S=[];for(let t of Object.keys(n.packages??{})){let n=t.lastIndexOf(`node_modules/`);n!==-1&&S.push(t.slice(n+13))}return S}catch{return[]}}function consumerNestedPlacements(t){let n=zn(t,`node_modules`)+qn,S=[];for(let C of scanPrefix(t))C.linked||(C.dir.startsWith(n)?C.dir.slice(n.length):``).includes(`${qn}node_modules${qn}`)&&S.push({name:C.name,dir:C.dir});return S}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:zn(t.consumerRoot,`node_modules`,C.name)});let C=S.map(t=>t.linkPath+qn),N=new Map(S.map(t=>[t.name,t]));for(let n of t.nested??[]){let t=N.get(n.name);t&&(C.some(t=>n.dir.startsWith(t))||S.push({name:n.name,target:t.target,linkPath:n.dir}))}return S.sort((t,n)=>t.name<n.name?-1:t.name>n.name?1:t.linkPath<n.linkPath?-1:+(t.linkPath>n.linkPath)),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),nested:consumerNestedPlacements(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(Hn(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 missing(t){try{return lstatSync(t),!1}catch{return!0}}function syncDevLinkClosure(t,n,S){removeDevLinkClosure(S);let C=zn(n,`node_modules`);if(!existsSync(C))return[];let N=[],add=(t,n)=>{linkDirSync(t,n),N.push(t)};for(let n of t){let t=zn(n.target,`node_modules`);if(t!==C){if(missing(t)){add(t,C);continue}if(lstatSync(t).isDirectory())for(let n of readdirSync(C)){if(n.startsWith(`.`))continue;if(!n.startsWith(`@`)){missing(zn(t,n))&&add(zn(t,n),zn(C,n));continue}let S=zn(t,n);if(missing(S)){add(S,zn(C,n));continue}if(lstatSync(S).isDirectory())for(let t of readdirSync(zn(C,n)))missing(zn(S,t))&&add(zn(S,t),zn(C,n,t))}}}return N}function removeDevLinkClosure(t){let n=[];for(let S of t){try{if(!lstatSync(S).isSymbolicLink())continue}catch{continue}rmSync(S,{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){S.push(In(t));try{S.push(realpathSync(t))}catch{}}if(S.length===0)return[];let C=[];for(let n of scanPrefix(t)){if(!n.linked)continue;let N;try{N=realpathSync(n.dir)}catch{try{N=In(Hn(n.dir),readlinkSync(n.dir))}catch{continue}}S.some(t=>N===t||N.startsWith(t+qn))&&C.push({name:packageNameAt(t,n.dir),target:N,linkPath:n.dir})}return C.sort((t,n)=>t.linkPath<n.linkPath?-1:+(t.linkPath>n.linkPath)),C}function packageNameAt(t,n){let S=Bn(t,n).split(qn).join(`/`);return S.slice(S.lastIndexOf(`node_modules/`)+13)}function retireDevLinks(t,n,S){let C=scanDevLinks(t,n).filter(t=>!S.has(t.name)),N=[];for(let t of C)rmSync(t.linkPath,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}),N.push(t);return N}function unbuiltDevLinks(t){let n=[];for(let S of t){let t;try{t=JSON.parse(readFileSync(zn(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(zn(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(`
|
|
940
940
|
`);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=zn(t,`.gitignore`);if(existsSync(S)&&fileMentionsPattern(S,`.gjsify-link.json`))return`already-ignored`;let C=zn(n.commonDir,`info`,`exclude`);if(existsSync(C)&&fileMentionsPattern(C,`.gjsify-link.json`))return`already-ignored`;mkdirSync(Hn(C),{recursive:!0});let N=existsSync(C)?readFileSync(C,`utf-8`):``;return writeFileSync(C,`${N}${N===``||N.endsWith(`
|
|
941
941
|
`)?``:`
|
|
942
942
|
`}${Fz}\n${Pz}\n`),`added`}function removeLocalIgnore(t){let n=resolveGitDir(t);if(!n.commonDir)return n.why;let S=zn(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()===Fz&&(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(`
|
|
@@ -951,7 +951,7 @@ Add @gjsify/node-gi as a dependency to run it on Node, e.g.:
|
|
|
951
951
|
echo "gjsify: got: node $*" >&2
|
|
952
952
|
exit 127 ;;
|
|
953
953
|
esac
|
|
954
|
-
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Zz,Qz,$z,eB=__esmMin(()=>{fl(),af(),o_(),Xn(),cr(),P_(),PR(),_L(),QR(),Xz(),JI(),Zz=!1,Qz=!1,$z=`node-shim`});function markDaemonCommand(){tB=!0}function isDaemonCommand(){return tB}var tB,nB=__esmMin(()=>{tB=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
954
|
+
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Zz,Qz,$z,eB=__esmMin(()=>{fl(),af(),o_(),Xn(),cr(),P_(),PR(),_L(),QR(),Xz(),JI(),Zz=!1,Qz=!1,$z=`node-shim`});function markDaemonCommand(){tB=!0}function isDaemonCommand(){return tB}var tB,nB=__esmMin(()=>{tB=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(GX(),WX));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 rB,iB=__esmMin(()=>{_e(),af(),Xn(),ER(),hv(),HR(),WR(),XR(),ZR(),eB(),JI(),cR(),nB(),KI(),P_(),vv(),rB={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:gv,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${gv.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),aB,oB=__esmMin(()=>{_e(),Xn(),_L(),aB={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?In(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),sB,cB=__esmMin(()=>{_e(),fL(),sB={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
|
|
955
955
|
`);let H=n.filter(t=>t.severity===`required`),W=n.filter(t=>t.severity===`optional`);if(H.length>0){ge.log(`Required:`);for(let t of H){let n=t.found?`✓`:`✗`,S=t.version?` (${t.version})`:``;ge.log(` ${n} ${t.name}${S}`)}}if(W.length>0){ge.log(`
|
|
956
956
|
Optional:`);for(let t of W){let n=t.found?`✓`:`⚠`,S=t.version?` (${t.version})`:``,C=t.requiredBy&&t.requiredBy.length>0?` — needed by ${t.requiredBy.join(`, `)}`:``;ge.log(` ${n} ${t.name}${S}${C}`)}}if(C.length>0){ge.log(`
|
|
957
957
|
Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`ℹ`;ge.log(` ${n} ${t.typePackage} describes ${t.declared}, installed ${t.pkgConfig} is ${t.installed}`)}C.some(t=>t.relation===`ahead`)&&ge.log(`
|
|
@@ -972,10 +972,10 @@ No install command available for your package manager. Install manually.`),proce
|
|
|
972
972
|
bunx @gjsify/cli@latest showcase <name>
|
|
973
973
|
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,AB={command:`showcase [name]`,description:`List or run curated gjsify showcase applications.`,builder:t=>t.positional(`name`,{description:`Showcase name to run (omit to list all)`,type:`string`}).option(`json`,{description:`Output as JSON`,type:`boolean`,default:!1}).option(`list`,{description:`List available showcases`,type:`boolean`,default:!1}).option(`runtime`,{type:`string`,choices:gv,defaultDescription:`gjs when gjs is installed, else the host runtime`,description:"Runtime to run the showcase on: gjs | node | bun | deno (default: gjs when installed, else the host runtime). node/bun/deno run its `--app node` bundle."}),handler:async t=>{if(!t.name||t.list){let n=discoverShowcases();if(t.json){ge.log(JSON.stringify(n,null,2));return}if(n.length===0){ge.log("No showcases found. The CLI ships a curated list in `showcases.json`; if it is missing the CLI install is incomplete.");return}let S=new Map;for(let t of n){let n=S.get(t.category)??[];n.push(t),S.set(t.category,n)}ge.log(`Available gjsify showcases:
|
|
974
974
|
`);for(let[t,n]of S){ge.log(` ${t.toUpperCase()}:`);let S=Math.max(...n.map(t=>t.name.length));for(let t of n){let n=` `.repeat(S-t.name.length+2),C=t.description?`${n}${t.description}`:``;ge.log(` ${t.name}${C}`)}ge.log(``)}ge.log(`Run a showcase: gjsify showcase <name>`);return}let n=findShowcase(t.name);if(!n)return ge.error(`Unknown showcase: "${t.name}"`),ge.error(`Run "gjsify showcase" to list available showcases.`),process.exit(1);let S=t.runtime??defaultExampleRuntime();if(!isExampleRuntime(S))return ge.error(`Unknown --runtime "${S}" (expected: ${gv.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(S)){let t=runMinimalChecks().filter(t=>!t.found&&t.severity===`required`);if(t.length>0){ge.error(`Missing system dependencies:
|
|
975
|
-
`);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
976
|
-
`),N(Error(qB));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};Sn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:RB[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 KB,qB,JB=__esmMin(()=>{_e(),Cn(),Xd(),zB(),BB(),KB={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},qB=`Cancelled by user`}),YB,XB=__esmMin(()=>{_e(),GB(),JB(),YB={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:PB})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Un(t,Wn(t));return In(Hn(t),n)}var ZB,QB,$B=__esmMin(()=>{_e(),cv(),Vd(),Xn(),zu(),ZB=promisify(execFile),QB={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.xml),S=t.target?In(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?In(t.sourcedir):Hn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(Hn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await ZB(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=zn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var eV=__esmMin(()=>{cv(),Xn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=zn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(zn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Un(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:zn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=zn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${zn(n,t.filename)}`,zn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await tV(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Un(S.replace(/\.in$/,``)):`${t}.xml`}}var tV,nV,rV=__esmMin(()=>{_e(),cv(),Vd(),o_(),Xn(),zu(),eV(),tV=promisify(execFile),nV={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.poDir),S=In(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?In(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),iV,aV,oV=__esmMin(()=>{_e(),cv(),Vd(),Xn(),zu(),iV=promisify(execFile),aV={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.schemadir),S=t.targetdir?In(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await iV(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=In(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var sV,cV=__esmMin(()=>{af(),Xn(),sV=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`51`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var lV,uV,dV=__esmMin(()=>{lV=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],uV=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of pV){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function scalableAppIconCleanup(t){return`/share/icons/hicolor/scalable/apps/${t}.svg`}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?uV:lV),cleanup:[...new Set([...W??[],...t.kind===`app`?[scalableAppIconCleanup(t.appId)]:[]])]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${fV}. 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 fV,pV,mV=__esmMin(()=>{dV(),fV=`1.0.0`,pV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return hV}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:[t.command,...(t.desktopExecArgs??[]).map(n=>quoteExecArg(n,t.configKey))].join(` `)+execFieldCode(N),APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function quoteExecArg(t,n){if(/[\r\n]/.test(t))throw Error(`${n}.desktopExecArgs contains ${JSON.stringify(t)}: a newline cannot appear in a desktop entry's Exec= line.`);let S=t.replace(/%/g,`%%`);return S===``?`""`:gV.test(S)?`"${S.replace(/(["`$\\])/g,`\\$1`).replace(/\\/g,`\\\\`)}"`:S}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`);for(let[n,S]of Object.entries(t.localizedUrls??{}))F.push(` <image xml:lang="${escapeXml(n)}">${escapeXml(S)}</image>`);t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&channelAllowsDonations(t.channel)&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}return F.push(`</component>`),F.join(`
|
|
975
|
+
`);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(GX(),WX));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=Hn(fileURLToPath(import.meta.url)),n=[zn(t,`..`,`dist-templates`),zn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,zn(Hn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=zn(t,S),N=zn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=MB[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 MB,NB=__esmMin(()=>{af(),Xl(),Xn(),cr(),MB={"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,...FB[t]].join(` `)}function runScriptCommand(t){return IB[t]}function packageManagersForRuntime(t){return LB[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 PB,FB,IB,LB,RB,zB=__esmMin(()=>{PB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],FB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},IB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},LB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},RB={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 BB=__esmMin(()=>{zB()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=In(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[VB,n],[HB,applicationIdFor(n)]];renameSentinelPaths(t,S),substituteSentinelContents(t,S)}function renameSentinelPaths(t,n){for(let S of readdirSync(t,{withFileTypes:!0})){let C=S.name;for(let[t,S]of n)C=C.replaceAll(t,S);let N=zn(t,S.name),F=zn(t,C);F!==N&&renameSync(N,F),S.isDirectory()&&renameSentinelPaths(F,n)}}function substituteSentinelContents(t,n){let S=new Set([`node_modules`,`dist`,`lib`]),C=[t];for(;C.length>0;){let t=C.pop();for(let N of readdirSync(t,{withFileTypes:!0})){let F=zn(t,N.name);if(N.isDirectory()){S.has(N.name)||C.push(F);continue}if(!N.isFile())continue;let I=N.name.lastIndexOf(`.`),H=I>=0?N.name.slice(I):``;if(!UB.has(H)&&!WB.has(N.name))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,S]of n)q=q.replaceAll(t,S);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}I.ship&&(ge.log(`Package it for a machine without gjsify:`),ge.log(` ${F} ship -- darwin`),ge.log(``))}function templateManifest(t){try{return JSON.parse(readFileSync(zn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var VB,HB,UB,WB,GB=__esmMin(()=>{_e(),cv(),af(),Xn(),NB(),zB(),BB(),VB=`new-gjsify-app`,HB=`org.gjsify.example`,UB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),WB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===qB}function render(t,n,S){S||xn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${KB.cyan}❯${KB.reset}`:` `,F=S===n?`${KB.bold}${KB.green}${C.label}${KB.reset}`:C.label,I=C.description?` ${KB.dim}${C.description}${KB.reset}`:``;xn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;xn.write(`${KB.bold}${t}${KB.reset} ${KB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${KB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
|
|
976
|
+
`),N(Error(qB));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};Sn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:RB[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 KB,qB,JB=__esmMin(()=>{_e(),Cn(),Xd(),zB(),BB(),KB={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},qB=`Cancelled by user`}),YB,XB=__esmMin(()=>{_e(),GB(),JB(),YB={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:PB})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Un(t,Wn(t));return In(Hn(t),n)}var ZB,QB,$B=__esmMin(()=>{_e(),cv(),Vd(),Xn(),zu(),ZB=promisify(execFile),QB={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.xml),S=t.target?In(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?In(t.sourcedir):Hn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(Hn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await ZB(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=zn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var eV=__esmMin(()=>{cv(),Xn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=zn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(zn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Un(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:zn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=zn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${zn(n,t.filename)}`,zn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await tV(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Un(S.replace(/\.in$/,``)):`${t}.xml`}}var tV,nV,rV=__esmMin(()=>{_e(),cv(),Vd(),o_(),Xn(),zu(),eV(),tV=promisify(execFile),nV={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.poDir),S=In(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?In(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),iV,aV,oV=__esmMin(()=>{_e(),cv(),Vd(),Xn(),zu(),iV=promisify(execFile),aV={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.schemadir),S=t.targetdir?In(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await iV(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=In(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var sV,cV=__esmMin(()=>{af(),Xn(),sV=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`51`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var lV,uV,dV=__esmMin(()=>{lV=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],uV=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of pV){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function scalableAppIconCleanup(t){return`/share/icons/hicolor/scalable/apps/${t}.svg`}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?uV:lV),cleanup:[...new Set([...W??[],...t.kind===`app`?[scalableAppIconCleanup(t.appId)]:[]])]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${fV}. 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 fV,pV,mV=__esmMin(()=>{dV(),fV=`1.0.0`,pV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return gV}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:[t.command,...(t.desktopExecArgs??[]).map(n=>quoteExecArg(n,t.configKey))].join(` `)+execFieldCode(N),APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function quoteExecArg(t,n){if(/[\r\n]/.test(t))throw Error(`${n}.desktopExecArgs contains ${JSON.stringify(t)}: a newline cannot appear in a desktop entry's Exec= line.`);let S=t.replace(/%/g,`%%`);return S===``?`""`:_V.test(S)?`"${S.replace(/(["`$\\])/g,`\\$1`).replace(/\\/g,`\\\\`)}"`:S}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`);for(let[n,S]of Object.entries(t.localizedUrls??{}))F.push(` <image xml:lang="${escapeXml(n)}">${escapeXml(S)}</image>`);t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&channelAllowsDonations(t.channel)&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}if(S.aiInvolvement!==void 0){let{level:n,disclosure:C}=S.aiInvolvement;if(!hV.includes(n))throw Error(`${t.configKey}.aiInvolvement.level is ${JSON.stringify(n)}; expected one of ${hV.join(`, `)} (ADR 0153). An unknown level is never guessed.`);F.push(` <custom>`),F.push(` <value key="gjsify::ai-involvement">${escapeXml(n)}</value>`);let N=C?.trim().replace(/\s+/g,` `);N&&F.push(` <value key="gjsify::ai-disclosure">${escapeXml(N)}</value>`),F.push(` </custom>`)}return F.push(`</component>`),F.join(`
|
|
977
977
|
`)+`
|
|
978
|
-
`}function renderDescriptionBlocks(t,n){let S=typeof t==`string`?stringToBlocks(t):t,C=[];for(let t of S)if(`p`in t)pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<p>${escapeXml(t.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<ul>`);for(let S of t.ul)typeof S==`string`?C.push(`${n} <li>${escapeXml(S)}</li>`):(pushTranslatorHint(C,S.translatorHint,`${n} `),C.push(`${n} <li>${escapeXml(S.item)}</li>`));C.push(`${n}</ul>`)}return C}function stringToBlocks(t){return t.trim().split(/\n\n+/).map(t=>({p:t.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(t,n,S){n&&t.push(`${S}<!-- TRANSLATORS: ${n} -->`)}function normaliseContentRating(t){return t===void 0?{type:`oars-1.1`}:typeof t==`string`?{type:t}:{type:t.type??`oars-1.1`,attributes:t.attributes}}function substitute(t,n){let S=t;for(let[t,C]of Object.entries(n))S=S.split(`{{${t}}}`).join(C);return S}function escapeXml(t){return t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var hV,gV,_V=__esmMin(()=>{kh(),hV=`[Desktop Entry]
|
|
978
|
+
`}function renderDescriptionBlocks(t,n){let S=typeof t==`string`?stringToBlocks(t):t,C=[];for(let t of S)if(`p`in t)pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<p>${escapeXml(t.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<ul>`);for(let S of t.ul)typeof S==`string`?C.push(`${n} <li>${escapeXml(S)}</li>`):(pushTranslatorHint(C,S.translatorHint,`${n} `),C.push(`${n} <li>${escapeXml(S.item)}</li>`));C.push(`${n}</ul>`)}return C}function stringToBlocks(t){return t.trim().split(/\n\n+/).map(t=>({p:t.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(t,n,S){n&&t.push(`${S}<!-- TRANSLATORS: ${n} -->`)}function normaliseContentRating(t){return t===void 0?{type:`oars-1.1`}:typeof t==`string`?{type:t}:{type:t.type??`oars-1.1`,attributes:t.attributes}}function substitute(t,n){let S=t;for(let[t,C]of Object.entries(n))S=S.split(`{{${t}}}`).join(C);return S}function escapeXml(t){return t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var hV,gV,_V,vV=__esmMin(()=>{kh(),hV=[`none`,`assisted`,`agent-built`],gV=`[Desktop Entry]
|
|
979
979
|
Name={{NAME}}
|
|
980
980
|
Comment={{SUMMARY}}
|
|
981
981
|
Exec={{COMMAND}}
|
|
@@ -985,11 +985,11 @@ Type=Application
|
|
|
985
985
|
Categories={{CATEGORIES_LINE}}
|
|
986
986
|
{{KEYWORDS_LINE}}{{MIMETYPES_LINE}}StartupNotify=true
|
|
987
987
|
StartupWMClass={{APP_ID}}
|
|
988
|
-
`,__name$1(renderMetainfoApp$1,`renderMetainfoApp`),__name$1(renderMetainfoCli$1,`renderMetainfoCli`),
|
|
988
|
+
`,__name$1(renderMetainfoApp$1,`renderMetainfoApp`),__name$1(renderMetainfoCli$1,`renderMetainfoCli`),_V=/[\s"'\\><~|&;$*?#()`]/});function loadFlathubAppTemplate(){return`{}
|
|
989
989
|
`}function loadFlathubCliTemplate(){return`{
|
|
990
990
|
"skip-icons-check": true
|
|
991
991
|
}
|
|
992
|
-
`}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,desktopExecArgs:t.desktopExecArgs,channel:`flathub`,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
|
|
992
|
+
`}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,desktopExecArgs:t.desktopExecArgs,channel:`flathub`,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 yV=__esmMin(()=>{vV()});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=zn(t,`node_modules`,n,S);return existsSync(C)?C:null}function findOxcLauncher(t,n=process.cwd()){let S=zn(`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=In(n,`..`);for(let n=0;n<6;n++){let n=probeNodeModules(F,t,S);if(n)return n;let C=In(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=zn(S,t);if(existsSync(n))return n}let t=In(S,`..`);if(t===S)break;S=t}return null}async function tryLoadNativeOxfmt(){return bV||(bV=(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 xV=t instanceof Error?t:Error(String(t)),null}return xV=S(`GjsifyOxfmt`),xV?null:n}catch{return null}})(),bV)}function decideOxfmtEngine(t){let{isGjs:n,nativeLoadable:S,embeddedVersion:C,projectVersion:N,override:F}=t,I=C!==void 0&&N!==void 0&&normalizeVersion(C)!==normalizeVersion(N);return F===`npm`?{engine:`npm`}:F===`native`?S?I?{engine:`native`,warning:`GJSIFY_OXFMT=native: @gjsify/oxfmt-native embeds oxfmt ${C} but this project pins oxfmt ${N}; output can differ from the project's own oxfmt (and from CI).`}:{engine:`native`}:{engine:`native`,error:`GJSIFY_OXFMT=native but @gjsify/oxfmt-native is not loadable (no prebuild for this architecture, or not running under GJS).`}:!n||!S?{engine:`npm`}:{engine:I?`npm`:`native`}}function findProjectOxfmtVersion(t=process.cwd()){try{let n=findOxcLauncher(`oxfmt`,t),S=JSON.parse(readFileSync(zn(Hn(n),`..`,`package.json`),`utf-8`));return typeof S?.version==`string`?S.version:void 0}catch{return}}async function shouldUseNativeOxfmt(t=process.cwd()){let n=(globalThis.process?.env??{}).GJSIFY_OXFMT;if(n===`npm`||!isGjs()&&n!==`native`)return!1;let S=await tryLoadNativeOxfmt(),C=decideOxfmtEngine({isGjs:isGjs(),nativeLoadable:S!==null,embeddedVersion:S?.EMBEDDED_OXFMT_VERSION,projectVersion:findProjectOxfmtVersion(t),override:n});if(C.error)throw Error(C.error+(xV?`\n${xV.message}`:``));return C.warning&&!SV&&(SV=!0,ge.warn(`[gjsify oxc] ${C.warning}`)),!S&&xV&&C.engine===`npm`&&ge.debug(xV.message),C.engine===`native`}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`{
|
|
993
993
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
|
994
994
|
"categories": {
|
|
995
995
|
"correctness": "error"
|
|
@@ -1078,11 +1078,11 @@ StartupWMClass={{APP_ID}}
|
|
|
1078
1078
|
"**/*.metainfo.xml"
|
|
1079
1079
|
]
|
|
1080
1080
|
}
|
|
1081
|
-
`}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=zn(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,
|
|
1081
|
+
`}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=zn(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,bV,xV,normalizeVersion,SV,CV=__esmMin(()=>{_e(),af(),Xn(),Xl(),cr(),jz(),JI(),XI(),yL(),WR(),hv(),P_(),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`}},bV=null,xV=null,normalizeVersion=t=>t.trim().replace(/^v/,``),SV=!1});function writeIfFresh(t,n,S,C){return existsSync(t)&&!S?(ge.log(`[gjsify flatpak init] skipped ${C}: ${t} (exists; --force to overwrite)`),null):(mkdirSync(Hn(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 wV,TV=__esmMin(()=>{_e(),af(),Xn(),cV(),dV(),mV(),yV(),vR(),CV(),wV={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`?uV:lV):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(In(C,t.manifest??`${F}.json`),JSON.stringify(ae,null,2)+`
|
|
1082
1082
|
`,t.force??!1,`manifest`));let ce=N.name??F,le={appId:F,name:S.name??friendlyName(ce,F),command:ne,kind:I,flatpak:S,desktopExecArgs:n.ship?.desktopExecArgs},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(`
|
|
1083
|
-
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(In(C,t.metainfo??`data/${F}.metainfo.xml.in`),n,t.force??!1,`metainfo`)),I===`app`&&(trackWrite(writeIfFresh(In(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(In(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(In(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
|
|
1083
|
+
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(In(C,t.metainfo??`data/${F}.metainfo.xml.in`),n,t.force??!1,`metainfo`)),I===`app`&&(trackWrite(writeIfFresh(In(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(In(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(In(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 EV,DV=__esmMin(()=>{_e(),af(),Xn(),hv(),EV={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=In(n,t.manifest??findDefaultManifest(n));if(!existsSync(S))throw Error(`gjsify flatpak build: manifest ${S} not found`);let C=In(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=In(n,t.repo);mkdirSync(Hn(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=In(n,t.bundle);mkdirSync(Hn(C),{recursive:!0}),await runFlatpak([`build-bundle`,In(n,t.repo),C,readManifestAppId(S)],{verbose:t.verbose})}if(t.tarball){let S=In(n,t.tarball);mkdirSync(Hn(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(In(t,`yarn.lock`))?`yarn.lock`:existsSync(In(t,`package-lock.json`))?`package-lock.json`:`yarn.lock`}var OV,kV=__esmMin(()=>{_e(),hv(),af(),Xn(),OV={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=In(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=In(n,t.out??`flatpak-node-sources.json`);mkdirSync(Hn(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&&!jV.test(n)?{kind:`workspace`,target:C}:n.startsWith(`workspace:`)?{kind:`missing-workspace`}:jV.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,MV).join(`, `),F=t.length>MV?`, … (${t.length-MV} 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 AV)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 AV,jV,MV,NV=__esmMin(()=>{AV=[`dependencies`,`devDependencies`,`optionalDependencies`],jV=/^(link|file|portal|git\+|https?):/,MV=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=ot.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(`
|
|
1084
1084
|
`)){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(zn(t,n)))return n;return`gjsify-lock.json`}function focusedTarballs(t,n){let S=discoverWorkspaces(Hn(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(`
|
|
1085
|
-
`)}var
|
|
1085
|
+
`)}var PV,FV,IV=__esmMin(()=>{_e(),af(),Xn(),ht(),KI(),NV(),Uz(),cV(),PV=new Set([`sha256`,`sha512`]),FV={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:sV,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=In(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(!PV.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=In(n,t.out??`gjsify-sources.json`);mkdirSync(Hn(X),{recursive:!0}),writeFileSync(X,JSON.stringify(Y,null,2)+`
|
|
1086
1086
|
`),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
|
|
1087
1087
|
|
|
1088
1088
|
on:
|
|
@@ -1111,20 +1111,20 @@ jobs:
|
|
|
1111
1111
|
manifest-path: ${t.manifest}
|
|
1112
1112
|
bundle: ${t.bundle}
|
|
1113
1113
|
cache-key: ${t.cacheKey}
|
|
1114
|
-
`}var IV,LV=__esmMin(()=>{_e(),af(),Xn(),vR(),cV(),dV(),mV(),IV={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=In(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(Hn(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 buildTree$1(t){let n={name:`#root`,attrs:{},children:[],text:``},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)for(let t of S)t.text+=n.text;else if(n.kind===`open`){let C={name:HV(n.name),attrs:n.attributes,children:[],text:``};t.children.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function localized(t,n){let S=new Map;for(let C of kids(t,n)){let t=UV(C.text);t!==``&&!S.has(lang(C))&&S.set(lang(C),t)}return S}function parseHex(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];S.length===3&&(S=S.replace(/./g,t=>t+t));let C=Number.parseInt(S.slice(0,2),16)/255,N=Number.parseInt(S.slice(2,4),16)/255,F=Number.parseInt(S.slice(4,6),16)/255,I=Math.max(C,N,F),H=Math.min(C,N,F),W=(I+H)/2,q=I-H;return{s:q===0?0:q/(1-Math.abs(2*W-1)),l:W}}function readImageInfo(t){if(t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let u32=n=>(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0;return{kind:`raster`,width:u32(16),height:u32(20)}}if(t.length>=4&&t[0]===255&&t[1]===216){let n=2;for(;n+9<t.length;){if(t[n]!==255){n++;continue}let S=t[n+1];if(S===255){n++;continue}if(S>=192&&S<=207&&S!==196&&S!==200&&S!==204)return{kind:`raster`,height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+(t[n+2]<<8|t[n+3])}return null}let n=``;for(let S=0;S<Math.min(t.length,1024);S++)n+=String.fromCharCode(t[S]);return/<svg[\s>]/.test(n)?{kind:`svg`}:null}function termPattern(t,n=`iu`){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`(^|[^\\p{L}\\p{N}])${S}($|[^\\p{L}\\p{N}])`,n)}async function lintMetainfo(t,n={}){let S=[],add=(t,n,C,N,F)=>{S.push({rule:t,severity:n,message:F,location:N,url:`${RV}#${C}`})},C=child(buildTree$1(t),`component`);if(C===void 0)return add(`no-component`,`error`,`app-name`,`document`,`no <component> element found`),S;let loc=(t,n)=>n===``?t:`${t}[${n}]`,N=localized(C,`name`),F=localized(C,`summary`);for(let[t,n]of N){let S=loc(`name`,t),C=[...n].length;if(C>=20?add(`name-too-long`,`error`,`not-too-long`,S,`"${n}" is ${C} characters; a name must be shorter than 20`):C>15&&add(`name-long`,`warning`,`not-too-long`,S,`"${n}" is ${C} characters; ideally at most 15`),/\s[-–—:]\s|:\s|\(.+\)/.test(n)||/\b(web browser|editor|client|viewer|player)$/i.test(n)&&n.includes(` `))add(`name-extra-info`,`warning`,`just-the-name`,S,`"${n}" carries a description; keep just the name and put the rest in the summary`);else if(/[.-]/.test(n))add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" contains a dot or dash; avoid punctuation in names`);else if(/\p{L}/u.test(n)){let t=n.replace(/[^\p{L}]/gu,``);n===n.toLowerCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all lowercase`):t.length>1&&n===n.toUpperCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all uppercase (exempt only for an established brand such as VLC)`):!/\s/.test(n)&&/\p{Ll}\p{Lu}/u.test(n)&&add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is camel/pascal case`)}}let I=(n.technicalTerms??[...zV]).map(t=>({term:t,re:termPattern(t)}));for(let[t,n]of F){let S=loc(`summary`,t),C=[...n].length;C>35?add(`summary-too-long`,`error`,`not-too-long-1`,S,`"${n}" is ${C} characters; at most 35 allowed`):(C>25||C<10)&&add(`summary-length`,`warning`,`not-too-long-1`,S,`"${n}" is ${C} characters; ideal is 10 to 25`),/[.。]$/.test(n)&&add(`summary-full-stop`,`warning`,`no-weird-formatting-1`,S,`a summary does not end with a full stop`);let F=n.split(/\s+/).filter(t=>/^\p{L}/u.test(t)),H=F.filter(t=>/^\p{Lu}/u.test(t)).length;F.length>=3&&H/F.length>=.75&&add(`summary-title-case`,`warning`,`no-weird-formatting-1`,S,`use sentence case, not Title Case`);let W=VV[langBase(t===``?`en`:t)],q=n.split(/\s+/)[0]?.toLowerCase();W?.includes(q)&&add(`summary-article`,`warning`,`dont-start-with-an-article`,S,`starts with the article "${q}"; omit it or phrase it with a verb`);let Y=N.get(t)??N.get(``);Y!==void 0&&[...Y].length>=3&&termPattern(Y,`u`).test(n)&&add(`summary-repeats-name`,`warning`,`dont-repeat-the-name`,S,`repeats the app name "${Y}"`);let X=I.find(({re:t})=>t.test(n));X!==void 0&&add(`summary-technical`,`warning`,`not-technical`,S,`mentions "${X.term}"; say what the app does for people, not how it is built`)}let H=kids(C,`description`).find(t=>lang(t)===``)??child(C,`description`);if(H!==void 0){let t=F.get(``)??``,n=kids(H,`p`).filter(t=>lang(t)===``).map(t=>UV(t.text)),S=n.join(` `);t!==``&&n.length>0&&n[0].replace(/[.!]$/,``).toLowerCase()===t.toLowerCase()&&add(`description-repeats-summary`,`warning`,`dont-repeat-the-summary`,`description`,`the first paragraph repeats the summary`),t!==``&&[...S].length<Math.max(80,3*[...t].length)&&add(`description-short`,`warning`,`not-too-short`,`description`,`${[...S].length} characters; it should be substantially longer than the summary`);for(let t of[...kids(H,`ul`),...kids(H,`ol`)]){let n=kids(t,`li`).filter(t=>lang(t)===``).length;n>10&&add(`description-long-list`,`warning`,`no-super-long-lists`,`description`,`a list with ${n} items; group them or use paragraphs (max 10)`)}}let W=kids(child(C,`branding`),`color`).filter(t=>t.attrs.type===`primary`),q=W.find(t=>t.attrs.scheme_preference===`light`),Y=W.find(t=>t.attrs.scheme_preference===`dark`);if(q===void 0||Y===void 0)add(`branding-missing`,`warning`,`has-primary-brand-colors`,`branding`,`set two primary brand colors, scheme_preference="light" and "dark"`);else{let t=UV(q.text).toLowerCase(),n=UV(Y.text).toLowerCase();t===n&&add(`branding-identical`,`warning`,`good-brand-colors`,`branding`,`light and dark primary colors are the same`);let S=parseHex(t),C=parseHex(n);for(let[N,F,I]of[[`light`,S,t],[`dark`,C,n]])F!==null&&(F.s<.15||F.l>.93||F.l<.07)&&add(`branding-dull`,`warning`,`good-brand-colors`,`branding/${N}`,`${I} is near white, black or gray; brand colors should be colorful`);S!==null&&C!==null&&t!==n&&C.l>=S.l&&add(`branding-dark-not-darker`,`warning`,`good-brand-colors`,`branding/dark`,`the dark variant should be darker than the light one`)}if(n.probeImage!==void 0)for(let t of n.iconRefs??[]){let S=await n.probeImage(t);if(S!==null){S.kind===`raster`&&(S.width===S.height?S.width<256&&add(`icon-too-small`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; use SVG or at least 256×256`):add(`icon-not-square`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; the icon has to be square`));break}}let X=kids(child(C,`screenshots`),`screenshot`);if(X.length===0)add(`screenshot-missing`,`warning`,`at-least-one-screenshot`,`screenshots`,`at least one screenshot is expected`);else{let englishTag=t=>t===``||langBase(t)===`en`,isEnglish=t=>{let n=kids(t,`image`).map(lang);return englishTag(lang(t))&&(n.length===0||n.some(englishTag))};X.some(isEnglish)||add(`screenshot-no-english`,`warning`,`at-least-one-screenshot`,`screenshots`,`no screenshot without xml:lang (or in English)`),X[0].attrs.type!=="default"&&add(`screenshot-default-not-first`,`warning`,`at-least-one-screenshot`,`screenshot[1]`,`the first screenshot should be type="default" — it is the one users see first`);for(let t=0;t<X.length;t++){let S=X[t],C=`screenshot[${t+1}]`,N=kids(S,`caption`);N.length===0&&add(`screenshot-caption-missing`,`warning`,`image-captions`,C,`no <caption>`);for(let t of N){let n=UV(t.text),S=`${C}/${loc(`caption`,lang(t))}`;/[.。]$/.test(n)&&add(`caption-full-stop`,`warning`,`image-captions`,S,`a caption does not end with a full stop`),/^\d/.test(n)&&add(`caption-starts-with-number`,`warning`,`image-captions`,S,`a caption does not start with a number`),/[.!?]\s+\p{Lu}/u.test(n)&&add(`caption-multiple-sentences`,`warning`,`image-captions`,S,`a caption is one sentence`)}if(n.probeImage!==void 0){let t=kids(S,`image`).find(t=>(t.attrs.type??`source`)===`source`),N=t===void 0?``:UV(t.text),F=N===``?null:await n.probeImage(N);F?.kind===`raster`&&(F.width>2e3||F.height>1400)&&add(`screenshot-too-large`,`warning`,`reasonable-window-size`,C,`${F.width}×${F.height}; keep the window at most 1000×700 (2000×1400 on HiDPI)`)}}}for(let t of kids(child(C,`releases`),`release`)){let n=`release ${t.attrs.version??`?`}`,S=child(t,`description`),C=S===void 0?``:UV(S.text);if(C===``){add(`release-notes-missing`,`warning`,`release-notes-for-every-release`,n,`no release notes`);continue}BV.some(t=>t.test(C.replace(/[.!]+$/,``)))?add(`release-notes-generic`,`warning`,`no-bug-fixes-and-performance-improvements`,n,`"${C}" says nothing about what changed`):([...C].length>600||kids(child(S,`ul`),`li`).length>10)&&add(`release-notes-long`,`warning`,`short-but-informative`,n,`release notes are long; summarise what changed for users`)}return S}function summarizeFindings(t,n){let S=0,C=0;for(let N of t)N.severity===`error`||n?S++:C++;return{errors:S,warnings:C}}function formatFinding(t,n){return`${(n?`error`:t.severity).padEnd(7)} ${t.rule} ${t.location}: ${t.message}\n ${t.url}`}var RV,zV,BV,VV,HV,child,kids,UV,lang,langBase,WV=__esmMin(()=>{Ye(),RV=`https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines`,zV=`GTK.GTK3.GTK4.Qt.Qt5.Qt6.libadwaita.Electron.Rust.Python.JavaScript.TypeScript.GJS.Flatpak.written in.open source.open-source.free software.FOSS.app.application.tool.client.wrapper.App.Anwendung.Werkzeug`.split(`.`),BV=[/^(minor |various |general |misc(ellaneous)? )?bug ?fix(es)?( (and|&) (minor )?(performance )?(improvements?|fixes|tweaks))?$/i,/^(minor |various |general )?(performance )?improvements?( (and|&) (bug ?fix(es)?|fixes))?$/i,/^bug ?fix(es)?,? (and )?(performance|stability) improvements?$/i,/^(performance|stability) (improvements?|fixes)( (and|&) bug ?fix(es)?)?$/i,/^(fehlerbehebungen?|fehlerkorrekturen?|verbesserungen)( (und|&) (fehlerbehebungen?|verbesserungen|leistungsverbesserungen))?$/i,/^(kleinere )?(fehlerbehebungen|verbesserungen)$/i],VV={en:[`a`,`an`,`the`],de:[`ein`,`eine`,`einen`,`einem`,`einer`,`der`,`die`,`das`,`den`,`dem`]},HV=__name$1(t=>t.startsWith(`_`)?t.slice(1):t,`normName`),__name$1(buildTree$1,`buildTree`),child=(t,n)=>t?.children.find(t=>t.name===n),kids=(t,n)=>t?.children.filter(t=>t.name===n)??[],UV=__name$1(t=>t.replace(/\s+/g,` `).trim(),`clean`),lang=t=>t.attrs[`xml:lang`]??``,langBase=t=>t.split(/[_\-.@]/)[0].toLowerCase()});function appstreamValidateArgs(t,n=!1){return[`validate`,`--strict`,...n?[]:[`--no-net`],t]}function builderLintViaFlatpak(t){return{bin:`flatpak`,args:[`run`,`--command=flatpak-builder-lint`,GV,...t]}}async function runQuality(t,n,S){let C=Hn(t),probeImage=async t=>{if(/^https?:\/\//.test(t)){if(!S.qualityNetwork)return null;try{let n=await fetch(t);return n.ok?readImageInfo(new Uint8Array(await n.arrayBuffer())):null}catch{return null}}let n=In(C,t);return existsSync(n)?readImageInfo(new Uint8Array(readFileSync(n))):null},N=n??``,F=N?[`icons/hicolor/scalable/apps/${N}.svg`,`icons/${N}.svg`,`${N}.svg`,`${N}.png`,`../data/icons/hicolor/scalable/apps/${N}.svg`]:[],I=await lintMetainfo(readFileSync(t,`utf-8`),{probeImage,iconRefs:F}),H=S.strict===!0,{errors:W,warnings:q}=summarizeFindings(I,H);if(S.json)ge.log(JSON.stringify({file:t,errors:W,warnings:q,findings:I.map(t=>({...t,severity:H?`error`:t.severity}))},null,2));else{for(let t of I)ge.log(formatFinding(t,H));ge.log(`[gjsify flatpak check] ${W===0?`OK`:`FAIL`}: quality ${t} — ${W} error(s), ${q} warning(s)`)}return W===0}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 In(S,t);if(n)return In(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return In(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 runBuilderLint(t,n){let S=await runLinter(`flatpak-builder-lint`,t,n);if(S!==`missing`)return S===`ok`;if(await builderAppInstalled()){let S=builderLintViaFlatpak(t);return await runLinter(S.bin,S.args,n)===`ok`}return ge.error(`[gjsify flatpak check] flatpak-builder-lint not found in PATH, and ${GV} is not installed.\nInstall via:\n flatpak install -y flathub ${GV}`),!1}async function builderAppInstalled(){try{return(await spawnToCompletion(`flatpak`,[`info`,GV],{completion:`return`,stdio:`capture`})).code===0}catch{return!1}}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`?`missing`:(ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),`fail`)}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?`ok`:`fail`}var GV,KV,qV=__esmMin(()=>{_e(),af(),Xn(),hv(),cV(),vR(),WV(),GV=`org.flatpak.Builder`,KV={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 --no-net` (default: true).",type:`boolean`,default:!0}).option(`quality`,{description:`Run Flathub's quality guidelines (name, summary, branding, screenshots, release notes) on the MetaInfo (default: true).`,type:`boolean`,default:!0}).option(`strict`,{description:`Treat quality warnings as errors.`,type:`boolean`,default:!1}).option(`json`,{description:`Print the quality findings as JSON (and nothing else on stdout).`,type:`boolean`,default:!1}).option(`quality-network`,{description:`Let the quality check fetch http(s) screenshot/icon URLs to measure their size.`,type:`boolean`,default:!1}).option(`appstream-network`,{description:"Let `appstreamcli` fetch the MetaInfo URLs to check they are reachable.",type:`boolean`,default:!1}).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=In(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,appstreamValidateArgs(F,t.appstreamNetwork===!0),t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.quality!==!1&&(existsSync(F)?await runQuality(F,C,t)||I++:ge.warn(`[gjsify flatpak check] skipping quality check — ${F} not found`)),t.builderLint!==!1&&!t.json){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runBuilderLint([`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runBuilderLint([`repo`,In(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 JV(`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 JV(`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 JV(`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 JV(`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 zn(process.env.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(zn(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(In(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await JV(`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 JV(`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(`
|
|
1114
|
+
`}var LV,RV=__esmMin(()=>{_e(),af(),Xn(),vR(),cV(),dV(),mV(),LV={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=In(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(Hn(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 buildTree$1(t){let n={name:`#root`,attrs:{},children:[],text:``},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)for(let t of S)t.text+=n.text;else if(n.kind===`open`){let C={name:UV(n.name),attrs:n.attributes,children:[],text:``};t.children.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function localized(t,n){let S=new Map;for(let C of kids(t,n)){let t=WV(C.text);t!==``&&!S.has(lang(C))&&S.set(lang(C),t)}return S}function parseHex(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];S.length===3&&(S=S.replace(/./g,t=>t+t));let C=Number.parseInt(S.slice(0,2),16)/255,N=Number.parseInt(S.slice(2,4),16)/255,F=Number.parseInt(S.slice(4,6),16)/255,I=Math.max(C,N,F),H=Math.min(C,N,F),W=(I+H)/2,q=I-H;return{s:q===0?0:q/(1-Math.abs(2*W-1)),l:W}}function readImageInfo(t){if(t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let u32=n=>(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0;return{kind:`raster`,width:u32(16),height:u32(20)}}if(t.length>=4&&t[0]===255&&t[1]===216){let n=2;for(;n+9<t.length;){if(t[n]!==255){n++;continue}let S=t[n+1];if(S===255){n++;continue}if(S>=192&&S<=207&&S!==196&&S!==200&&S!==204)return{kind:`raster`,height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+(t[n+2]<<8|t[n+3])}return null}let n=``;for(let S=0;S<Math.min(t.length,1024);S++)n+=String.fromCharCode(t[S]);return/<svg[\s>]/.test(n)?{kind:`svg`}:null}function termPattern(t,n=`iu`){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`(^|[^\\p{L}\\p{N}])${S}($|[^\\p{L}\\p{N}])`,n)}async function lintMetainfo(t,n={}){let S=[],add=(t,n,C,N,F)=>{S.push({rule:t,severity:n,message:F,location:N,url:`${zV}#${C}`})},C=child(buildTree$1(t),`component`);if(C===void 0)return add(`no-component`,`error`,`app-name`,`document`,`no <component> element found`),S;let loc=(t,n)=>n===``?t:`${t}[${n}]`,N=localized(C,`name`),F=localized(C,`summary`);for(let[t,n]of N){let S=loc(`name`,t),C=[...n].length;if(C>=20?add(`name-too-long`,`error`,`not-too-long`,S,`"${n}" is ${C} characters; a name must be shorter than 20`):C>15&&add(`name-long`,`warning`,`not-too-long`,S,`"${n}" is ${C} characters; ideally at most 15`),/\s[-–—:]\s|:\s|\(.+\)/.test(n)||/\b(web browser|editor|client|viewer|player)$/i.test(n)&&n.includes(` `))add(`name-extra-info`,`warning`,`just-the-name`,S,`"${n}" carries a description; keep just the name and put the rest in the summary`);else if(/[.-]/.test(n))add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" contains a dot or dash; avoid punctuation in names`);else if(/\p{L}/u.test(n)){let t=n.replace(/[^\p{L}]/gu,``);n===n.toLowerCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all lowercase`):t.length>1&&n===n.toUpperCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all uppercase (exempt only for an established brand such as VLC)`):!/\s/.test(n)&&/\p{Ll}\p{Lu}/u.test(n)&&add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is camel/pascal case`)}}let I=(n.technicalTerms??[...BV]).map(t=>({term:t,re:termPattern(t)}));for(let[t,n]of F){let S=loc(`summary`,t),C=[...n].length;C>35?add(`summary-too-long`,`error`,`not-too-long-1`,S,`"${n}" is ${C} characters; at most 35 allowed`):(C>25||C<10)&&add(`summary-length`,`warning`,`not-too-long-1`,S,`"${n}" is ${C} characters; ideal is 10 to 25`),/[.。]$/.test(n)&&add(`summary-full-stop`,`warning`,`no-weird-formatting-1`,S,`a summary does not end with a full stop`);let F=n.split(/\s+/).filter(t=>/^\p{L}/u.test(t)),H=F.filter(t=>/^\p{Lu}/u.test(t)).length;F.length>=3&&H/F.length>=.75&&add(`summary-title-case`,`warning`,`no-weird-formatting-1`,S,`use sentence case, not Title Case`);let W=HV[langBase(t===``?`en`:t)],q=n.split(/\s+/)[0]?.toLowerCase();W?.includes(q)&&add(`summary-article`,`warning`,`dont-start-with-an-article`,S,`starts with the article "${q}"; omit it or phrase it with a verb`);let Y=N.get(t)??N.get(``);Y!==void 0&&[...Y].length>=3&&termPattern(Y,`u`).test(n)&&add(`summary-repeats-name`,`warning`,`dont-repeat-the-name`,S,`repeats the app name "${Y}"`);let X=I.find(({re:t})=>t.test(n));X!==void 0&&add(`summary-technical`,`warning`,`not-technical`,S,`mentions "${X.term}"; say what the app does for people, not how it is built`)}let H=kids(C,`description`).find(t=>lang(t)===``)??child(C,`description`);if(H!==void 0){let t=F.get(``)??``,n=kids(H,`p`).filter(t=>lang(t)===``).map(t=>WV(t.text)),S=n.join(` `);t!==``&&n.length>0&&n[0].replace(/[.!]$/,``).toLowerCase()===t.toLowerCase()&&add(`description-repeats-summary`,`warning`,`dont-repeat-the-summary`,`description`,`the first paragraph repeats the summary`),t!==``&&[...S].length<Math.max(80,3*[...t].length)&&add(`description-short`,`warning`,`not-too-short`,`description`,`${[...S].length} characters; it should be substantially longer than the summary`);for(let t of[...kids(H,`ul`),...kids(H,`ol`)]){let n=kids(t,`li`).filter(t=>lang(t)===``).length;n>10&&add(`description-long-list`,`warning`,`no-super-long-lists`,`description`,`a list with ${n} items; group them or use paragraphs (max 10)`)}}let W=kids(child(C,`branding`),`color`).filter(t=>t.attrs.type===`primary`),q=W.find(t=>t.attrs.scheme_preference===`light`),Y=W.find(t=>t.attrs.scheme_preference===`dark`);if(q===void 0||Y===void 0)add(`branding-missing`,`warning`,`has-primary-brand-colors`,`branding`,`set two primary brand colors, scheme_preference="light" and "dark"`);else{let t=WV(q.text).toLowerCase(),n=WV(Y.text).toLowerCase();t===n&&add(`branding-identical`,`warning`,`good-brand-colors`,`branding`,`light and dark primary colors are the same`);let S=parseHex(t),C=parseHex(n);for(let[N,F,I]of[[`light`,S,t],[`dark`,C,n]])F!==null&&(F.s<.15||F.l>.93||F.l<.07)&&add(`branding-dull`,`warning`,`good-brand-colors`,`branding/${N}`,`${I} is near white, black or gray; brand colors should be colorful`);S!==null&&C!==null&&t!==n&&C.l>=S.l&&add(`branding-dark-not-darker`,`warning`,`good-brand-colors`,`branding/dark`,`the dark variant should be darker than the light one`)}if(n.probeImage!==void 0)for(let t of n.iconRefs??[]){let S=await n.probeImage(t);if(S!==null){S.kind===`raster`&&(S.width===S.height?S.width<256&&add(`icon-too-small`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; use SVG or at least 256×256`):add(`icon-not-square`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; the icon has to be square`));break}}let X=kids(child(C,`screenshots`),`screenshot`);if(X.length===0)add(`screenshot-missing`,`warning`,`at-least-one-screenshot`,`screenshots`,`at least one screenshot is expected`);else{let englishTag=t=>t===``||langBase(t)===`en`,isEnglish=t=>{let n=kids(t,`image`).map(lang);return englishTag(lang(t))&&(n.length===0||n.some(englishTag))};X.some(isEnglish)||add(`screenshot-no-english`,`warning`,`at-least-one-screenshot`,`screenshots`,`no screenshot without xml:lang (or in English)`),X[0].attrs.type!=="default"&&add(`screenshot-default-not-first`,`warning`,`at-least-one-screenshot`,`screenshot[1]`,`the first screenshot should be type="default" — it is the one users see first`);for(let t=0;t<X.length;t++){let S=X[t],C=`screenshot[${t+1}]`,N=kids(S,`caption`);N.length===0&&add(`screenshot-caption-missing`,`warning`,`image-captions`,C,`no <caption>`);for(let t of N){let n=WV(t.text),S=`${C}/${loc(`caption`,lang(t))}`;/[.。]$/.test(n)&&add(`caption-full-stop`,`warning`,`image-captions`,S,`a caption does not end with a full stop`),/^\d/.test(n)&&add(`caption-starts-with-number`,`warning`,`image-captions`,S,`a caption does not start with a number`),/[.!?]\s+\p{Lu}/u.test(n)&&add(`caption-multiple-sentences`,`warning`,`image-captions`,S,`a caption is one sentence`)}if(n.probeImage!==void 0){let t=kids(S,`image`).find(t=>(t.attrs.type??`source`)===`source`),N=t===void 0?``:WV(t.text),F=N===``?null:await n.probeImage(N);F?.kind===`raster`&&(F.width>2e3||F.height>1400)&&add(`screenshot-too-large`,`warning`,`reasonable-window-size`,C,`${F.width}×${F.height}; keep the window at most 1000×700 (2000×1400 on HiDPI)`)}}}for(let t of kids(child(C,`releases`),`release`)){let n=`release ${t.attrs.version??`?`}`,S=child(t,`description`),C=S===void 0?``:WV(S.text);if(C===``){add(`release-notes-missing`,`warning`,`release-notes-for-every-release`,n,`no release notes`);continue}VV.some(t=>t.test(C.replace(/[.!]+$/,``)))?add(`release-notes-generic`,`warning`,`no-bug-fixes-and-performance-improvements`,n,`"${C}" says nothing about what changed`):([...C].length>600||kids(child(S,`ul`),`li`).length>10)&&add(`release-notes-long`,`warning`,`short-but-informative`,n,`release notes are long; summarise what changed for users`)}return S}function summarizeFindings(t,n){let S=0,C=0;for(let N of t)N.severity===`error`||n?S++:C++;return{errors:S,warnings:C}}function formatFinding(t,n){return`${(n?`error`:t.severity).padEnd(7)} ${t.rule} ${t.location}: ${t.message}\n ${t.url}`}var zV,BV,VV,HV,UV,child,kids,WV,lang,langBase,GV=__esmMin(()=>{Ye(),zV=`https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines`,BV=`GTK.GTK3.GTK4.Qt.Qt5.Qt6.libadwaita.Electron.Rust.Python.JavaScript.TypeScript.GJS.Flatpak.written in.open source.open-source.free software.FOSS.app.application.tool.client.wrapper.App.Anwendung.Werkzeug`.split(`.`),VV=[/^(minor |various |general |misc(ellaneous)? )?bug ?fix(es)?( (and|&) (minor )?(performance )?(improvements?|fixes|tweaks))?$/i,/^(minor |various |general )?(performance )?improvements?( (and|&) (bug ?fix(es)?|fixes))?$/i,/^bug ?fix(es)?,? (and )?(performance|stability) improvements?$/i,/^(performance|stability) (improvements?|fixes)( (and|&) bug ?fix(es)?)?$/i,/^(fehlerbehebungen?|fehlerkorrekturen?|verbesserungen)( (und|&) (fehlerbehebungen?|verbesserungen|leistungsverbesserungen))?$/i,/^(kleinere )?(fehlerbehebungen|verbesserungen)$/i],HV={en:[`a`,`an`,`the`],de:[`ein`,`eine`,`einen`,`einem`,`einer`,`der`,`die`,`das`,`den`,`dem`]},UV=__name$1(t=>t.startsWith(`_`)?t.slice(1):t,`normName`),__name$1(buildTree$1,`buildTree`),child=(t,n)=>t?.children.find(t=>t.name===n),kids=(t,n)=>t?.children.filter(t=>t.name===n)??[],WV=__name$1(t=>t.replace(/\s+/g,` `).trim(),`clean`),lang=t=>t.attrs[`xml:lang`]??``,langBase=t=>t.split(/[_\-.@]/)[0].toLowerCase()});function appstreamValidateArgs(t,n=!1){return[`validate`,`--strict`,...n?[]:[`--no-net`],t]}function builderLintViaFlatpak(t){return{bin:`flatpak`,args:[`run`,`--command=flatpak-builder-lint`,KV,...t]}}async function runQuality(t,n,S){let C=Hn(t),probeImage=async t=>{if(/^https?:\/\//.test(t)){if(!S.qualityNetwork)return null;try{let n=await fetch(t);return n.ok?readImageInfo(new Uint8Array(await n.arrayBuffer())):null}catch{return null}}let n=In(C,t);return existsSync(n)?readImageInfo(new Uint8Array(readFileSync(n))):null},N=n??``,F=N?[`icons/hicolor/scalable/apps/${N}.svg`,`icons/${N}.svg`,`${N}.svg`,`${N}.png`,`../data/icons/hicolor/scalable/apps/${N}.svg`]:[],I=await lintMetainfo(readFileSync(t,`utf-8`),{probeImage,iconRefs:F}),H=S.strict===!0,{errors:W,warnings:q}=summarizeFindings(I,H);if(S.json)ge.log(JSON.stringify({file:t,errors:W,warnings:q,findings:I.map(t=>({...t,severity:H?`error`:t.severity}))},null,2));else{for(let t of I)ge.log(formatFinding(t,H));ge.log(`[gjsify flatpak check] ${W===0?`OK`:`FAIL`}: quality ${t} — ${W} error(s), ${q} warning(s)`)}return W===0}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 In(S,t);if(n)return In(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return In(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 runBuilderLint(t,n){let S=await runLinter(`flatpak-builder-lint`,t,n);if(S!==`missing`)return S===`ok`;if(await builderAppInstalled()){let S=builderLintViaFlatpak(t);return await runLinter(S.bin,S.args,n)===`ok`}return ge.error(`[gjsify flatpak check] flatpak-builder-lint not found in PATH, and ${KV} is not installed.\nInstall via:\n flatpak install -y flathub ${KV}`),!1}async function builderAppInstalled(){try{return(await spawnToCompletion(`flatpak`,[`info`,KV],{completion:`return`,stdio:`capture`})).code===0}catch{return!1}}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`?`missing`:(ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),`fail`)}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?`ok`:`fail`}var KV,qV,JV=__esmMin(()=>{_e(),af(),Xn(),hv(),cV(),vR(),GV(),KV=`org.flatpak.Builder`,qV={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 --no-net` (default: true).",type:`boolean`,default:!0}).option(`quality`,{description:`Run Flathub's quality guidelines (name, summary, branding, screenshots, release notes) on the MetaInfo (default: true).`,type:`boolean`,default:!0}).option(`strict`,{description:`Treat quality warnings as errors.`,type:`boolean`,default:!1}).option(`json`,{description:`Print the quality findings as JSON (and nothing else on stdout).`,type:`boolean`,default:!1}).option(`quality-network`,{description:`Let the quality check fetch http(s) screenshot/icon URLs to measure their size.`,type:`boolean`,default:!1}).option(`appstream-network`,{description:"Let `appstreamcli` fetch the MetaInfo URLs to check they are reachable.",type:`boolean`,default:!1}).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=In(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,appstreamValidateArgs(F,t.appstreamNetwork===!0),t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.quality!==!1&&(existsSync(F)?await runQuality(F,C,t)||I++:ge.warn(`[gjsify flatpak check] skipping quality check — ${F} not found`)),t.builderLint!==!1&&!t.json){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runBuilderLint([`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runBuilderLint([`repo`,In(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 YV(`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 YV(`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 YV(`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 YV(`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 zn(process.env.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(zn(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(In(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await YV(`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 YV(`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(`
|
|
1115
1115
|
`)?`
|
|
1116
|
-
`:``)}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 JV,YV,XV=__esmMin(()=>{_e(),af(),Xn(),o_(),cv(),hv(),zu(),vR(),cV(),JV=promisify(execFile),YV={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: \`${sV}\`. Skipped when the tag does not carry it.`,type:`string`,default:sV}).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=zn(W,N.replace(`/`,`__`));mkdirSync(W,{recursive:!0}),await ensureClone(q,N,t.verbose);let Y=zn(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=zn(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 ZV(`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 ZV,QV,$V=__esmMin(()=>{_e(),af(),cv(),zu(),vR(),cV(),ZV=promisify(execFile),QV={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 In(In(Hn(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 eH,tH,nH=__esmMin(()=>{_e(),cv(),hv(),zu(),cr(),Xn(),eH=promisify(execFile),tH={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 eH(`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 eH(`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`)}}}),rH,iH=__esmMin(()=>{wV(),EV(),OV(),FV(),LV(),qV(),XV(),$V(),nH(),rH={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(CV.command,CV.description,CV.builder,CV.handler).command(TV.command,TV.description,TV.builder,TV.handler).command(DV.command,DV.description,DV.builder,DV.handler).command(PV.command,PV.description,PV.builder,PV.handler).command(IV.command,IV.description,IV.builder,IV.handler).command(KV.command,KV.description,KV.builder,KV.handler).command(YV.command,YV.description,YV.builder,YV.handler).command(QV.command,QV.description,QV.builder,QV.handler).command(tH.command,tH.description,tH.builder,tH.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 aH=__esmMin(()=>{});function createArArchive(t){let n=[encodeUtf8(oH)];for(let S of t)n.push(buildMemberHeader(S)),n.push(S.data),S.data.byteLength%2==1&&n.push(encodeUtf8(`
|
|
1116
|
+
`:``)}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 YV,XV,ZV=__esmMin(()=>{_e(),af(),Xn(),o_(),cv(),hv(),zu(),vR(),cV(),YV=promisify(execFile),XV={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: \`${sV}\`. Skipped when the tag does not carry it.`,type:`string`,default:sV}).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=zn(W,N.replace(`/`,`__`));mkdirSync(W,{recursive:!0}),await ensureClone(q,N,t.verbose);let Y=zn(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=zn(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 QV(`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 QV,$V,eH=__esmMin(()=>{_e(),af(),cv(),zu(),vR(),cV(),QV=promisify(execFile),$V={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 In(In(Hn(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 tH,nH,rH=__esmMin(()=>{_e(),cv(),hv(),zu(),cr(),Xn(),tH=promisify(execFile),nH={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 tH(`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 tH(`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`)}}}),iH,aH=__esmMin(()=>{TV(),DV(),kV(),IV(),RV(),JV(),ZV(),eH(),rH(),iH={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(wV.command,wV.description,wV.builder,wV.handler).command(EV.command,EV.description,EV.builder,EV.handler).command(OV.command,OV.description,OV.builder,OV.handler).command(FV.command,FV.description,FV.builder,FV.handler).command(LV.command,LV.description,LV.builder,LV.handler).command(qV.command,qV.description,qV.builder,qV.handler).command(XV.command,XV.description,XV.builder,XV.handler).command($V.command,$V.description,$V.builder,$V.handler).command(nH.command,nH.description,nH.builder,nH.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 oH=__esmMin(()=>{});function createArArchive(t){let n=[encodeUtf8(sH)];for(let S of t)n.push(buildMemberHeader(S)),n.push(S.data),S.data.byteLength%2==1&&n.push(encodeUtf8(`
|
|
1117
1117
|
`));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)+`\`
|
|
1118
|
-
`;if(n.length!==
|
|
1119
|
-
`,
|
|
1118
|
+
`;if(n.length!==cH)throw Error(`gjsify ship: internal error — ar header is ${n.length} bytes, expected ${cH}.`);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 sH,cH,lH=__esmMin(()=>{oH(),sH=`!<arch>
|
|
1119
|
+
`,cH=60});function warnAboutGjsFloor(t,n){return!pH[t]||compareVersions(n,`1.82.3`)<=0||compareVersions(n,`1.88.1`)===0?[]:[`gjsify ship: \`Depends: gjs (>= ${n})\` is not satisfiable on Debian stable — ${fH}. 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!hH[t]||compareVersions(n,`22`)<=0?[]:[`gjsify ship: \`Depends: nodejs (>= ${n})\` is not satisfiable on any current DEB stable/LTS — ${mH}. 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=>!_H.test(t)&&!S.has(t))}function deriveDepends(t,n){let S=n.interpreter===`node`?[`${uH[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:
|
|
1120
1120
|
"gjsify": { "ship": { "typelibPackages": { ${JSON.stringify(F[0])}: { "deb": "gir1.2-…", "rpm": "…" } } } }
|
|
1121
|
-
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(
|
|
1121
|
+
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(dH[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={...gH,...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 uH,dH,fH,pH,mH,hH,gH,_H,vH=__esmMin(()=>{uH={deb:`nodejs`,rpm:`nodejs(engine)`},dH={deb:`libglib2.0-bin`,rpm:`glib2`},fH=`trixie ships 1.82.3 and forky 1.88.1; 1.84 and 1.86 were skipped`,pH={deb:!0,rpm:!1},mH=`trixie ships 20, forky 24; Ubuntu 24.04 LTS ships 18 and 26.04 LTS 22`,hH={deb:!0,rpm:!1},gH={"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`}},_H=/^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 yH=__esmMin(()=>{sz()});function isUnder(t,n){return t.startsWith(`${n}/`)}var bH,xH=__esmMin(()=>{bH={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}/${bH.applications}`}),t.hasIcons&&S.push({probe:`gtk-update-icon-cache`,run:`gtk-update-icon-cache -q -t -f ${n}/${bH.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}/${bH.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(`
|
|
1122
1122
|
`);return{postinst:[`#!/bin/sh`,`set -e`,`if [ "$1" = "configure" ]; then`,C,`fi`,``].join(`
|
|
1123
1123
|
`),postrm:[`#!/bin/sh`,`set -e`,`if [ "$1" = "remove" ]; then`,C,`fi`,``].join(`
|
|
1124
1124
|
`)}}function renderRpmScriptlets(t,n){let S=cacheRefreshCommands(t,n);if(S.length===0)return{};let C=`${S.join(`
|
|
1125
|
-
`)}\n`;return{post:C,postun:C}}var
|
|
1125
|
+
`)}\n`;return{post:C,postun:C}}var SH=__esmMin(()=>{xH()});function isSymbolicIcon(t){return Wn(t).toLowerCase()===`.svg`?/(?:^|[\\/])symbolic[\\/]/.test(t)?!0:Un(t,Wn(t)).endsWith(`-symbolic`):!1}function iconThemeDir(t){if(isSymbolicIcon(t))return`symbolic`;if(Wn(t).toLowerCase()===`.svg`)return`scalable`;let n=/(?:^|[\\/])(\d{1,4})x\1(?:[\\/]|$)/.exec(t);if(n)return`${n[1]}x${n[1]}`;let S=Un(t,Wn(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||wH.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-TH.length;if(TH.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`,EH,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. ${CH}.`)}),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. ${CH}.`:``;throw Error(`${n}: rendering ${t.svg} through gjs failed (exit ${S.code??S.signal}).${N}${C===``?``:`\n ${C.split(`
|
|
1126
1126
|
`).join(`
|
|
1127
|
-
`)}`}`)}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=>Wn(t).toLowerCase()===`.svg`&&!isSymbolicIcon(t)),S=t.iconFiles.filter(t=>Wn(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
|
|
1127
|
+
`)}`}`)}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=>Wn(t).toLowerCase()===`.svg`&&!isSymbolicIcon(t)),S=t.iconFiles.filter(t=>Wn(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 CH,wH,TH,EH,DH=__esmMin(()=>{af(),Xn(),_L(),hv(),CH="Fedora: `sudo dnf install gjs librsvg2`, Debian/Ubuntu: `sudo apt install gjs gir1.2-rsvg-2.0`, macOS: `brew install gjs librsvg gobject-introspection`",wH=[137,80,78,71,13,10,26,10],TH=[0,0,0,0,73,69,78,68,174,66,96,130],EH=`imports.gi.versions.Rsvg = '2.0';
|
|
1128
1128
|
const { Rsvg, GLib } = imports.gi;
|
|
1129
1129
|
const Cairo = imports.cairo;
|
|
1130
1130
|
const [svg, ...sizes] = ARGV;
|
|
@@ -1143,85 +1143,85 @@ for (const text of sizes) {
|
|
|
1143
1143
|
GLib.unlink(path);
|
|
1144
1144
|
out[size] = GLib.base64_encode(bytes);
|
|
1145
1145
|
}
|
|
1146
|
-
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=DH.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 DH,OH,kH=__esmMin(()=>{aH(),EH(),DH=[{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`}],OH=[...new Set(DH.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 AH){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 AH,jH=__esmMin(()=>{aH(),EH(),AH=[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,JH,dataEntryAt(t),!1),dataEntry(t,H[t]);directory(C,1),entry(C+16,1,N,!0),directory(N,1),entry(N+16,JH,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,RH.size&255,RH.size>>8&255,0,0),leaStack(t,`rdi`,RH.args),t.push(49,192),movImm32(t,`ecx`,(RH.size-RH.args)/8),t.push(243,72,171),t.push(49,201),t.leaRip(`rdx`,`selfBuf`),movImm32(t,`r8d`,qH.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`,qH.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`,HH),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`,qH.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`,UH),movImm32(t,`r8d`,WH),leaStack(t,`r9`,RH.securityAttributes),movStackDword(t,RH.securityAttributes,BH),movStackDword(t,RH.securityAttributes+16,1),movStackDword(t,RH.args,GH),movStackDword(t,RH.args+8,KH),movStackDword(t,RH.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`,RH.startupInfo+80),movStackFromReg(t,`rbx`,RH.startupInfo+88),movStackFromReg(t,`rsi`,RH.startupInfo+96),movStackDword(t,RH.startupInfo+60,VH),t.jmp(`create`),t.label(`haveConsole`),t.push(69,49,246),t.label(`create`),movStackDword(t,RH.startupInfo,zH),t.push(49,201),t.leaRip(`rdx`,`cmdBuf`),t.push(69,49,192),t.push(69,49,201),movStackDword(t,RH.args,1),t.push(68,137,180,36);{let n=Buffer.alloc(4);n.writeInt32LE(RH.args+8),t.push(...n)}movStackDword(t,RH.args+16,0),movStackDword(t,RH.args+24,0),leaStack(t,`rax`,RH.startupInfo),movStackFromReg(t,`rax`,RH.args+32),leaStack(t,`rax`,RH.processInformation),movStackFromReg(t,`rax`,RH.args+40),t.callImport(`CreateProcessW`),t.push(133,192),t.jcc(`e`,`fail`),movRaxFromStack(t,RH.processInformation),t.push(72,137,193),movImm32(t,`edx`,-1),t.callImport(`WaitForSingleObject`),movRaxFromStack(t,RH.processInformation),t.push(72,137,193),leaStack(t,`rdx`,RH.exitCode),t.callImport(`GetExitCodeProcess`),t.push(139,140,36);{let n=Buffer.alloc(4);n.writeInt32LE(RH.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 LH)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 LH)n.push({symbol:`ilt.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`ilt.null`,bytes:new Uint8Array(8)});for(let t of LH){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(qH))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=FH,N=C+align(S,FH),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 LH){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,PH),Z=align(W,PH),te=PH,ne=te,re=ne+X,ie=N+align(W,FH),ae=t.icon===void 0?void 0:buildResourceSection(t.icon,ie),oe=ae===void 0?0:align(ae.length,PH),Q=re+Z,se=ae===void 0?2:3,ce=ae===void 0?N+align(W,FH):ie+align(ae.length,FH),le=Buffer.alloc(Q+oe);le.write(`MZ`,0,`ascii`),le.write(`This program cannot be run in DOS mode.\r\r
|
|
1147
|
-
$`,64,`ascii`),le.writeUInt32LE(
|
|
1148
|
-
`)}\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`),I=appleCategoryFor(t.categories);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
|
|
1149
|
-
`)}function renderPkgInfo(){return`${
|
|
1146
|
+
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=OH.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 OH,kH,AH=__esmMin(()=>{oH(),DH(),OH=[{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`}],kH=[...new Set(OH.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 jH){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 jH,MH=__esmMin(()=>{oH(),DH(),jH=[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,YH,dataEntryAt(t),!1),dataEntry(t,H[t]);directory(C,1),entry(C+16,1,N,!0),directory(N,1),entry(N+16,YH,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,zH.size&255,zH.size>>8&255,0,0),leaStack(t,`rdi`,zH.args),t.push(49,192),movImm32(t,`ecx`,(zH.size-zH.args)/8),t.push(243,72,171),t.push(49,201),t.leaRip(`rdx`,`selfBuf`),movImm32(t,`r8d`,JH.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`,JH.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`,UH),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`,JH.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`,WH),movImm32(t,`r8d`,GH),leaStack(t,`r9`,zH.securityAttributes),movStackDword(t,zH.securityAttributes,VH),movStackDword(t,zH.securityAttributes+16,1),movStackDword(t,zH.args,KH),movStackDword(t,zH.args+8,qH),movStackDword(t,zH.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`,zH.startupInfo+80),movStackFromReg(t,`rbx`,zH.startupInfo+88),movStackFromReg(t,`rsi`,zH.startupInfo+96),movStackDword(t,zH.startupInfo+60,HH),t.jmp(`create`),t.label(`haveConsole`),t.push(69,49,246),t.label(`create`),movStackDword(t,zH.startupInfo,BH),t.push(49,201),t.leaRip(`rdx`,`cmdBuf`),t.push(69,49,192),t.push(69,49,201),movStackDword(t,zH.args,1),t.push(68,137,180,36);{let n=Buffer.alloc(4);n.writeInt32LE(zH.args+8),t.push(...n)}movStackDword(t,zH.args+16,0),movStackDword(t,zH.args+24,0),leaStack(t,`rax`,zH.startupInfo),movStackFromReg(t,`rax`,zH.args+32),leaStack(t,`rax`,zH.processInformation),movStackFromReg(t,`rax`,zH.args+40),t.callImport(`CreateProcessW`),t.push(133,192),t.jcc(`e`,`fail`),movRaxFromStack(t,zH.processInformation),t.push(72,137,193),movImm32(t,`edx`,-1),t.callImport(`WaitForSingleObject`),movRaxFromStack(t,zH.processInformation),t.push(72,137,193),leaStack(t,`rdx`,zH.exitCode),t.callImport(`GetExitCodeProcess`),t.push(139,140,36);{let n=Buffer.alloc(4);n.writeInt32LE(zH.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 RH)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 RH)n.push({symbol:`ilt.${t}`,bytes:new Uint8Array(8)});n.push({symbol:`ilt.null`,bytes:new Uint8Array(8)});for(let t of RH){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(JH))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=IH,N=C+align(S,IH),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 RH){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,FH),Z=align(W,FH),te=FH,ne=te,re=ne+X,ie=N+align(W,IH),ae=t.icon===void 0?void 0:buildResourceSection(t.icon,ie),oe=ae===void 0?0:align(ae.length,FH),Q=re+Z,se=ae===void 0?2:3,ce=ae===void 0?N+align(W,IH):ie+align(ae.length,IH),le=Buffer.alloc(Q+oe);le.write(`MZ`,0,`ascii`),le.write(`This program cannot be run in DOS mode.\r\r
|
|
1147
|
+
$`,64,`ascii`),le.writeUInt32LE(PH,60),le.write(`PE\0\0`,PH,`ascii`),le.writeUInt16LE(NH,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(LH,176),le.writeUInt32LE(IH,184),le.writeUInt32LE(FH,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((RH.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 NH,PH,FH,IH,LH,RH,Emitter,zH,BH,VH,HH,UH,WH,GH,KH,qH,JH,YH,XH=__esmMin(()=>{MH(),NH=34404,PH=128,FH=512,IH=4096,LH=5368709120n,RH=[`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)}},zH={args:32,securityAttributes:80,startupInfo:112,processInformation:216,exitCode:240,size:272},BH=104,VH=24,HH=256,UH=134217728,WH=1073741824,GH=3,KH=2,qH=128,JH={sysBuf:264,selfBuf:520,tmpBuf:264,logBuf:600,cmdBuf:4096},YH=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 appleCategoryFor(t){for(let n of t??[]){let t=nU.get(n);if(t!==void 0)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(`
|
|
1148
|
+
`)}\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`),I=appleCategoryFor(t.categories);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`,eU),stringEntry(`CFBundleShortVersionString`,t.version),stringEntry(`CFBundleSignature`,tU),arrayEntry(`CFBundleSupportedPlatforms`,[`MacOSX`]),stringEntry(`CFBundleVersion`,`${t.version}-${t.release}`),...I===void 0?[]:[stringEntry(`LSApplicationCategoryType`,I)],`</dict>`,`</plist>`,``].join(`
|
|
1149
|
+
`)}function renderPkgInfo(){return`${eU}${tU}`}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(`
|
|
1150
1150
|
`),`</dict>`,`</plist>`,``].join(`
|
|
1151
|
-
`)}var
|
|
1152
|
-
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=n.executables?.find(t=>S===`bin/${t.name}`);if(N!==void 0)return launcherPath(t,{...n,binaryName:N.name,hasMainExecutable:!1});let F=`lib/${n.binaryName}/`,I=`${F}gi/`;return S.startsWith(I)?On.join(C.native,S.slice(I.length)):S.startsWith(F)?On.join(C.bundle,S.slice(F.length)):S.startsWith(`bin/`)?On.join(C.launcher,S.slice(4)):S.startsWith(`share/`)?On.join(C.data,S.slice(6)):On.join(C.other,S)}function nameFormBelowRoot(t,n){if(t.nameForm===void 0)return n;let S=t.nameForm,[C,...N]=n.split(On.sep);return N.length===0?n:[C,...N.map(t=>t.normalize(S))].join(On.sep)}function placeStage(t,n,S,C=[]){let N=new Map,F=[],claim=(n,S,C)=>{let I=nameFormBelowRoot(t,n),H=N.get(I);if(H!==void 0)throw Error(`gjsify ship: in the ${t.name} layout both ${H} and ${S} install as ${I}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);N.set(I,S),F.push({...C,path:I})};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
|
|
1151
|
+
`)}var ZH,QH,$H,eU,tU,nU,rU=__esmMin(()=>{ZH=`Contents/Info.plist`,QH=`Contents/PkgInfo`,$H=`Contents/Resources`,eU=`APPL`,tU=`????`,nU=new Map([[`Development`,`public.app-category.developer-tools`],[`Education`,`public.app-category.education`],[`Game`,`public.app-category.games`],[`Graphics`,`public.app-category.graphics-design`],[`Office`,`public.app-category.productivity`],[`System`,`public.app-category.utilities`],[`Utility`,`public.app-category.utilities`]])});function darwinFontsPath(t,n){let S=`${bH.fonts}/${t.appId}`,C=n.find(t=>t.path.startsWith(`${S}/`));if(C===void 0)return;let N=oU.darwin.dirs(t);return On.relative(N.other,On.dirname(place(oU.darwin,t,C.path)))}function appBundleDir(t){if(iU.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 assertUsableAsHelperName(t){if(t===``||t===`.`||t===`..`||iU.test(t)||t.includes(`\0`))throw Error(`gjsify ship: the macOS layout would name the carried interpreter "${t}" under \`Contents/Helpers\`, and that is not usable as a file name — empty, ".", ".." and anything containing "/", ":", "\\" or a NUL byte are refused. Set \`gjsify.ship.name\` to the display name you want.`);return t}function iconFor(t,n){if(t.kind===`app`){if(t.icon===void 0){if(oU[n].icon?.required!==!0)return;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){let S=t.dirs(n);return t.name===`darwin`&&n.hasMainExecutable===!0?On.join(S.other,`${n.binaryName}-launcher${t.launcherExt}`):On.join(S.launcher,`${n.binaryName}${t.launcherExt}`)}function mainExecutablePath(t,n){return On.join(t.dirs(n).launcher,`${n.binaryName}${t.launcherExt}`)}function windowsGuiLauncherPath(t){let n=oU.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 On.join(n.dirs(t).launcher,`${t.binaryName}.exe`)}function payloadArchExemptions(t,n){if(t===`win32`)return new Set([windowsGuiLauncherPath(n),...guiExecutables(n).map(t=>windowsGuiLauncherPath({...n,binaryName:t.name}))])}function guiExecutables(t){return(t.executables??[]).filter(t=>t.gui)}function windowsLaunchLogLeaf(t){return`${t.binaryName}.launch.log`}function layoutForOs(t){let n=cU.get(t);if(n===void 0)throw Error(`"${t}" is not a \`process.platform\` token this gjsify has a layout for. Known: ${sU.map(t=>oU[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(oU,n))return oU[n];let S=cU.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: ${sU.join(`, `)} (\`win32\` is accepted for \`windows\`, because that is the spelling \`--expect-target <os>-<arch>\` uses).`)}function hostLayout(t=process.platform){let n=cU.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 <${sU.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
|
|
1152
|
+
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=n.executables?.find(t=>S===`bin/${t.name}`);if(N!==void 0)return launcherPath(t,{...n,binaryName:N.name,hasMainExecutable:!1});let F=`lib/${n.binaryName}/`,I=`${F}gi/`;return S.startsWith(I)?On.join(C.native,S.slice(I.length)):S.startsWith(F)?On.join(C.bundle,S.slice(F.length)):S.startsWith(`bin/`)?On.join(C.launcher,S.slice(4)):S.startsWith(`share/`)?On.join(C.data,S.slice(6)):On.join(C.other,S)}function nameFormBelowRoot(t,n){if(t.nameForm===void 0)return n;let S=t.nameForm,[C,...N]=n.split(On.sep);return N.length===0?n:[C,...N.map(t=>t.normalize(S))].join(On.sep)}function placeStage(t,n,S,C=[]){let N=new Map,F=[],claim=(n,S,C)=>{let I=nameFormBelowRoot(t,n),H=N.get(I);if(H!==void 0)throw Error(`gjsify ship: in the ${t.name} layout both ${H} and ${S} install as ${I}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);N.set(I,S),F.push({...C,path:I})};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 iU,aU,oU,sU,cU,lU=__esmMin(()=>{Xn(),AH(),MH(),XH(),rU(),xH(),iU=/[/:\\]/,aU=[64,128,256],oU={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:``,helpers:``,plugins:``}),icon:{sizes:aU,writes:"the hicolor theme's raster icons (`share/icons/hicolor/<n>x<n>/apps/<appId>.png`)",required:!1},metadata:(t,n)=>{let S=iconFor(t,`linux`);if(S===void 0)return[];let C=new Set(n.map(t=>t.path)),N=[];for(let n of[...S.png.keys()].sort((t,n)=>t-n)){let F=`${bH.icons}/${n}x${n}/apps/${t.appId}.png`,I=S.png.get(n);I===void 0||C.has(F)||N.push({path:place(oU.linux,t,F),mode:420,source:{kind:`bytes`,data:I}})}return N},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:``,nameForm:`NFD`,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`,helpers:`${n}/Contents/Helpers`,plugins:`${n}/Contents/PlugIns`}},icon:{sizes:kH,writes:"the macOS bundle icon (`Contents/Resources/<binaryName>.icns`)",required:!0},metadata:(t,n)=>{let S=iconFor(t,`darwin`),C=S===void 0?void 0:`${t.binaryName}.icns`;return[{path:`${appBundleDir(t)}/${ZH}`,mode:420,source:{kind:`text`,text:renderInfoPlist(t,darwinFontsPath(t,n),C)}},{path:`${appBundleDir(t)}/${QH}`,mode:420,source:{kind:`text`,text:renderPkgInfo()}},...S===void 0||C===void 0?[]:[{path:`${appBundleDir(t)}/${$H}/${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:``,helpers:``,plugins:``}),icon:{sizes:jH,writes:"the Windows launcher icon (`.rsrc` of `<binaryName>.exe`)",required:!0},metadata:t=>{let n=iconFor(t,`windows`);return[{path:windowsGuiLauncherPath(t),mode:493,source:{kind:`bytes`,data:buildGuiLauncher({logLeaf:windowsLaunchLogLeaf(t),...n===void 0?{}:{icon:iconResources(n)}})}},...guiExecutables(t).map(S=>({path:windowsGuiLauncherPath({...t,binaryName:S.name}),mode:493,source:{kind:`bytes`,data:buildGuiLauncher({logLeaf:windowsLaunchLogLeaf({...t,binaryName:S.name}),...n===void 0?{}:{icon:iconResources(n)}})}}))]},arches:{only:[`x64`,`arm64`],why:"win32 runs on x64 natively and on arm64 via the MSVC closure ADR 0089 builds — both have a `@gjsify/gtk-runtime-win32-*` and `@gjsify/node-runtime-win32-*` to stage"}}},sU=Object.keys(oU),cU=new Map(sU.map(t=>[oU[t].os,oU[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,zn(t.workDir,Un(n)));return await runSchemaCompiler(t.workDir),[{path:pU,mode:420,source:{kind:`file`,path:zn(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(zn(t.workDir,On.basename(S.path)),S.data);return await runSchemaCompiler(t.workDir),{path:pU,mode:420,data:readFileSync(zn(t.workDir,`gschemas.compiled`))}}}function isSchemaSource(t){return t.startsWith(`${bH.schemas}/`)&&t.endsWith(`.gschema.xml`)}async function runSchemaCompiler(t){try{await uU(dU,[`--strict`,`--targetdir=${t}`,t])}catch(t){let n=t;throw n.code===`ENOENT`?Error(`gjsify ship: this artifact has no install step, so \`${dU}\` has to run HERE to turn the payload's schemas into \`${pU}\` — and it is not on PATH. Install it (${fU}). 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: \`${dU} --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
|
|
1153
1153
|
is written without it, so the app still aborts on the schema that was dropped. Fix the
|
|
1154
|
-
file it names, or drop it from \`gjsify.ship.schemas\`.`)}}var
|
|
1154
|
+
file it names, or drop it from \`gjsify.ship.schemas\`.`)}}var uU,dU,fU,pU,mU=__esmMin(()=>{cv(),Xn(),af(),zu(),xH(),uU=promisify(execFile),dU=`glib-compile-schemas`,fU="Fedora: `sudo dnf install glib2`, Debian/Ubuntu: `sudo apt install libglib2.0-bin`",pU=`${bH.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,bH.applications)&&t.endsWith(`.desktop`)),hasIcons:n.some(t=>isUnder(t,bH.icons)),hasSchemas:n.some(t=>isUnder(t,bH.schemas)&&t.endsWith(`.gschema.xml`)),hasMimeTypes:n.some(t=>isUnder(t,bH.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 gU.has(word(S))?after(S+1):word(S).includes(`==`)?after(S):_U.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<vU&&S.length>0;t++){let t=S.shift();if(t===``||t===`)`||t.startsWith(`::`))continue;let C=(cmdTokens(t)[0]?.text??``).toLowerCase();if(hU.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
|
|
1155
1155
|
at first launch, on the user's machine.
|
|
1156
1156
|
Either set \`gjsify.ship.app.${n.os}\` to "${F}" in the project this was staged from — it overrides
|
|
1157
1157
|
\`gjsify.app\` for that target alone — or fix the launcher: if it comes from \`gjsify.ship.extraFiles\`,
|
|
1158
|
-
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===
|
|
1159
|
-
`)[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
|
|
1160
|
-
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
|
|
1158
|
+
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===pU)};for(let C of t){if(!isUnder(C.path,`share`)||bU.some(t=>C.path===t||isUnder(C.path,t)))continue;let t=yU.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(`
|
|
1159
|
+
`)[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 xU[n]??null}if(n===4277009102||n===4277009103)return SU[(t[4]<<24|t[5]<<16|t[6]<<8|t[7])>>>0]??null;if(n===3472551422||n===3489328638)return SU[(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:CU[t[n+4]|t[n+5]<<8]??null}return null}function assertPayloadMatchesArch(t,n,S={}){for(let C of t){let t=readBinaryArch(C.data);if(!(t===null||t===n)&&!S.exempt?.has(C.path))throw Error(`gjsify ship: the payload is ${t}, but the package would be labelled ${n} — ${C.path} is built for ${t}.\n \`--arch\` names the architecture the PAYLOAD was built for; it does not cross-compile anything.
|
|
1160
|
+
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 hU,gU,_U,vU,yU,bU,xU,SU,CU,wU=__esmMin(()=>{af(),lU(),mU(),xH(),hU=new Set([`rem`,`set`,`setlocal`,`endlocal`,`echo`,`goto`,`exit`,`title`,`pause`,`shift`,`cd`,`chdir`,`pushd`,`popd`,`color`,`cls`,`verify`,`prompt`]),gU=new Set([`exist`,`defined`,`errorlevel`]),_U=new Set([`equ`,`neq`,`lss`,`leq`,`gtr`,`geq`]),vU=32,yU=[[bH.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`"]],[bH.mime,()=>[`inert`,"needs `update-mime-database`; detection runs off the compiled cache"]],[bH.icons,()=>[`inert`,"needs `gtk-update-icon-cache`; neither OS reads the hicolor theme"]],[bH.applications,()=>[`inert`,`a freedesktop desktop entry; neither OS reads one`]],[bH.metainfo,()=>[`inert`,`an AppStream component; neither OS reads one`]]],bU=[bH.locale,bH.fonts,pU],xU={3:`ia32`,21:`ppc64`,22:`s390x`,40:`arm`,62:`x64`,183:`arm64`,243:`riscv64`},SU={7:`ia32`,12:`arm`,16777223:`x64`,16777228:`arm64`},CU={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:`./${On.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
|
|
1161
1161
|
`),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(`
|
|
1162
|
-
`)}\n`}var
|
|
1162
|
+
`)}\n`}var TU=__esmMin(()=>{fl(),Xn(),sz(),lH(),vH(),yH(),SH(),wU()});function xmlEscape(t){return t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var EU=__esmMin(()=>{});function validateMimeTypes(t){let n=new Set;for(let S of t){if(!DU.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"?>
|
|
1163
1163
|
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
|
1164
1164
|
${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(`
|
|
1165
1165
|
`)}).join(`
|
|
1166
1166
|
`)}
|
|
1167
1167
|
</mime-info>
|
|
1168
|
-
`}var EU,DU=__esmMin(()=>{TU(),EU=/^[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(!OU.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(!kU.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 OU,kU,AU=__esmMin(()=>{OU=/^\d[A-Za-z0-9.+~]*$/,kU=/^[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(jU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(jU).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 on Linux, the Flatpak will carry no catalogue icon for an app store to show, 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,appId:q});n.push(...se.warnings);let ce=resolveShipNestedBundles({declared:C.nestedBundles,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),le=resolveShipHelperExecutables({declared:C.helperExecutables,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),ue=resolveShipMainExecutable({declared:C.mainExecutable,projectDir:t.projectDir,layoutOs:t.cli.layoutOs});if(t.cli.layoutOs!==`darwin`){let S=[...Array.isArray(C.nestedBundles)&&C.nestedBundles.length>0?[`nestedBundles`]:[],...Array.isArray(C.helperExecutables)&&C.helperExecutables.length>0?[`helperExecutables`]:[],...C.mainExecutable===void 0?[]:[`mainExecutable`]];S.length>0&&n.push(`gjsify ship: ${S.join(`/`)} apply to darwin only — not staged for ${t.cli.layoutOs}`)}return{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,formatFiles:F.formatFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],desktopExecArgs:C.desktopExecArgs??[],executables:resolveShipExecutables({declared:C.executables,binaryName:W,projectDir:t.projectDir,bundleDir:F.bundleDir}),nestedBundles:ce,helperExecutables:le,...ue===void 0?{}:{mainExecutableSource:ue,hasMainExecutable:!0},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,...C.snap?.plugs===void 0||C.snap.plugs.length===0?{}:{snapPlugs:C.snap.plugs}},metadata:I,warnings:n}}function resolveShipExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.executables` must be a list of `{ "name", "entry", "gui"? }` objects.');let S=new Set([t.binaryName]);return n.map((n,C)=>{let N=`gjsify.ship.executables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`name\` and \`entry\`.`);let{name:F,entry:I,gui:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: name, entry, gui.`);if(typeof F!=`string`||!NU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${NU} — it becomes \`bin/<name>\`, \`Contents/MacOS/<name>\` and \`<name>.cmd\`, so it is lower-case with no path separator or space.`);if(S.has(F))throw Error(`gjsify ship: \`${N}.name\` "${F}" is already taken — by the package's own \`binaryName\` or by an earlier entry. Two launchers cannot share one file name.`);if(S.add(F),typeof I!=`string`||I===``)throw Error(`gjsify ship: \`${N}.entry\` must be the project-relative path of a built bundle.`);if(H!==void 0&&typeof H!=`boolean`)throw Error(`gjsify ship: \`${N}.gui\` must be a boolean.`);let Y=Rn(I)?I:In(t.projectDir,I),X=Bn(t.bundleDir,Y);if(X===``||X.startsWith(`..`)||Rn(X))throw Error(`gjsify ship: \`${N}.entry\` ${I} is outside ${t.bundleDir}, the directory \`gjsify.main\` lives in — only that directory is staged, so the launcher would point at a file the package does not carry. Build the entries into one directory.`);return{name:F,entry:X.split(qn).join(On.sep),gui:H===!0}})}function assertUsableBundleLeaf(t,n,S){if(t===``||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`))throw Error(`gjsify ship: \`${n}.name\` "${t}" is not usable as a leaf under \`${S}\` — empty and ".", "..", and anything containing "/", "\\" or a NUL byte are refused.`);return t}function resolveShipNestedBundles(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.nestedBundles` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.nestedBundles[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative directory of a built bundle.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/PlugIns/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/PlugIns`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier nested bundle.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipHelperExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.helperExecutables` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.helperExecutables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative path of a prebuilt executable.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/Helpers/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/Helpers`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier helper executable.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipMainExecutable(t){let{declared:n}=t;if(n===void 0)return;if(typeof n!=`object`||!n||Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.mainExecutable` must be an object `{ "source" }`.');let{source:S,...C}=n,N=Object.keys(C);if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` has unknown key(s) ${N.join(`, `)}; known: source.`);if(typeof S!=`string`||S===``)throw Error("gjsify ship: `gjsify.ship.mainExecutable.source` must be the project-relative path of a prebuilt Mach-O executable.");if(t.layoutOs!==`darwin`)return;let F=Rn(S)?S:In(t.projectDir,S);if(!existsSync(F)||!statSync(F).isFile())throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} does not exist or is not a file.`);let I=Buffer.alloc(4),H=openSync(F,`r`);try{readSync(H,I,0,4,0)}finally{closeSync(H)}if(classifyBinary(I)!==`macho`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} is not a Mach-O binary (thin or universal). macOS resolves the host app record only for a native main executable, and the Mac App Store refuses a script; the generated launcher is staged as \`Contents/Resources/<binaryName>-launcher\`.`);return F}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(jU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(jU).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(jU).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 MU)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 jU,MU,NU,PU,FU,IU=__esmMin(()=>{DU(),af(),Xn(),CU(),_H(),mV(),AU(),jU={linux:!0,darwin:!0,win32:!0},MU=[[`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`}]],NU=/^[a-z0-9][a-z0-9._+-]*$/,PU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],FU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return BU.includes(t)}function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=In(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,resolveBundledTypelibs(S.bundledTypelibs,t.layoutOs)),formatFiles:discoverFormatFiles(n,S,t.layoutOs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverFormatFiles(t,n,S){let C={};if(S!==void 0&&S!==`linux`)return C;for(let[S,N]of Object.entries(n.formats??{})){if(!isFormatFilesId(S))throw Error(`gjsify ship: \`gjsify.ship.formats.${S}\` is not a format that carries its own files. Known: ${BU.join(`, `)}.`);C[S]={typelibFiles:discoverTypelibs(t,N?.bundledTypelibs),extraFiles:Object.fromEntries(Object.entries(N?.extraFiles??{}).map(([n,S])=>[n,In(t,S)]))}}return C}function resolveBundledTypelibs(t,n){if(t===void 0||Array.isArray(t))return t??[];let S=[`linux`,`darwin`,`win32`];for(let n of Object.keys(t))if(!S.includes(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs.${n}\` is not an OS this command assembles for. Known: ${S.join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's.`);if(n===void 0)throw Error("gjsify ship: `gjsify.ship.bundledTypelibs` is a per-OS table but no layout OS was given.");return t[n]??[]}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=In(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(zn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Bn(n,In(S,C));if(N===``||N.startsWith(`..`)||Rn(N))return t;let F=`${N.split(qn).join(On.sep)}${On.sep}`;return t.filter(t=>!`${t}${On.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=In(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(On.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:zn(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(`
|
|
1168
|
+
`}var DU,OU=__esmMin(()=>{EU(),DU=/^[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(!kU.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(!AU.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 kU,AU,jU=__esmMin(()=>{kU=/^\d[A-Za-z0-9.+~]*$/,AU=/^[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(MU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(MU).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 on Linux, the Flatpak will carry no catalogue icon for an app store to show, 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,appId:q});n.push(...se.warnings);let ce=resolveShipNestedBundles({declared:C.nestedBundles,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),le=resolveShipHelperExecutables({declared:C.helperExecutables,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),ue=resolveShipMainExecutable({declared:C.mainExecutable,projectDir:t.projectDir,layoutOs:t.cli.layoutOs});if(t.cli.layoutOs!==`darwin`){let S=[...Array.isArray(C.nestedBundles)&&C.nestedBundles.length>0?[`nestedBundles`]:[],...Array.isArray(C.helperExecutables)&&C.helperExecutables.length>0?[`helperExecutables`]:[],...C.mainExecutable===void 0?[]:[`mainExecutable`]];S.length>0&&n.push(`gjsify ship: ${S.join(`/`)} apply to darwin only — not staged for ${t.cli.layoutOs}`)}return{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,formatFiles:F.formatFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],desktopExecArgs:C.desktopExecArgs??[],executables:resolveShipExecutables({declared:C.executables,binaryName:W,projectDir:t.projectDir,bundleDir:F.bundleDir}),nestedBundles:ce,helperExecutables:le,...ue===void 0?{}:{mainExecutableSource:ue,hasMainExecutable:!0},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,...C.snap?.plugs===void 0||C.snap.plugs.length===0?{}:{snapPlugs:C.snap.plugs}},metadata:I,warnings:n}}function resolveShipExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.executables` must be a list of `{ "name", "entry", "gui"? }` objects.');let S=new Set([t.binaryName]);return n.map((n,C)=>{let N=`gjsify.ship.executables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`name\` and \`entry\`.`);let{name:F,entry:I,gui:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: name, entry, gui.`);if(typeof F!=`string`||!PU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${PU} — it becomes \`bin/<name>\`, \`Contents/MacOS/<name>\` and \`<name>.cmd\`, so it is lower-case with no path separator or space.`);if(S.has(F))throw Error(`gjsify ship: \`${N}.name\` "${F}" is already taken — by the package's own \`binaryName\` or by an earlier entry. Two launchers cannot share one file name.`);if(S.add(F),typeof I!=`string`||I===``)throw Error(`gjsify ship: \`${N}.entry\` must be the project-relative path of a built bundle.`);if(H!==void 0&&typeof H!=`boolean`)throw Error(`gjsify ship: \`${N}.gui\` must be a boolean.`);let Y=Rn(I)?I:In(t.projectDir,I),X=Bn(t.bundleDir,Y);if(X===``||X.startsWith(`..`)||Rn(X))throw Error(`gjsify ship: \`${N}.entry\` ${I} is outside ${t.bundleDir}, the directory \`gjsify.main\` lives in — only that directory is staged, so the launcher would point at a file the package does not carry. Build the entries into one directory.`);return{name:F,entry:X.split(qn).join(On.sep),gui:H===!0}})}function assertUsableBundleLeaf(t,n,S){if(t===``||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`))throw Error(`gjsify ship: \`${n}.name\` "${t}" is not usable as a leaf under \`${S}\` — empty and ".", "..", and anything containing "/", "\\" or a NUL byte are refused.`);return t}function resolveShipNestedBundles(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.nestedBundles` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.nestedBundles[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative directory of a built bundle.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/PlugIns/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/PlugIns`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier nested bundle.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipHelperExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.helperExecutables` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.helperExecutables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative path of a prebuilt executable.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/Helpers/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/Helpers`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier helper executable.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipMainExecutable(t){let{declared:n}=t;if(n===void 0)return;if(typeof n!=`object`||!n||Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.mainExecutable` must be an object `{ "source" }`.');let{source:S,...C}=n,N=Object.keys(C);if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` has unknown key(s) ${N.join(`, `)}; known: source.`);if(typeof S!=`string`||S===``)throw Error("gjsify ship: `gjsify.ship.mainExecutable.source` must be the project-relative path of a prebuilt Mach-O executable.");if(t.layoutOs!==`darwin`)return;let F=Rn(S)?S:In(t.projectDir,S);if(!existsSync(F)||!statSync(F).isFile())throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} does not exist or is not a file.`);let I=Buffer.alloc(4),H=openSync(F,`r`);try{readSync(H,I,0,4,0)}finally{closeSync(H)}if(classifyBinary(I)!==`macho`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} is not a Mach-O binary (thin or universal). macOS resolves the host app record only for a native main executable, and the Mac App Store refuses a script; the generated launcher is staged as \`Contents/Resources/<binaryName>-launcher\`.`);return F}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(MU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(MU).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(MU).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 NU)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 MU,NU,PU,FU,IU,LU=__esmMin(()=>{OU(),af(),Xn(),wU(),vH(),mV(),jU(),MU={linux:!0,darwin:!0,win32:!0},NU=[[`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`}]],PU=/^[a-z0-9][a-z0-9._+-]*$/,FU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],IU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return VU.includes(t)}function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=In(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,resolveBundledTypelibs(S.bundledTypelibs,t.layoutOs)),formatFiles:discoverFormatFiles(n,S,t.layoutOs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverFormatFiles(t,n,S){let C={};if(S!==void 0&&S!==`linux`)return C;for(let[S,N]of Object.entries(n.formats??{})){if(!isFormatFilesId(S))throw Error(`gjsify ship: \`gjsify.ship.formats.${S}\` is not a format that carries its own files. Known: ${VU.join(`, `)}.`);C[S]={typelibFiles:discoverTypelibs(t,N?.bundledTypelibs),extraFiles:Object.fromEntries(Object.entries(N?.extraFiles??{}).map(([n,S])=>[n,In(t,S)]))}}return C}function resolveBundledTypelibs(t,n){if(t===void 0||Array.isArray(t))return t??[];let S=[`linux`,`darwin`,`win32`];for(let n of Object.keys(t))if(!S.includes(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs.${n}\` is not an OS this command assembles for. Known: ${S.join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's.`);if(n===void 0)throw Error("gjsify ship: `gjsify.ship.bundledTypelibs` is a per-OS table but no layout OS was given.");return t[n]??[]}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=In(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(zn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Bn(n,In(S,C));if(N===``||N.startsWith(`..`)||Rn(N))return t;let F=`${N.split(qn).join(On.sep)}${On.sep}`;return t.filter(t=>!`${t}${On.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=In(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(On.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:zn(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(`
|
|
1169
1169
|
`)+`
|
|
1170
|
-
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=Rn(t)?t:In(S,t);if(C===N)continue;let I=Bn(n,C);I===``||I.startsWith(`..`)||Rn(I)||F.add(I.split(qn).join(On.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=Rn(n)?n:In(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=In(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=zn(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=>
|
|
1171
|
-
`)){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>
|
|
1172
|
-
`)}var
|
|
1170
|
+
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=Rn(t)?t:In(S,t);if(C===N)continue;let I=Bn(n,C);I===``||I.startsWith(`..`)||Rn(I)||F.add(I.split(qn).join(On.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=Rn(n)?n:In(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=In(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=zn(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=>RU.some(n=>t.toLowerCase().endsWith(n))).map(n=>zn(t,n.split(`/`).join(qn))).sort()}function discoverFonts(t,n){let S=n??`data/fonts`,C=n===void 0?zn(t,`data`,`fonts`):In(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),!zU.some(t=>C.toLowerCase().endsWith(t)))throw Error(`gjsify ship: \`gjsify.ship.fonts\` names ${n}, which is not a font face fontconfig will open (${zU.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),zU.some(n=>t.toLowerCase().endsWith(n))&&N.push(zn(C,t.split(`/`).join(qn)));if(N.length===0&&n!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${n}) holds no font face (${zU.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=BU.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 (${zU.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?[zn(t,`data`)]:[In(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=>zn(t,n.split(`/`).join(qn))).sort();if(S.length>0)return S}return[]}function discoverLicense(t,n){if(n!==void 0){let S=In(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 FU){let S=zn(n,t);if(existsSync(S))return S}}function discoverChangelog(t,n){if(n!==void 0){let S=In(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 IU){let S=zn(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=Hn(S);if(C===S)return[t];S=C}}function isProjectRoot(t){if(existsSync(zn(t,`.git`)))return!0;let n=zn(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=zn(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(On.join(...Bn(t,N).split(qn)))}};return walk(t),n.sort()}var RU,zU,BU,VU,HU=__esmMin(()=>{af(),Xn(),LU(),RU=[`.svg`,`.png`],zU=[`.ttf`,`.otf`,`.ttc`,`.otc`],BU=[`.woff`,`.woff2`,`.eot`],VU=Object.keys({deb:null,rpm:null,appimage:null})});function isNodeRuntimeTarget(t){return UU.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,zn(Hn(I),`bin`),C)}function complete(t,n,S){let C=zn(n,S),N=zn(n,`LICENSE`);return!existsSync(C)||!existsSync(N)?null:{source:t,binDir:n,nodePath:C,licensePath:N}}var UU,WU=__esmMin(()=>{af(),Xn(),XI(),UU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`]});function rfc822(t){let n=new Date(t*1e3),pad=t=>String(t).padStart(2,`0`);return`${GU[n.getUTCDay()]}, ${pad(n.getUTCDate())} ${KU[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(`
|
|
1171
|
+
`)){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>qU&&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(`
|
|
1172
|
+
`)}var GU,KU,qU,JU=__esmMin(()=>{GU=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],KU=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],qU=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 C of t.executables){let N=n.executableLaunchers?.[C.name];if(N===void 0||!n.bundleFiles.includes(C.entry))throw Error(`gjsify ship: \`gjsify.ship.executables\` "${C.name}" runs ${C.entry}, which is not in ${t.bundleDir} — build it before shipping, or the launcher would point at nothing.`);S.push({path:`bin/${C.name}`,mode:493,source:{kind:`text`,text:N}})}for(let N of n.bundleFiles)S.push({path:On.join(C,N),mode:isExecutableAsset(N)?493:420,source:{kind:`file`,path:On.join(t.bundleDir,N)}});if(S.push({path:`${bH.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:`${bH.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=Un(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:`${bH.schemas}/${C}`,mode:420,source:{kind:`file`,path:n}})}for(let n of t.typelibFiles)S.push({path:On.join(C,`gi`,Un(n)),mode:493,source:{kind:`file`,path:n}});t.mimeTypes.length>0&&S.push({path:`${bH.mime}/${t.appId}.xml`,mode:420,source:{kind:`text`,text:renderMimePackage(t.mimeTypes)}});for(let n of t.localeFiles)S.push({path:On.join(bH.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=`${bH.fonts}/${t.appId}/${Un(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)}})}let F=t.formatFiles[n.id];for(let n of F?.typelibFiles??[])N.push({path:On.join(`lib`,t.binaryName,`gi`,Un(n)),mode:493,source:{kind:`bytes`,data:new Uint8Array(await readFile$1(n))}});for(let[t,n]of Object.entries(F?.extraFiles??{}))N.push({path:assertInsidePrefix(t),mode:t.endsWith(`.so`)?493:420,source:{kind:`bytes`,data:new Uint8Array(await readFile$1(n))}});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(`
|
|
1173
1173
|
`).map(t=>t.trim()===``?` .`:` ${t}`).join(`
|
|
1174
1174
|
`);return[`Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/`,`Upstream-Name: ${t.name}`,...t.homepage?[`Source: ${t.homepage}`]:[],``,`Files: *`,`Copyright: ${t.maintainer}`,`License: ${t.license}`,S,``].join(`
|
|
1175
|
-
`)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=Wn(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${yH.icons}/${F}/apps/${I}${N}`,W=S.get(H);if(W!==void 0)throw Error(`gjsify ship: ${C} and ${W} both install as ${H}. An icon is keyed on its context and its size: \`symbolic\` is read from a \`symbolic/\` path component or a \`-symbolic\` filename, the size from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`). Give them distinguishable sizes, or point \`gjsify.ship.icon\` at a single file.`);S.set(H,C),n.push({path:H,mode:420,source:{kind:`file`,path:C}})}return n}function assertInsidePrefix(t){let n=On.normalize(t);if(On.isAbsolute(n)||n===`..`||n.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${t}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return n}function isExecutableAsset(t){return/\.(so|node|dylib)(\.\d+)*$/.test(t)}function normalise(t){let n=new Map;for(let S of t)n.set(S.path,S);return[...n.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var JU=__esmMin(()=>{qU(),vH(),EH(),DU(),bH(),Vd(),Xn()});function isGtkRuntimeTarget(t){return YU.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:`${ZU}/prebuilds/${t}`,dir:zn(I,`prebuilds`,t,`gtk`)}),N.push({source:`${ZU} sibling`,dir:zn(I,`..`,`gtk-runtime-${t}`,`gtk`)}));let H=gtkRuntimePackageName(t),W=resolveStagedPackage(H,n);W!==null&&N.push({source:H,dir:zn(Hn(W),`gtk`)}),n.fetchedGtkRuntimeDir!==void 0&&N.push({source:`${H} (fetched for this ship run)`,dir:zn(n.fetchedGtkRuntimeDir,`gtk`)});for(let t of N){let n=zn(t.dir,C),S=zn(t.dir,`girepository-1.0`);if(!(!existsSync(n)||!existsSync(S)))return{source:t.source,dir:t.dir,libDir:n,typelibDir:S}}return null}function resolveNodeGiAddon(t,n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=zn(S,`prebuilds`,t,XU);return existsSync(C)?{source:ZU,addonPath:C}:null}function resolveNodeGiRoot(t){let n=resolveStagedPackage(ZU,t);return n===null?null:Hn(n)}function resolveStagedPackage(t,n,{fromCli:S=!0}={}){let C=S?{bundleUrl:import.meta.url}:{};return n.cwd!==void 0&&(C.cwd=n.cwd),n.resolve!==void 0&&(C.resolve=n.resolve),resolveInstalledPackage(t,C)}function quartzBridgePackageName(t){return`${QU}-${t}`}function resolveQuartzBridge(t,n={}){if(!t.startsWith(`darwin-`))return null;let S=quartzBridgePackageName(t),dirOf=(t,n)=>{let S=resolveStagedPackage(`${t}/package.json`,n,{fromCli:!1});return S===null?null:Hn(S)},C=dirOf(S,n),N=null;if(C===null){if(N=dirOf(QU,n),N===null){let t=resolveStagedPackage(`@gjsify/adwaita-app`,n,{fromCli:!1}),S=t===null?null:packageRootOf(t);S!==null&&(N=dirOf(QU,{...n,cwd:S}))}N!==null&&(C=dirOf(S,{...n,cwd:N}))}if(C===null)return N===null?null:{unpopulated:`${S} is not installed`};let F=zn(C,`prebuilds`,t),I=zn(F,$U),H=zn(F,eW);return!existsSync(I)||!existsSync(H)?{unpopulated:`${S} holds no prebuilds/${t}/{${$U},${eW}}`}:{source:S,typelibPath:I,libraryPath:H}}function packageRootOf(t){let n=Hn(t);for(;;){if(existsSync(zn(n,`package.json`)))return n;let t=Hn(n);if(t===n)return null;n=t}}function resolveNodeGiPackage(t={}){let n=resolveNodeGiRoot(t);if(n===null)return null;let S=[`package.json`];for(let t of readdirSync(n,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1))t.isFile()&&t.name.endsWith(`.js`)&&S.push(t.name);let C=zn(n,`overrides`);if(existsSync(C))for(let t of listFilesRecursive(C))S.push(On.join(`overrides`,t));return S.length>1?{source:ZU,root:n,files:S.sort()}:null}function appRuntimePaths(t,n,S){let C=t.dirs(n),N=On.join(C.native,`node-gi`),F=On.join(N,`prebuilds`,S);return{nodeGiRoot:N,nodeGiPackageDir:On.join(C.bundle,`node_modules`,ZU),prebuildDir:F,gtkDir:On.join(F,`gtk`),addonPath:On.join(F,XU),interpreterPath:C.helpers===``?On.join(C.launcher,nodeRuntimeBinaryName(S)):On.join(C.helpers,assertUsableAsHelperName(n.name)),interpreterLicensePath:On.join(C.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(t){let n=appRuntimePaths(t.layout,t.identity,t.target),S=[],C={},N=[],F=[];t.interpreter===null?F.push(`no bundled interpreter — install \`@gjsify/node-runtime-${t.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(S.push({path:n.interpreterPath,mode:493,source:{kind:`file`,path:t.interpreter.nodePath}}),S.push({path:n.interpreterLicensePath,mode:420,source:{kind:`file`,path:t.interpreter.licensePath}}),C.interpreter=n.interpreterPath,N.push(`interpreter from ${t.interpreter.source}`));let I=resolveGtkRuntime(t.target,discoveryOptions(t));if(I!==null){for(let t of listFilesRecursive(I.dir)){let C=zn(I.dir,t.split(`/`).join(qn));S.push({path:On.join(n.gtkDir,t),mode:stagedMode(t,C),source:{kind:`file`,path:C}})}C.gtkRuntimeDir=n.gtkDir,N.push(`GTK closure from ${I.source}`);let H=resolveQuartzBridge(t.target,discoveryOptions(t));H!==null&&`unpopulated`in H?F.push(`Dock-click reopen bridge not carried — ${H.unpopulated}`):H!==null&&(S.push({path:On.join(n.gtkDir,`girepository-1.0`,$U),mode:420,source:{kind:`file`,path:H.typelibPath}}),S.push({path:On.join(n.gtkDir,nativeSubdirOf(t.target),eW),mode:493,source:{kind:`file`,path:H.libraryPath}}),N.push(`Dock-click reopen bridge from ${H.source}`))}else{let n=t.target.startsWith(`win32-`)?`bin`:`lib`,S=t.gtkFetchFailure===void 0?``:` — fetching it failed: ${t.gtkFetchFailure}`;F.push(`no GTK closure${S} — point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${n}/\` and \`girepository-1.0/\`, or install \`${gtkRuntimePackageName(t.target)}\` where the build can reach it`)}let H=resolveNodeGiPackage(discoveryOptions(t));if(H!==null){for(let t of H.files)S.push({path:On.join(n.nodeGiPackageDir,t),mode:420,source:{kind:`file`,path:zn(H.root,t.split(`/`).join(qn))}});N.push(`node-gi runtime (${H.files.length} file(s)) from ${H.source}`)}else F.push(`no node-gi JavaScript — install \`${ZU}\`; 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 \`${ZU}\`, whose \`prebuilds/${t.target}/${XU}\` is the binary built against that closure`):(S.push({path:n.addonPath,mode:493,source:{kind:`file`,path:W.addonPath}}),C.nodeGiAddon=n.addonPath,N.push(`node-gi addon from ${W.source}`)),{files:S,launcher:C,found:N,missing:F}}function nativeSubdirOf(t){return t.startsWith(`win32-`)?`bin`:`lib`}function discoveryOptions(t){let n={};return t.cwd!==void 0&&(n.cwd=t.cwd),t.env!==void 0&&(n.env=t.env),t.resolve!==void 0&&(n.resolve=t.resolve),t.fetchedGtkRuntimeDir!==void 0&&(n.fetchedGtkRuntimeDir=t.fetchedGtkRuntimeDir),n}function stagedMode(t,n){if(isExecutableAsset(t)||t.startsWith(`libexec/`)||t.startsWith(`bin/`))return 493;try{if(statSync(n).mode&73)return 493}catch{}return 420}var YU,XU,ZU,QU,$U,eW,tW=__esmMin(()=>{af(),Xn(),VU(),cU(),UU(),JU(),XI(),YU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`],XU=`node_gi.node`,ZU=`@gjsify/node-gi`,QU=`@gjsify/gtk-quartz-native`,$U=`GjsifyQuartz-1.0.typelib`,eW=`libgjsifyquartz.dylib`});function stageSubordinates(t){let n=t.layout.dirs(t.identity),S=[],C=[],N=[];for(let N of t.nestedBundles){if(n.plugins===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/PlugIns\` equivalent, so the nested bundle "${N.name}" has nowhere to go. \`gjsify.ship.nestedBundles\` is darwin-only; \`resolveShipNestedBundles\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.plugins,N.name);for(let t of listFilesRecursive(N.source)){let n=zn(N.source,...t.split(On.sep));S.push({path:On.join(F,t),mode:/^Contents\/MacOS\/[^/]+$/.test(t)?493:stagedMode(t,n),source:{kind:`file`,path:n}})}C.push({path:F,entitlements:N.entitlements})}for(let C of t.helperExecutables){if(n.helpers===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/Helpers\` equivalent, so the helper executable "${C.name}" has nowhere to go. \`gjsify.ship.helperExecutables\` is darwin-only; \`resolveShipHelperExecutables\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.helpers,C.name);S.push({path:F,mode:493,source:{kind:`file`,path:C.source}}),N.push({path:F,entitlements:C.entitlements})}if(t.mainExecutable!==void 0){if(t.layout.name!==`darwin`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` is darwin-only, but the ${t.layout.name} layout was asked to stage it — report this as a gjsify bug.`);S.push({path:mainExecutablePath(t.layout,t.identity),mode:493,source:{kind:`file`,path:t.mainExecutable}})}return{files:S,nestedBundles:C,helperExecutables:N}}function signedSubordinatesFor(t,n,S){let C=t.dirs(n);return{nestedBundles:S.nestedBundles.map(t=>({path:On.join(C.plugins,t.name),entitlements:t.entitlements})),helperExecutables:S.helperExecutables.map(t=>({path:On.join(C.helpers,t.name),entitlements:t.entitlements}))}}function plistStringValue(t,n){return RegExp(`<key>${n}</key>\\s*<string>([^<]*)</string>`).exec(t)?.[1]}function nestedBundlePlist(t,n){let S=t.find(t=>t.path===On.join(n,`Contents`,`Info.plist`));return S===void 0?void 0:new TextDecoder().decode(S.data)}function recordedNestedBundles(t,n){return n.map(n=>{let S=On.basename(n.path),C=nestedBundlePlist(t,n.path);if(C===void 0)return{name:S};let N=plistStringValue(C,`CFBundleIdentifier`),F=plistStringValue(C,`NSExtensionPointIdentifier`);return{name:S,...N===void 0?{}:{bundleId:N},...F===void 0?{}:{extensionPoint:F}}})}var nW=__esmMin(()=>{Xn(),VU(),tW(),cU()});function readManifest(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf-8`))}catch{return null}}function findInstalled(t,n){let S=n;for(;;){let n=zn(S,`node_modules`,...t.split(`/`));if(existsSync(zn(n,`package.json`)))return n;let C=Hn(S);if(C===S)return null;S=C}}function allows(t,n){let S=typeof t==`string`?[t]:t??[];if(S.includes(`!${n}`))return!1;let C=S.filter(t=>!t.startsWith(`!`));return C.length===0||C.includes(n)}function destinationOf(t){let n=t.split(qn),S=n.indexOf(`node_modules`);return S===-1||S===n.length-1?null:n.slice(S+1).join(`/`)}function resolveNodeModulesClosure(t,n,S={}){let{target:C,exclude:N=[]}=S,F=new Map,I=[],H=[],W=[],visit=(t,n,S,q)=>{if(t===rW)return;if(S.length>0&&N.includes(t)){W.includes(t)||W.push(t);return}let Y=findInstalled(t,n);if(Y===null){if(q){I.includes(t)||I.push(t);return}throw Error(`gjsify ship: \`${t}\` is not installed${S.length>0?` (needed by ${S.join(` > `)})`:``}. `+(S.length===0?"`gjsify.ship.nodeModules` names it, so the artifact must carry it — install it, or remove the entry.":`A package without its required dependency is an artifact that fails at its first import.`))}let X=destinationOf(Y);if(X===null)throw Error(`gjsify ship: ${Y} is not inside a node_modules directory, so it has no place to be staged.`);let Z=realpathSync(Y),te=readManifest(Z);if(te===null)throw Error(`gjsify ship: ${zn(Z,`package.json`)} is unreadable.`);if(S.length>0&&C!==void 0&&!(allows(te.os,C.os)&&allows(te.cpu,C.cpu))){H.includes(t)||H.push(t);return}let ne=F.get(X);if(ne!==void 0){if(ne.dir!==Z)throw Error(`gjsify ship: two installed copies of \`${t}\` would both be staged at node_modules/${X} (${ne.dir} and ${Z}).`);return}F.set(X,{name:t,version:te.version??`0.0.0`,dir:Z,dest:X});let re=[...S,t];for(let t of Object.keys(te.dependencies??{}))visit(t,Y,re,!1);for(let t of Object.keys(te.optionalDependencies??{}))visit(t,Y,re,!0)};for(let S of t)visit(S,n,[],!1);return{packages:[...F.values()].sort((t,n)=>t.dest<n.dest?-1:1),skippedOptional:I.sort(),skippedForTarget:H.sort(),excluded:W.sort(),target:C}}function prebuildPlatformOf(t){let n=/^(?:.*\/)?prebuilds\/([a-z0-9]+)-([a-z0-9_]+)(?:[-+][a-z0-9]+)?$/.exec(t);return n===null?null:[n[1],n[2]]}function listPackageFiles(t,n,S){let C=[],walk=N=>{for(let F of readdirSync(N,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let I=zn(N,F.name);if(F.isDirectory()){if(F.name===`node_modules`)continue;let C=n===void 0?null:prebuildPlatformOf(On.join(...Bn(t,I).split(qn)));if(C!==null&&(C[0]!==n.os||C[1]!==n.cpu)){S?.push(On.join(...Bn(t,I).split(qn)));continue}walk(I)}else if(F.isSymbolicLink())throw Error(`gjsify ship: ${I} is a symlink. The payload has to be self-contained — a package that links inside itself needs the link replaced by the file.`);else F.isFile()&&C.push(On.join(...Bn(t,I).split(qn)))}};return walk(t),C}function modeOf(t,n){return isExecutableAsset(t)||statSync(n).mode&73?493:420}function stageNodeModules(t,n){let S=[],C=[];t.skippedPrebuilds=C;for(let N of t.packages){let F=C.length;for(let F of listPackageFiles(N.dir,t.target,C)){let t=zn(N.dir,...F.split(`/`));S.push({path:On.join(n,`node_modules`,N.dest,F),mode:modeOf(F,t),source:{kind:`file`,path:t}})}for(let t=F;t<C.length;t++)C[t]=`${N.name}/${C[t]}`}return S}var rW,iW=__esmMin(()=>{af(),Xn(),JU(),rW=`@gjsify/node-gi`});async function acquireGtkRuntime(t){let n=t.discovery??{};if(resolveGtkRuntime(t.target,n)!==null)return{kind:`present`};let S=gtkRuntimePackageName(t.target),C=`${S}@${t.version}`;if((n.env??process.env).GJSIFY_GTK_RUNTIME_FETCH===`0`)return{kind:`failed`,reason:`GJSIFY_GTK_RUNTIME_FETCH=0 turned off the fetch of ${C}`};t.log?.(`${S} is not installed here, and is not meant to be — fetching ${C} into the cache (about 100 MB, once)`);let N;try{N=await t.ensure(C)}catch(t){return{kind:`failed`,reason:t instanceof Error?t.message:String(t)}}return resolveGtkRuntime(t.target,{...n,fetchedGtkRuntimeDir:N})===null?{kind:`failed`,reason:`${C} was fetched to ${N} but holds no complete gtk/ closure`}:{kind:`fetched`,dir:N}}var aW=__esmMin(()=>{tW()});function appDirFor(t){return zn(t,`appimage`,uW)}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=aU.linux.dirs(t).launcher,C=interpreterFloor(t),[N=`0`,F=`0`]=C.split(`.`);return[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(dirname "$(readlink -f "$0")")`,`if ! command -v ${t.app} >/dev/null 2>&1; then`,` echo "${shellSafe(t.name)} needs ${t.app}, and this system has none." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 127`,`fi`,`found=$(${t.app} --version 2>/dev/null | sed -n 's/[^0-9]*\\([0-9][0-9]*\\)\\.\\([0-9][0-9]*\\).*/\\1 \\2/p' | head -n 1 || true)`,"major=${found% *}","minor=${found#* }",`if [ -n "$major" ]; then`,` if [ "$major" -lt ${N} ] || { [ "$major" -eq ${N} ] && [ "$minor" -lt ${F} ]; }; then`,` echo "${shellSafe(t.name)} needs ${t.app} ${C} or newer, and this system has $major.$minor." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 126`,` fi`,`fi`,`exec "$here/usr/${S}/${t.binaryName}" "$@"`,``].join(`
|
|
1176
|
-
`)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${lW}/runtime-${t} (or point ${cW} 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(pW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${yH.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=`${yH.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 ${yH.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 ${yH.schemas}/ and no ${fU} 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 ${fU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${yH.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:dW,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:fW,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,[sW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${oW} 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: ${oW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${oW} 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 ${sW}=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(` `)} ${oW} ${n.join(` `)}`);let C=await spawnToCompletion(oW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${oW} 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 \`${oW}\`. \`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: ${oW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var oW,sW,cW,lW,uW,dW,fW,pW,mW=__esmMin(()=>{_e(),af(),Xn(),hv(),aH(),_H(),cU(),pU(),bH(),oW=`appimagetool`,sW=`APPIMAGE_EXTRACT_AND_RUN`,cW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,lW=`/usr/local/share/gjsify/appimage-runtime`,uW=`AppDir`,dW=`AppRun`,fW=`.DirIcon`,pW=[`.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(gW.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] ${hW} ${n.join(` `)}`);let S=await spawnToCompletion(hW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${hW} 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: ${hW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(_W.target,zn(t,_W.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${vW} ${n.join(` `)}`);let S=await spawnToCompletion(vW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${vW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${vW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var hW,gW,_W,vW,yW=__esmMin(()=>{_e(),af(),Xn(),hv(),hW=`hdiutil`,gW=/[/:]/,_W={name:`Applications`,target:`/Applications`},vW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var bW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function resolveHandMetainfo(t){let n=(t.configReleases?.length??0)>0,S,C;if(t.shipMetainfo!==void 0){if(S=`gjsify.ship.metainfo`,C=t.shipMetainfo,n)throw Error(`gjsify ship: \`gjsify.ship.metainfo\` and \`gjsify.ship.releases\` both describe the releases. The file is staged verbatim, so the config entries would be dropped without a word — keep the \`<releases>\` in ${C} and remove \`releases\` from the config.`)}else if(t.siteMetainfo!==void 0&&!n)S=`gjsify.site.metainfo`,C=t.siteMetainfo;else return;let N=In(t.projectDir,C);if(!existsSync(N))throw Error(`gjsify ship: \`${S}\` points at ${C}, which does not exist (${N}).`);return{path:C,xml:readFileSync(N,`utf-8`),key:S}}function readFacts(t){let n={releaseVersions:[]},S=[],C=``;for(let N of scanXml(t))if(N.kind===`open`){let t=N.name;t===`release`&&N.attributes.version!==void 0&&n.releaseVersions.push(N.attributes.version),t===`launchable`&&N.attributes.type===`desktop-id`&&!N.selfClosing?(S.push(`launchable`),C=``):t===`id`&&S.length===0&&n.id===void 0&&!N.selfClosing&&(S.push(`id`),C=``)}else if(N.kind===`text`)S.length>0&&(C+=N.text);else if(S.length>0){let t=S.pop();t===`id`?n.id=C.trim():t===`launchable`&&(n.launchable=C.trim())}return n}function checkHandMetainfo(t,n){let S=readFacts(t.xml);if(S.id!==n.appId)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <id>${S.id??``}</id>, but the package's application id is "${n.appId}" (\`gjsify.ship.appId\`). Stores resolve the component by the <id> inside the file, so one of the two is wrong.`);if(n.kind===`app`&&S.launchable!==void 0&&S.launchable!==`${n.appId}.desktop`)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <launchable type="desktop-id">${S.launchable}</launchable>, but \`ship\` stages the desktop entry as ${n.appId}.desktop.`);let C=[];return S.releaseVersions.includes(n.version)||C.push(`${t.path} has no <release version="${n.version}"> — the shipped component will not list the version it is packaged as.`),C}var xW=__esmMin(()=>{af(),Xn(),Ye()});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var SW=__esmMin(()=>{cv(),af(),o_(),Xn(),eV()});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 CW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,...t.snapPlugs===void 0||t.snapPlugs.length===0?{}:{snapPlugs:t.snapPlugs},executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,wW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${wW}, 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(!$W.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${$W.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=oU.map(t=>aU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.snapPlugs===void 0?{}:{snapPlugs:expectArray(t.snapPlugs,field(`snapPlugs`)).map((t,n)=>expectString(t,field(`snapPlugs[${n}]`)))},...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var wW,TW=__esmMin(()=>{af(),Xn(),CW(),Ch(),tG(),cU(),wW=`.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 \`${wW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var EW=__esmMin(()=>{af(),Xn(),VU(),TW()});function isSnapName(t){return t.length<=PW&&NW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${PW} characters, at least one letter)`),n.version.length>FW&&S.push(`the version "${n.version}" is longer than ${FW} characters`),n.summary.length>IW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${IW}`);for(let t of n.snapPlugs??[])LW.test(t)||S.push(`gjsify.ship.snap.plugs: "${t}" is not an interface name (lowercase letters, digits, hyphens)`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${yH.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${MW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${MW}/${snapDesktopPath(n)}`,"common-id":n.appId,environment:{GI_TYPELIB_PATH:AW}};n.snapPlugs!==void 0&&n.snapPlugs.length>0&&(S.plugs=[...n.snapPlugs]);let C={name:n.binaryName,title:n.name,base:OW,version:n.version,summary:n.summary,description:n.description.join(`
|
|
1175
|
+
`)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=Wn(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${bH.icons}/${F}/apps/${I}${N}`,W=S.get(H);if(W!==void 0)throw Error(`gjsify ship: ${C} and ${W} both install as ${H}. An icon is keyed on its context and its size: \`symbolic\` is read from a \`symbolic/\` path component or a \`-symbolic\` filename, the size from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`). Give them distinguishable sizes, or point \`gjsify.ship.icon\` at a single file.`);S.set(H,C),n.push({path:H,mode:420,source:{kind:`file`,path:C}})}return n}function assertInsidePrefix(t){let n=On.normalize(t);if(On.isAbsolute(n)||n===`..`||n.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${t}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return n}function isExecutableAsset(t){return/\.(so|node|dylib)(\.\d+)*$/.test(t)}function normalise(t){let n=new Map;for(let S of t)n.set(S.path,S);return[...n.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var YU=__esmMin(()=>{JU(),yH(),DH(),OU(),xH(),Vd(),Xn()});function isGtkRuntimeTarget(t){return XU.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:`${QU}/prebuilds/${t}`,dir:zn(I,`prebuilds`,t,`gtk`)}),N.push({source:`${QU} sibling`,dir:zn(I,`..`,`gtk-runtime-${t}`,`gtk`)}));let H=gtkRuntimePackageName(t),W=resolveStagedPackage(H,n);W!==null&&N.push({source:H,dir:zn(Hn(W),`gtk`)}),n.fetchedGtkRuntimeDir!==void 0&&N.push({source:`${H} (fetched for this ship run)`,dir:zn(n.fetchedGtkRuntimeDir,`gtk`)});for(let t of N){let n=zn(t.dir,C),S=zn(t.dir,`girepository-1.0`);if(!(!existsSync(n)||!existsSync(S)))return{source:t.source,dir:t.dir,libDir:n,typelibDir:S}}return null}function resolveNodeGiAddon(t,n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=zn(S,`prebuilds`,t,ZU);return existsSync(C)?{source:QU,addonPath:C}:null}function resolveNodeGiRoot(t){let n=resolveStagedPackage(QU,t);return n===null?null:Hn(n)}function resolveStagedPackage(t,n,{fromCli:S=!0}={}){let C=S?{bundleUrl:import.meta.url}:{};return n.cwd!==void 0&&(C.cwd=n.cwd),n.resolve!==void 0&&(C.resolve=n.resolve),resolveInstalledPackage(t,C)}function quartzBridgePackageName(t){return`${$U}-${t}`}function resolveQuartzBridge(t,n={}){if(!t.startsWith(`darwin-`))return null;let S=quartzBridgePackageName(t),dirOf=(t,n)=>{let S=resolveStagedPackage(`${t}/package.json`,n,{fromCli:!1});return S===null?null:Hn(S)},C=dirOf(S,n),N=null;if(C===null){if(N=dirOf($U,n),N===null){let t=resolveStagedPackage(`@gjsify/adwaita-app`,n,{fromCli:!1}),S=t===null?null:packageRootOf(t);S!==null&&(N=dirOf($U,{...n,cwd:S}))}N!==null&&(C=dirOf(S,{...n,cwd:N}))}if(C===null)return N===null?null:{unpopulated:`${S} is not installed`};let F=zn(C,`prebuilds`,t),I=zn(F,eW),H=zn(F,tW);return!existsSync(I)||!existsSync(H)?{unpopulated:`${S} holds no prebuilds/${t}/{${eW},${tW}}`}:{source:S,typelibPath:I,libraryPath:H}}function packageRootOf(t){let n=Hn(t);for(;;){if(existsSync(zn(n,`package.json`)))return n;let t=Hn(n);if(t===n)return null;n=t}}function resolveNodeGiPackage(t={}){let n=resolveNodeGiRoot(t);if(n===null)return null;let S=[`package.json`];for(let t of readdirSync(n,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1))t.isFile()&&t.name.endsWith(`.js`)&&S.push(t.name);let C=zn(n,`overrides`);if(existsSync(C))for(let t of listFilesRecursive(C))S.push(On.join(`overrides`,t));return S.length>1?{source:QU,root:n,files:S.sort()}:null}function appRuntimePaths(t,n,S){let C=t.dirs(n),N=On.join(C.native,`node-gi`),F=On.join(N,`prebuilds`,S);return{nodeGiRoot:N,nodeGiPackageDir:On.join(C.bundle,`node_modules`,QU),prebuildDir:F,gtkDir:On.join(F,`gtk`),addonPath:On.join(F,ZU),interpreterPath:C.helpers===``?On.join(C.launcher,nodeRuntimeBinaryName(S)):On.join(C.helpers,assertUsableAsHelperName(n.name)),interpreterLicensePath:On.join(C.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(t){let n=appRuntimePaths(t.layout,t.identity,t.target),S=[],C={},N=[],F=[];t.interpreter===null?F.push(`no bundled interpreter — install \`@gjsify/node-runtime-${t.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(S.push({path:n.interpreterPath,mode:493,source:{kind:`file`,path:t.interpreter.nodePath}}),S.push({path:n.interpreterLicensePath,mode:420,source:{kind:`file`,path:t.interpreter.licensePath}}),C.interpreter=n.interpreterPath,N.push(`interpreter from ${t.interpreter.source}`));let I=resolveGtkRuntime(t.target,discoveryOptions(t));if(I!==null){for(let t of listFilesRecursive(I.dir)){let C=zn(I.dir,t.split(`/`).join(qn));S.push({path:On.join(n.gtkDir,t),mode:stagedMode(t,C),source:{kind:`file`,path:C}})}C.gtkRuntimeDir=n.gtkDir,N.push(`GTK closure from ${I.source}`);let H=resolveQuartzBridge(t.target,discoveryOptions(t));H!==null&&`unpopulated`in H?F.push(`Dock-click reopen bridge not carried — ${H.unpopulated}`):H!==null&&(S.push({path:On.join(n.gtkDir,`girepository-1.0`,eW),mode:420,source:{kind:`file`,path:H.typelibPath}}),S.push({path:On.join(n.gtkDir,nativeSubdirOf(t.target),tW),mode:493,source:{kind:`file`,path:H.libraryPath}}),N.push(`Dock-click reopen bridge from ${H.source}`))}else{let n=t.target.startsWith(`win32-`)?`bin`:`lib`,S=t.gtkFetchFailure===void 0?``:` — fetching it failed: ${t.gtkFetchFailure}`;F.push(`no GTK closure${S} — point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${n}/\` and \`girepository-1.0/\`, or install \`${gtkRuntimePackageName(t.target)}\` where the build can reach it`)}let H=resolveNodeGiPackage(discoveryOptions(t));if(H!==null){for(let t of H.files)S.push({path:On.join(n.nodeGiPackageDir,t),mode:420,source:{kind:`file`,path:zn(H.root,t.split(`/`).join(qn))}});N.push(`node-gi runtime (${H.files.length} file(s)) from ${H.source}`)}else F.push(`no node-gi JavaScript — install \`${QU}\`; 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 \`${QU}\`, whose \`prebuilds/${t.target}/${ZU}\` is the binary built against that closure`):(S.push({path:n.addonPath,mode:493,source:{kind:`file`,path:W.addonPath}}),C.nodeGiAddon=n.addonPath,N.push(`node-gi addon from ${W.source}`)),{files:S,launcher:C,found:N,missing:F}}function nativeSubdirOf(t){return t.startsWith(`win32-`)?`bin`:`lib`}function discoveryOptions(t){let n={};return t.cwd!==void 0&&(n.cwd=t.cwd),t.env!==void 0&&(n.env=t.env),t.resolve!==void 0&&(n.resolve=t.resolve),t.fetchedGtkRuntimeDir!==void 0&&(n.fetchedGtkRuntimeDir=t.fetchedGtkRuntimeDir),n}function stagedMode(t,n){if(isExecutableAsset(t)||t.startsWith(`libexec/`)||t.startsWith(`bin/`))return 493;try{if(statSync(n).mode&73)return 493}catch{}return 420}var XU,ZU,QU,$U,eW,tW,nW=__esmMin(()=>{af(),Xn(),HU(),lU(),WU(),YU(),XI(),XU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`],ZU=`node_gi.node`,QU=`@gjsify/node-gi`,$U=`@gjsify/gtk-quartz-native`,eW=`GjsifyQuartz-1.0.typelib`,tW=`libgjsifyquartz.dylib`});function stageSubordinates(t){let n=t.layout.dirs(t.identity),S=[],C=[],N=[];for(let N of t.nestedBundles){if(n.plugins===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/PlugIns\` equivalent, so the nested bundle "${N.name}" has nowhere to go. \`gjsify.ship.nestedBundles\` is darwin-only; \`resolveShipNestedBundles\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.plugins,N.name);for(let t of listFilesRecursive(N.source)){let n=zn(N.source,...t.split(On.sep));S.push({path:On.join(F,t),mode:/^Contents\/MacOS\/[^/]+$/.test(t)?493:stagedMode(t,n),source:{kind:`file`,path:n}})}C.push({path:F,entitlements:N.entitlements})}for(let C of t.helperExecutables){if(n.helpers===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/Helpers\` equivalent, so the helper executable "${C.name}" has nowhere to go. \`gjsify.ship.helperExecutables\` is darwin-only; \`resolveShipHelperExecutables\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.helpers,C.name);S.push({path:F,mode:493,source:{kind:`file`,path:C.source}}),N.push({path:F,entitlements:C.entitlements})}if(t.mainExecutable!==void 0){if(t.layout.name!==`darwin`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` is darwin-only, but the ${t.layout.name} layout was asked to stage it — report this as a gjsify bug.`);S.push({path:mainExecutablePath(t.layout,t.identity),mode:493,source:{kind:`file`,path:t.mainExecutable}})}return{files:S,nestedBundles:C,helperExecutables:N}}function signedSubordinatesFor(t,n,S){let C=t.dirs(n);return{nestedBundles:S.nestedBundles.map(t=>({path:On.join(C.plugins,t.name),entitlements:t.entitlements})),helperExecutables:S.helperExecutables.map(t=>({path:On.join(C.helpers,t.name),entitlements:t.entitlements}))}}function plistStringValue(t,n){return RegExp(`<key>${n}</key>\\s*<string>([^<]*)</string>`).exec(t)?.[1]}function nestedBundlePlist(t,n){let S=t.find(t=>t.path===On.join(n,`Contents`,`Info.plist`));return S===void 0?void 0:new TextDecoder().decode(S.data)}function recordedNestedBundles(t,n){return n.map(n=>{let S=On.basename(n.path),C=nestedBundlePlist(t,n.path);if(C===void 0)return{name:S};let N=plistStringValue(C,`CFBundleIdentifier`),F=plistStringValue(C,`NSExtensionPointIdentifier`);return{name:S,...N===void 0?{}:{bundleId:N},...F===void 0?{}:{extensionPoint:F}}})}var rW=__esmMin(()=>{Xn(),HU(),nW(),lU()});function readManifest(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf-8`))}catch{return null}}function findInstalled(t,n){let S=n;for(;;){let n=zn(S,`node_modules`,...t.split(`/`));if(existsSync(zn(n,`package.json`)))return n;let C=Hn(S);if(C===S)return null;S=C}}function allows(t,n){let S=typeof t==`string`?[t]:t??[];if(S.includes(`!${n}`))return!1;let C=S.filter(t=>!t.startsWith(`!`));return C.length===0||C.includes(n)}function destinationOf(t){let n=t.split(qn),S=n.indexOf(`node_modules`);return S===-1||S===n.length-1?null:n.slice(S+1).join(`/`)}function resolveNodeModulesClosure(t,n,S={}){let{target:C,exclude:N=[]}=S,F=new Map,I=[],H=[],W=[],visit=(t,n,S,q)=>{if(t===iW)return;if(S.length>0&&N.includes(t)){W.includes(t)||W.push(t);return}let Y=findInstalled(t,n);if(Y===null){if(q){I.includes(t)||I.push(t);return}throw Error(`gjsify ship: \`${t}\` is not installed${S.length>0?` (needed by ${S.join(` > `)})`:``}. `+(S.length===0?"`gjsify.ship.nodeModules` names it, so the artifact must carry it — install it, or remove the entry.":`A package without its required dependency is an artifact that fails at its first import.`))}let X=destinationOf(Y);if(X===null)throw Error(`gjsify ship: ${Y} is not inside a node_modules directory, so it has no place to be staged.`);let Z=realpathSync(Y),te=readManifest(Z);if(te===null)throw Error(`gjsify ship: ${zn(Z,`package.json`)} is unreadable.`);if(S.length>0&&C!==void 0&&!(allows(te.os,C.os)&&allows(te.cpu,C.cpu))){H.includes(t)||H.push(t);return}let ne=F.get(X);if(ne!==void 0){if(ne.dir!==Z)throw Error(`gjsify ship: two installed copies of \`${t}\` would both be staged at node_modules/${X} (${ne.dir} and ${Z}).`);return}F.set(X,{name:t,version:te.version??`0.0.0`,dir:Z,dest:X});let re=[...S,t];for(let t of Object.keys(te.dependencies??{}))visit(t,Y,re,!1);for(let t of Object.keys(te.optionalDependencies??{}))visit(t,Y,re,!0)};for(let S of t)visit(S,n,[],!1);return{packages:[...F.values()].sort((t,n)=>t.dest<n.dest?-1:1),skippedOptional:I.sort(),skippedForTarget:H.sort(),excluded:W.sort(),target:C}}function prebuildPlatformOf(t){let n=/^(?:.*\/)?prebuilds\/([a-z0-9]+)-([a-z0-9_]+)(?:[-+][a-z0-9]+)?$/.exec(t);return n===null?null:[n[1],n[2]]}function listPackageFiles(t,n,S){let C=[],walk=N=>{for(let F of readdirSync(N,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let I=zn(N,F.name);if(F.isDirectory()){if(F.name===`node_modules`)continue;let C=n===void 0?null:prebuildPlatformOf(On.join(...Bn(t,I).split(qn)));if(C!==null&&(C[0]!==n.os||C[1]!==n.cpu)){S?.push(On.join(...Bn(t,I).split(qn)));continue}walk(I)}else if(F.isSymbolicLink())throw Error(`gjsify ship: ${I} is a symlink. The payload has to be self-contained — a package that links inside itself needs the link replaced by the file.`);else F.isFile()&&C.push(On.join(...Bn(t,I).split(qn)))}};return walk(t),C}function modeOf(t,n){return isExecutableAsset(t)||statSync(n).mode&73?493:420}function stageNodeModules(t,n){let S=[],C=[];t.skippedPrebuilds=C;for(let N of t.packages){let F=C.length;for(let F of listPackageFiles(N.dir,t.target,C)){let t=zn(N.dir,...F.split(`/`));S.push({path:On.join(n,`node_modules`,N.dest,F),mode:modeOf(F,t),source:{kind:`file`,path:t}})}for(let t=F;t<C.length;t++)C[t]=`${N.name}/${C[t]}`}return S}var iW,aW=__esmMin(()=>{af(),Xn(),YU(),iW=`@gjsify/node-gi`});async function acquireGtkRuntime(t){let n=t.discovery??{};if(resolveGtkRuntime(t.target,n)!==null)return{kind:`present`};let S=gtkRuntimePackageName(t.target),C=`${S}@${t.version}`;if((n.env??process.env).GJSIFY_GTK_RUNTIME_FETCH===`0`)return{kind:`failed`,reason:`GJSIFY_GTK_RUNTIME_FETCH=0 turned off the fetch of ${C}`};t.log?.(`${S} is not installed here, and is not meant to be — fetching ${C} into the cache (about 100 MB, once)`);let N;try{N=await t.ensure(C)}catch(t){return{kind:`failed`,reason:t instanceof Error?t.message:String(t)}}return resolveGtkRuntime(t.target,{...n,fetchedGtkRuntimeDir:N})===null?{kind:`failed`,reason:`${C} was fetched to ${N} but holds no complete gtk/ closure`}:{kind:`fetched`,dir:N}}var oW=__esmMin(()=>{nW()});function appDirFor(t){return zn(t,`appimage`,dW)}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=oU.linux.dirs(t).launcher,C=interpreterFloor(t),[N=`0`,F=`0`]=C.split(`.`);return[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(dirname "$(readlink -f "$0")")`,`if ! command -v ${t.app} >/dev/null 2>&1; then`,` echo "${shellSafe(t.name)} needs ${t.app}, and this system has none." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 127`,`fi`,`found=$(${t.app} --version 2>/dev/null | sed -n 's/[^0-9]*\\([0-9][0-9]*\\)\\.\\([0-9][0-9]*\\).*/\\1 \\2/p' | head -n 1 || true)`,"major=${found% *}","minor=${found#* }",`if [ -n "$major" ]; then`,` if [ "$major" -lt ${N} ] || { [ "$major" -eq ${N} ] && [ "$minor" -lt ${F} ]; }; then`,` echo "${shellSafe(t.name)} needs ${t.app} ${C} or newer, and this system has $major.$minor." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 126`,` fi`,`fi`,`exec "$here/usr/${S}/${t.binaryName}" "$@"`,``].join(`
|
|
1176
|
+
`)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${uW}/runtime-${t} (or point ${lW} 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(mW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${bH.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=`${bH.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 ${bH.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 ${bH.schemas}/ and no ${pU} 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 ${pU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${bH.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:fW,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:pW,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,[cW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${sW} 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: ${sW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${sW} 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 ${cW}=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(` `)} ${sW} ${n.join(` `)}`);let C=await spawnToCompletion(sW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${sW} 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 \`${sW}\`. \`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: ${sW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var sW,cW,lW,uW,dW,fW,pW,mW,hW=__esmMin(()=>{_e(),af(),Xn(),hv(),oH(),vH(),lU(),mU(),xH(),sW=`appimagetool`,cW=`APPIMAGE_EXTRACT_AND_RUN`,lW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,uW=`/usr/local/share/gjsify/appimage-runtime`,dW=`AppDir`,fW=`AppRun`,pW=`.DirIcon`,mW=[`.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(_W.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] ${gW} ${n.join(` `)}`);let S=await spawnToCompletion(gW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${gW} is not on PATH. 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: ${gW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(vW.target,zn(t,vW.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${yW} ${n.join(` `)}`);let S=await spawnToCompletion(yW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${yW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${yW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var gW,_W,vW,yW,bW=__esmMin(()=>{_e(),af(),Xn(),hv(),gW=`hdiutil`,_W=/[/:]/,vW={name:`Applications`,target:`/Applications`},yW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var xW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function resolveHandMetainfo(t){let n=(t.configReleases?.length??0)>0,S,C;if(t.shipMetainfo!==void 0){if(S=`gjsify.ship.metainfo`,C=t.shipMetainfo,n)throw Error(`gjsify ship: \`gjsify.ship.metainfo\` and \`gjsify.ship.releases\` both describe the releases. The file is staged verbatim, so the config entries would be dropped without a word — keep the \`<releases>\` in ${C} and remove \`releases\` from the config.`)}else if(t.siteMetainfo!==void 0&&!n)S=`gjsify.site.metainfo`,C=t.siteMetainfo;else return;let N=In(t.projectDir,C);if(!existsSync(N))throw Error(`gjsify ship: \`${S}\` points at ${C}, which does not exist (${N}).`);return{path:C,xml:readFileSync(N,`utf-8`),key:S}}function readFacts(t){let n={releaseVersions:[]},S=[],C=``;for(let N of scanXml(t))if(N.kind===`open`){let t=N.name;t===`release`&&N.attributes.version!==void 0&&n.releaseVersions.push(N.attributes.version),t===`launchable`&&N.attributes.type===`desktop-id`&&!N.selfClosing?(S.push(`launchable`),C=``):t===`id`&&S.length===0&&n.id===void 0&&!N.selfClosing&&(S.push(`id`),C=``)}else if(N.kind===`text`)S.length>0&&(C+=N.text);else if(S.length>0){let t=S.pop();t===`id`?n.id=C.trim():t===`launchable`&&(n.launchable=C.trim())}return n}function checkHandMetainfo(t,n){let S=readFacts(t.xml);if(S.id!==n.appId)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <id>${S.id??``}</id>, but the package's application id is "${n.appId}" (\`gjsify.ship.appId\`). Stores resolve the component by the <id> inside the file, so one of the two is wrong.`);if(n.kind===`app`&&S.launchable!==void 0&&S.launchable!==`${n.appId}.desktop`)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <launchable type="desktop-id">${S.launchable}</launchable>, but \`ship\` stages the desktop entry as ${n.appId}.desktop.`);let C=[];return S.releaseVersions.includes(n.version)||C.push(`${t.path} has no <release version="${n.version}"> — the shipped component will not list the version it is packaged as.`),C}var SW=__esmMin(()=>{af(),Xn(),Ye()});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var CW=__esmMin(()=>{cv(),af(),o_(),Xn(),eV()});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 wW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,...t.snapPlugs===void 0||t.snapPlugs.length===0?{}:{snapPlugs:t.snapPlugs},executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,TW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${TW}, 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(!eG.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${eG.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=sU.map(t=>oU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.snapPlugs===void 0?{}:{snapPlugs:expectArray(t.snapPlugs,field(`snapPlugs`)).map((t,n)=>expectString(t,field(`snapPlugs[${n}]`)))},...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var TW,EW=__esmMin(()=>{af(),Xn(),wW(),Ch(),nG(),lU(),TW=`.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 \`${TW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var DW=__esmMin(()=>{af(),Xn(),HU(),EW()});function isSnapName(t){return t.length<=FW&&PW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${FW} characters, at least one letter)`),n.version.length>IW&&S.push(`the version "${n.version}" is longer than ${IW} characters`),n.summary.length>LW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${LW}`);for(let t of n.snapPlugs??[])RW.test(t)||S.push(`gjsify.ship.snap.plugs: "${t}" is not an interface name (lowercase letters, digits, hyphens)`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${bH.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${NW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${NW}/${snapDesktopPath(n)}`,"common-id":n.appId,environment:{GI_TYPELIB_PATH:jW}};n.snapPlugs!==void 0&&n.snapPlugs.length>0&&(S.plugs=[...n.snapPlugs]);let C={name:n.binaryName,title:n.name,base:kW,version:n.version,summary:n.summary,description:n.description.join(`
|
|
1177
1177
|
|
|
1178
|
-
`),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:
|
|
1178
|
+
`),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:MW}}};return n.homepage!==void 0&&(C.website=n.homepage),C}function renderSnapcraftYaml(t){return`${JSON.stringify(renderSnapcraftManifest(t),null,2)}\n`}function snapcraftArgs(t){let n=[`pack`,`--build-for=${t.archLabel}`,`--output`,t.target];return t.destructive&&n.push(`--destructive-mode`),n}function writeSnapProject(t){assertSnapIsPackable(t.payload,t.settings),rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(zn(t.workDir,`snap`),{recursive:!0}),writePayload(zn(t.workDir,MW),t.payload.map(t=>({...t,path:`${NW}/${t.path}`})),``),writeFileSync(zn(t.workDir,`snap`,`snapcraft.yaml`),encodeUtf8(renderSnapcraftYaml(t)))}async function buildSnap(t){writeSnapProject(t);let n=process.env[AW]===`1`,S=zn(t.workDir,`out.snap`),C=snapcraftArgs({target:S,archLabel:t.archLabel,destructive:n});t.verbose&&ge.log(`[gjsify ship] ${OW} ${C.join(` `)}`);let N=await spawnToCompletion(OW,C,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${OW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(N.code!==0)throw Error(`gjsify ship: ${OW} failed with ${describeExit(N)}.`);if(!existsSync(S))throw Error(`gjsify ship: ${OW} exited 0 but wrote no snap at ${S}.`);renameSync(S,t.target)}var OW,kW,AW,jW,MW,NW,PW,FW,IW,LW,RW,zW=__esmMin(()=>{_e(),af(),Xn(),hv(),oH(),xH(),DW(),OW=`snapcraft`,kW=`core26`,AW=`GJSIFY_SNAP_DESTRUCTIVE`,jW=`$SNAP/gnome-platform/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/gjs/girepository-1.0`,MW=`payload`,NW=`usr`,PW=/^(?=.*[a-z])[a-z0-9]+(-[a-z0-9]+)*$/,FW=40,IW=32,LW=78,RW=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});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(BW,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(VW,t,`RPM`)}function flatpakArch(t,n){return lookupArch(HW,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(UW,t,`AppImage`)}function snapArch(t,n){return lookupArch(WW,t,`Snap`)}function linuxTarArch(t,n){return lookupArch(GW,t,`Linux tarball`)}function macosArch(t,n){return lookupArch(KW,t,`macOS`)}function windowsArch(t,n){return lookupArch(qW,t,`Windows`)}function windowsNameIsUnusable(t){return JW.test(t)||YW.test(t)||/[. ]$/.test(t)?!0:[...t].some(t=>(t.codePointAt(0)??0)<32)}function windowsProgramDirName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(n))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${n}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
|
|
1179
1179
|
The artifact would assemble here and be unextractable — or extract under a different name than
|
|
1180
|
-
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return $W.filter(n=>QW[n].layoutOs===t&&QW[n].host.finishOn===`any`)}function formatIdsFor(t){return $W.filter(n=>QW[n].layoutOs===t)}function assertHostCanFinish(t,n=process.platform){let{finishOn:S}=t.host;if(!(S===`any`||S.includes(n)))throw Error(`gjsify ship: a ${t.id} artifact is packed on ${S.join(` or `)} and this host is ${n} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${S.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${t.id}\`.`)}function assertToolsInstalled(t,n=isOnPath,S=process.platform){let C=requiredToolsOn(t.host.requiredTools,S),N=C.filter(t=>!n(t));if(N.length===0)return;let F=t.host.installHint;throw Error(`gjsify ship: packing a ${t.id} on ${S} needs ${C.join(` and `)}, and ${N.join(`, `)} ${N.length>1?`are`:`is`} not on PATH. ${F===void 0?`Install it`:`Install it (${F})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${N.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(t,n){let S=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t.length>0),C=S.filter(t=>!Object.hasOwn(QW,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${$W.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${$W.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>QW[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>QW[t].layoutOs))];throw Error(`gjsify ship: ${C.join(`, `)} ${C.length>1?`wrap`:`wraps`} the ${S.join(`/`)} layout and this run assembles the ${n.name} one. `+(t.length===0?`No format wraps the ${n.name} layout — \`gjsify ship ${n.name} --stage\` assembles it and stops.`:`Formats for this layout: ${t.join(`, `)}.`)+` To build ${C.join(`, `)}, name the layout each wraps: ${S.map(t=>`\`gjsify ship ${eG[t]??t} --target ${C.filter(n=>QW[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>QW[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>QW[t].layoutOs===n.os).map(t=>QW[t]),dropped:S.filter(t=>QW[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,YW,XW,ZW,SHARE_LICENSE_DEST,WRITTEN_HERE,QW,$W,eG,tG=__esmMin(()=>{fL(),mW(),RW(),yW(),cU(),pU(),zW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},BW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},VW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},HW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},UW={x64:`amd64`,arm64:`arm64`},WW={x64:`x86_64`,arm64:`aarch64`},GW={x64:`x86_64`,arm64:`arm64`},KW={x64:`x64`,arm64:`arm64`},qW=/[<>:"/\\|?*]/,JW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,YW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,XW='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',ZW="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=t=>`share/licenses/${t}/LICENSE`,WRITTEN_HERE=t=>({finishOn:`any`,requiredTools:[],oracle:{readWith:t,readOn:[`linux`],selfReading:!1}}),QW={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:YW,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:YW,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:[oW,uU],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: ${dU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[DW,uU],installHint:`\`sudo snap install ${DW} --classic\` (snapcraft is a snap; ${OW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${dU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[uU],installHint:`The schema compiler is packaged: ${dU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[uU],installHint:dU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:XW,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:[uU],installHint:dU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:XW,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:[hW],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:XW,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:[uU],installHint:dU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:ZW,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:[uU],installHint:dU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:ZW,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:[uU,`wixl`],win32:[uU,`candle.exe`,`light.exe`]},installHint:`${dU}; 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:ZW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},$W=Object.keys(QW),eG=Object.fromEntries(oU.map(t=>[aU[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(nG,`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(nG,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(nG,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
|
|
1180
|
+
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return eG.filter(n=>$W[n].layoutOs===t&&$W[n].host.finishOn===`any`)}function formatIdsFor(t){return eG.filter(n=>$W[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($W,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${eG.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${eG.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>$W[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>$W[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 ${tG[t]??t} --target ${C.filter(n=>$W[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>$W[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>$W[t].layoutOs===n.os).map(t=>$W[t]),dropped:S.filter(t=>$W[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var BW,VW,HW,UW,WW,GW,KW,qW,JW,YW,XW,ZW,QW,SHARE_LICENSE_DEST,WRITTEN_HERE,$W,eG,tG,nG=__esmMin(()=>{fL(),hW(),zW(),bW(),lU(),mU(),BW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},VW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},HW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},UW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},WW={x64:`amd64`,arm64:`arm64`},GW={x64:`x86_64`,arm64:`aarch64`},KW={x64:`x86_64`,arm64:`arm64`},qW={x64:`x64`,arm64:`arm64`},JW=/[<>:"/\\|?*]/,YW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,XW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,ZW='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',QW="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}}),$W={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:XW,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:XW,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:[sW,dU],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: ${fU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[OW,dU],installHint:`\`sudo snap install ${OW} --classic\` (snapcraft is a snap; ${kW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${fU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[dU],installHint:`The schema compiler is packaged: ${fU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[dU],installHint:fU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:ZW,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:[dU],installHint:fU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:ZW,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:[gW],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:ZW,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:[dU],installHint:fU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:QW,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:[dU],installHint:fU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:QW,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:[dU,`wixl`],win32:[dU,`candle.exe`,`light.exe`]},installHint:`${fU}; 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:QW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},eG=Object.keys($W),tG=Object.fromEntries(sU.map(t=>[oU[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(rG,`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(rG,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(rG,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
|
|
1181
1181
|
Dropping the suffix is not an option this command will take silently: \`1.2.0~rc.1\` and \`1.2.0\` would
|
|
1182
1182
|
become the same version, \`MajorUpgrade\` could not tell them apart, and installing one over the other
|
|
1183
1183
|
would leave both on the machine. Set \`gjsify.ship.version\` to a plain \`x.y.z\`, or drop \`msi\` from the targets.`);let[S,C,N]=[Number(n[1]),Number(n[2]),Number(n[3]??`0`)];if(S>255||C>255||N>65535)throw Error(`gjsify ship: version "${t}" is outside what Windows Installer compares — \`major\` and \`minor\` are at most 255 and \`build\` at most 65535. A field over the limit is not rejected by the installer, it is
|
|
1184
|
-
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||
|
|
1184
|
+
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||iG.test(t))throw Error(`gjsify ship: the payload holds "${n}", and Windows Installer cannot address the path segment "${t}". A \`FileName\` or \`DefaultDir\` cell reserves < > : " / \\ | ? * and ; (its own list separator), and
|
|
1185
1185
|
\`.\` and \`..\` are not names. The \`.msi\` would build and install the file somewhere else, or not at all.`);if(t.length>255)throw Error(`gjsify ship: the payload holds "${n}", whose segment "${t.slice(0,40)}…" is ${t.length} characters. Windows Installer's \`FileName\` column is 255.`)}function directoryTree(t){let n={path:``,name:``,children:new Map,files:[]};for(let S of[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))){let t=S.path.split(`/`),C=t.pop();if(C===void 0)throw Error(`gjsify ship: the payload holds an empty path.`);let N=n;for(let n of t){assertNameIsAddressable(n,S.path);let t=N.children.get(n)??{path:N.path===``?n:`${N.path}/${n}`,name:n,children:new Map,files:[]};N.children.set(n,t),N=t}assertNameIsAddressable(C,S.path),N.files.push(S)}return n}function renderWxs(t){let{settings:n,programDirName:S,archLabel:C}=t,N=C!==`x86`,F=C===`arm64`?500:200,I=msiProductVersion(n.version),H=n.maintainer.replace(/\s*<[^>]*>\s*$/,``).trim()||n.maintainer,W=windowsGuiLauncherPath(n),q=new Map,claim=(t,n)=>{let S=q.get(t);if(S!==void 0)throw Error(`gjsify ship: the MSI identifier "${t}" would be shared by ${S} and ${n}. Two rows cannot carry one id — one would silently replace the other.`);return q.set(t,n),t},Y=claim(msiIdentifier(`i`,W,`.exe`),`the launcher icon`),X=[],Z=[],te=!1,ne,emitDir=(t,S)=>{for(let C of t.files){let t=claim(msiIdentifier(`c`,C.path),C.path),F=claim(msiIdentifier(`f`,C.path),C.path);Z.push(t);let I=msiComponentGuid(n,C.path),H=xmlEscape(On.basename(C.path));X.push(`${S}<Component Id="${t}" Guid="${I}" Win64="${N?`yes`:`no`}">`),C.path===W?(te=!0,ne=C.source,X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes">`),X.push(`${S} <Shortcut Id="${claim(`s_startmenu`,`the Start-Menu shortcut`)}" Directory="ProgramMenuFolder" Name="${xmlEscape(n.name)}" WorkingDirectory="INSTALLDIR" Description="${xmlEscape(n.summary)}" Icon="${Y}" IconIndex="0" Advertise="yes" />`),X.push(`${S} </File>`)):X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes" />`),X.push(`${S}</Component>`)}for(let n of[...t.children.values()].sort((t,n)=>t.name<n.name?-1:1)){let t=claim(msiIdentifier(`d`,n.path),`the directory ${n.path}`);X.push(`${S}<Directory Id="${t}" Name="${xmlEscape(n.name)}">`),emitDir(n,`${S} `),X.push(`${S}</Directory>`)}};if(emitDir(directoryTree(t.files),` `),Z.length===0)throw Error("gjsify ship: the windows payload is empty, so there is nothing for an `.msi` to install.");if(!te||ne===void 0)throw Error(`gjsify ship: the windows payload carries no "${W}" at the root of the program directory, so the installer would have nothing to point a Start-Menu shortcut at — an application a user installs and
|
|
1186
1186
|
cannot start. \`windows-dir\` puts the launcher there; a payload without one is a stage assembled for another layout.`);let re=n.homepage===void 0?[]:[` <Property Id="ARPURLINFOABOUT" Value="${xmlEscape(n.homepage)}" />`];return[`<?xml version="1.0" encoding="utf-8"?>`,"<!-- Generated by `gjsify ship` (ADR 0024 stage 5). Do not edit; edit utils/ship/msi.ts. -->",`<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">`,` <Product Id="${msiProductCode(n,C)}" Name="${xmlEscape(n.name)}" Language="1033" Version="${I}" Manufacturer="${xmlEscape(H)}" UpgradeCode="${msiUpgradeCode(n)}">`,` <Package InstallerVersion="${F}" Compressed="yes" InstallScope="perMachine" Manufacturer="${xmlEscape(H)}" Description="${xmlEscape(n.summary)}" />`,` <MajorUpgrade DowngradeErrorMessage="A newer version of ${xmlEscape(n.name)} is already installed." />`,` <Media Id="1" Cabinet="app.cab" EmbedCab="yes" />`,` <Icon Id="${Y}" SourceFile="${xmlEscape(ne)}" />`,` <Property Id="ARPPRODUCTICON" Value="${Y}" />`,...re,` <Directory Id="TARGETDIR" Name="SourceDir">`,` <Directory Id="ProgramFiles64Folder">`,` <Directory Id="INSTALLDIR" Name="${xmlEscape(S)}">`,...X,` <Component Id="AddToPathComponent" Guid="${msiComponentGuid(n,`:path`)}" Win64="${N?`yes`:`no`}">`,` <CreateFolder />`,` <Environment Id="GjsifyPath" Name="PATH" Action="set" Part="last" System="yes" Permanent="no" Value="[INSTALLDIR]" />`,` </Component>`,` </Directory>`,` </Directory>`,` <Directory Id="ProgramMenuFolder" />`,` </Directory>`,` <Feature Id="Main" Title="${xmlEscape(n.name)}" Level="1">`,...Z.map(t=>` <ComponentRef Id="${t}" />`),` </Feature>`,` <Feature Id="AddToPath" Title="Add ${xmlEscape(n.name)} to PATH" Level="2">`,` <ComponentRef Id="AddToPathComponent" />`,` <Condition Level="1">ADDTOPATH=1</Condition>`,` </Feature>`,` </Product>`,`</Wix>`,``].join(`
|
|
1187
|
-
`)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var
|
|
1188
|
-
Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var hG,gG=__esmMin(()=>{pP(),hG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${_G}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var _G,vG=__esmMin(()=>{fl(),af(),Xn(),_G=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=yG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=bG[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 yG,bG,xG=__esmMin(()=>{af(),Xn(),fL(),hv(),VU(),CU(),nU(),EW(),yG={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},bG={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(yH.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
|
|
1187
|
+
`)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var rG,iG,aG,oG=__esmMin(()=>{_e(),fl(),af(),Xn(),hv(),lU(),EU(),rG=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,iG=/[<>:"/\\|?*;]/,aG=`root`});function tarballTopDir(t,n){return`${t.binaryName}-${t.version}-linux-${n}`}function inDeclaredClosure(t,n){return n.some(n=>t.startsWith(`${n}/`)?!t.slice(n.length+1).split(`/`).includes(`node_modules`):!1)}function assertTarballHygiene(t,n){let S=[];for(let C of t){let t=C.path.split(`/`),N=t[t.length-1];N===`.env`||N.startsWith(`.env.`)?S.push(`${C.path} (environment file)`):t.includes(`.git`)?S.push(`${C.path} (version-control data)`):N.endsWith(`.log`)?S.push(`${C.path} (log file)`):t.includes(`node_modules`)&&n.app!==`node`&&!inDeclaredClosure(C.path,n.nodeModulesDirs??[])&&S.push(`${C.path} (node_modules in a non-Node payload)`)}if(S.length!==0)throw Error(`gjsify ship: refusing to pack a tarball that would contain ${S.slice(0,5).join(`, `)}${S.length>5?` and ${S.length-5} more`:``}.`)}async function buildLinuxTarball(t){assertTarballHygiene(t.payload,t.settings);let n=tarballTopDir(t.settings,t.archLabel),S=new Set([`${n}/`]);for(let C of t.payload){let t=On.dirname(C.path),N=t===`.`?[]:t.split(`/`),F=n;for(let t of N)F=`${F}/${t}`,S.add(`${F}/`)}return gzipDeterministic(createTarball([...[...S].sort().map(n=>({name:n,mode:493,mtime:t.mtime,directory:!0})),...t.payload.map(S=>({name:`${n}/${S.path}`,body:S.data,mode:S.mode,mtime:t.mtime}))]))}var sG=__esmMin(()=>{Xn(),sz(),yH()});function getCrcTable(){if(mG!==null)return mG;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 mG=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(cG),I.u16(pG),I.u16(2048),I.u16(dG),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(lG),H.u16(fG),H.u16(pG),H.u16(2048),H.u16(dG),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(uG),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 cG,lG,uG,dG,fG,pG,mG,Writer,hG=__esmMin(()=>{cG=67324752,lG=33639248,uG=101010256,dG=0,fG=788,pG=20,mG=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(t){this.push(new Uint8Array([t&255,t>>>8&255]))}u32(t){this.push(new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255]))}bytes(t){this.push(t)}push(t){this.parts.push(t),this.length+=t.byteLength}finish(){let t=new Uint8Array(this.length),n=0;for(let S of this.parts)t.set(S,n),n+=S.byteLength;return t}}});function entryEvidence(t){let n=new Set,S=new Set;return walkModuleAst(t,t=>{let C=importedSpecifier(t);C!==null&&(C.startsWith(`gi://`)||gG.has(C)?n.add(C):C.startsWith(`node:`)&&t.type!==`ImportExpression`&&S.add(C))}),{gi:[...n].sort(),node:[...S].sort()}}function assertEntryRunsUnder(t){let n=entryEvidence(t.source),S=t.interpreter===`node`?n.gi:n.node;if(S.length===0)return;let C=t.interpreter===`node`?`gjs`:`node`,N=t.interpreter===`gjs`?`GJS's loader refuses it: ImportError, "Unsupported URI scheme for importing: node"`:S.some(t=>t.startsWith(`gi://`))?`node's ESM loader refuses it: ERR_UNSUPPORTED_ESM_URL_SCHEME, "Only URLs with a scheme in: file, data, and node are supported by the default ESM loader"`:`node's ESM loader refuses it: ERR_MODULE_NOT_FOUND — a GJS built-in is not a package`,F=S.slice(0,3).join(`, `),I=S.length>3?`, and ${S.length-3} more`:``;throw Error(`gjsify ship: this target execs \`${t.interpreter}\` (\`${t.appKey}\`), and the entry it would ship — ${t.entry} (\`${t.bundleKey}\`) — imports ${F}${I}.\n ${N}, before a line of application code runs.\n The artifact would be built, reported as built, and fail at launch on every machine.
|
|
1188
|
+
Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var gG,_G=__esmMin(()=>{pP(),gG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${vG}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var vG,yG=__esmMin(()=>{fl(),af(),Xn(),vG=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=bG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=xG[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 bG,xG,SG=__esmMin(()=>{af(),Xn(),fL(),hv(),HU(),wU(),rU(),DW(),bG={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},xG={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(bH.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
|
|
1189
1189
|
`)}function renderAppBundleLauncher(t,n,S,C){let N=`${S.root(t)}/Contents`,F=S.dirs(t),under=t=>On.relative(N,t),beside=t=>On.relative(F.launcher,t),I=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(cd -- "$(dirname -- "$0")" && pwd)`,`contents=$(dirname -- "$here")`,`XDG_DATA_DIRS="$contents/${under(F.data)}"\${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}`,`export XDG_DATA_DIRS`];C.gtkRuntimeDir!==void 0&&I.push(`GJSIFY_GTK_RUNTIME="$contents/${under(C.gtkRuntimeDir)}"`,`export GJSIFY_GTK_RUNTIME`),C.nodeGiAddon!==void 0&&I.push(`NODE_GI_NATIVE="$contents/${under(C.nodeGiAddon)}"`,`export NODE_GI_NATIVE`),t.typelibFiles.length>0&&(I.push(`GI_TYPELIB_PATH="$contents/${under(F.native)}"\${GI_TYPELIB_PATH:+:$GI_TYPELIB_PATH}`,`export GI_TYPELIB_PATH`),I.push(`GJSIFY_GI_LIBRARY_PATH="$contents/${under(F.native)}"\${GJSIFY_GI_LIBRARY_PATH:+:$GJSIFY_GI_LIBRARY_PATH}`,`export GJSIFY_GI_LIBRARY_PATH`)),t.localeFiles.length>0&&I.push(`GJSIFY_LOCALE_DIR="$contents/${under(F.data)}/locale"`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&I.push(`GJSIFY_FONT_DIR="$contents/${stagedFontDir(under(F.data),t.appId)}"`,`export GJSIFY_FONT_DIR`);let H=C.interpreter===void 0?void 0:`"$here/${beside(C.interpreter)}"`;return I.push(`exec ${execLine(S,`"$contents/${under(F.bundle)}/${n}"`,t,H)} "$@"`,``),I.join(`
|
|
1190
1190
|
`)}function renderWindowsLauncher(t,n,S,C){let N=S.dirs(t),at=t=>`%HERE%${windowsPath(t)}`,F=[`@echo off`,`rem Generated by "gjsify ship" - do not edit.`,`setlocal`,`set "HERE=%~dp0"`,prependVar(`XDG_DATA_DIRS`,at(N.data))];C.gtkRuntimeDir!==void 0&&F.push(`set "GJSIFY_GTK_RUNTIME=${at(C.gtkRuntimeDir)}"`),C.nodeGiAddon!==void 0&&F.push(`set "NODE_GI_NATIVE=${at(C.nodeGiAddon)}"`),t.typelibFiles.length>0&&F.push(prependVar(`GI_TYPELIB_PATH`,at(N.native)),prependVar(`PATH`,at(N.native))),t.localeFiles.length>0&&F.push(`set "GJSIFY_LOCALE_DIR=${at(N.data)}\\locale"`),t.fontFiles.length>0&&F.push(`set "GJSIFY_FONT_DIR=${at(stagedFontDir(N.data,t.appId))}"`);let I=C.interpreter===void 0?void 0:`"${at(C.interpreter)}"`;return F.push(`${execLine(S,`"${at(N.bundle)}\\${windowsPath(n)}"`,t,I)} %*`,``),F.join(`\r
|
|
1191
|
-
`)}function prependVar(t,n){return`if defined ${t} (set "${t}=${n};%${t}%") else (set "${t}=${n}")`}function windowsPath(t){return t.split(`/`).filter(t=>t.length>0).join(`\\`)}function execLine(t,n,S,C){let N=t.name===`windows`?cmdQuote:shellQuote,F=S.execArgs.map(N).join(` `),I=C??(S.app===`node`?`node`:`gjs`);return`${S.app===`node`?I:`${I} -m`} ${n}${F?` ${F}`:``}`}var
|
|
1191
|
+
`)}function prependVar(t,n){return`if defined ${t} (set "${t}=${n};%${t}%") else (set "${t}=${n}")`}function windowsPath(t){return t.split(`/`).filter(t=>t.length>0).join(`\\`)}function execLine(t,n,S,C){let N=t.name===`windows`?cmdQuote:shellQuote,F=S.execArgs.map(N).join(` `),I=C??(S.app===`node`?`node`:`gjs`);return`${S.app===`node`?I:`${I} -m`} ${n}${F?` ${F}`:``}`}var CG=__esmMin(()=>{Xn(),xH()});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=wG+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!==TG)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${TG}.`);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 wG,TG,EG,DG,OG=__esmMin(()=>{oH(),wG=`070701`,TG=110,EG=32768,DG=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=MG[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,-(AG*H),jG)),F+=AG;let W=new Uint8Array(kG.byteLength+8+H*AG+F),q=new DataView(W.buffer);W.set(kG,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,jG),Y),Y+=AG;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=AG;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(AG),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 kG,AG,jG,MG,NG=__esmMin(()=>{kG=Uint8Array.from([142,173,232,1,0,0,0,0]),AG=16,jG=16,MG={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:FG.SHA1HEADER,type:6,value:hashHex(`sha1`,I)},{tag:FG.SHA256HEADER,type:6,value:hashHex(`sha256`,I)},{tag:FG.SIZE,type:4,value:[H.byteLength]},{tag:FG.MD5,type:7,value:hashBytes(`md5`,H)},{tag:FG.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:EG|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}`,zG.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:DG|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:PG.HEADERI18NTABLE,type:8,value:[`C`]},{tag:PG.NAME,type:6,value:N.binaryName},{tag:PG.VERSION,type:6,value:N.version},{tag:PG.RELEASE,type:6,value:N.release},{tag:PG.SUMMARY,type:9,value:[N.summary]},{tag:PG.DESCRIPTION,type:9,value:[N.description.join(`
|
|
1192
1192
|
|
|
1193
|
-
`)]},{tag:NG.BUILDTIME,type:4,value:[t.mtime]},{tag:NG.BUILDHOST,type:6,value:`localhost`},{tag:NG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:NG.LICENSE,type:6,value:N.license},{tag:NG.GROUP,type:9,value:[N.group]},{tag:NG.OS,type:6,value:`linux`},{tag:NG.ARCH,type:6,value:t.archLabel},{tag:NG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:NG.RPMVERSION,type:6,value:`4.20.0`},{tag:NG.ENCODING,type:6,value:`utf-8`},{tag:NG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:NG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:NG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:NG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:NG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:NG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:NG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:NG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:NG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:NG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:NG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:NG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:NG.FILELANGS,type:8,value:n.map(()=>``)},{tag:NG.FILEDIGESTALGO,type:4,value:[IG]},{tag:NG.DIRINDEXES,type:4,value:H},{tag:NG.BASENAMES,type:8,value:W},{tag:NG.DIRNAMES,type:8,value:I},{tag:NG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:NG.PROVIDEFLAGS,type:4,value:[FG.EQUAL]},{tag:NG.PROVIDEVERSION,type:8,value:[F]},{tag:NG.REQUIRENAME,type:8,value:Y.names},{tag:NG.REQUIREFLAGS,type:4,value:Y.flags},{tag:NG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:NG.RECOMMENDNAME,type:8,value:X.names},{tag:NG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:NG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:NG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:NG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:NG.PAYLOADFLAGS,type:6,value:`9`},{tag:NG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:NG.PAYLOADDIGESTALGO,type:4,value:[IG]},{tag:NG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:NG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:NG.POSTIN,type:6,value:q.post}),Z.push({tag:NG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:NG.POSTUN,type:6,value:q.postun}),Z.push({tag:NG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([NG.FILESIZES,NG.FILEMODES,NG.FILERDEVS,NG.FILEMTIMES,NG.FILEDIGESTS,NG.FILELINKTOS,NG.FILEFLAGS,NG.FILEUSERNAME,NG.FILEGROUPNAME,NG.FILEVERIFYFLAGS,NG.FILEDEVICES,NG.FILEINODES,NG.FILELANGS,NG.DIRINDEXES,NG.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(FG.INTERP|FG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(FG.INTERP|FG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(FG.FIND_REQUIRES),F.push(``);for(let[t,n]of LG)C.push(t),N.push(FG.RPMLIB|FG.LESS|FG.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 FG.GREATER|FG.EQUAL;case`>`:return FG.GREATER;case`<=`:return FG.LESS|FG.EQUAL;case`<`:return FG.LESS;case`=`:return FG.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 NG,PG,FG,IG,LG,RG,zG=__esmMin(()=>{fl(),aH(),DG(),_H(),CU(),MG(),vH(),xH(),bH(),NG={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},PG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},FG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},IG=8,LG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],RG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${yH.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${yH.metainfo}`,`/usr/share/glib-2.0`,`/usr/${yH.schemas}`,`/usr/${yH.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(`${BG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${BG} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>QW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${BG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${BG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${BG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,desktopExecArgs:ae.desktopExecArgs,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()},ue=resolveHandMetainfo({shipMetainfo:N.metainfo,siteMetainfo:C.site?.metainfo,configReleases:N.releases,projectDir:n});if(ue!==void 0){for(let t of checkHandMetainfo(ue,{appId:ae.appId,kind:ae.kind,version:ae.version}))ge.warn(`${BG} ${t}`);ge.log(`${BG} AppStream metainfo from ${ue.path} (\`${ue.key}\`), staged as written`);for(let t of await lintMetainfo(ue.xml))ge.warn(`${BG} ${formatFinding(t,!1)}`)}if(ue===void 0)for(let t of validateAppMetadata(le))ge.warn(`${BG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${BG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let de=ue?.xml,fe=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),pe=await resolveCarriedRuntime(S,ae,n),me=carryNodeModules(pe,S,ae,n,N.nodeModules,N.nodeModulesExclude);me.length>0&&(ae.nodeModulesDirs=me);let he=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),_e={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,pe.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,pe.launcher)])),metainfo:de??fe.metainfo,desktopEntry:fe.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},ve=In(n,ae.outDir),ye=zn(ve,`stage`),be=[...planStage(ae,_e),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(ve,`schemas`)})],xe=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;xe!==void 0&&ge.log(`${BG} icon: ${iconSizes(xe).join(`/`)} px, ${xe.source}`);let Se=placeStage(S,{...ae,icon:xe,categories:oe.categories},be,[...pe.files,...he.files]);if(writeStage(ye,Se),ge.log(`${BG} staged ${Se.length} file(s) for ${S.name} in ${Bn(n,ye)}/`),t.verbose)for(let t of Se)ge.log(`${BG} ${t.path}`);if(assertPayloadMatchesArch(readStage([ye],Se),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(be);if(t.length>0){ge.warn(`${BG} 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(`${BG} ${n[C]??``}${S} — ${N}`)}for(let t of pe.found)ge.log(`${BG} carries its own ${t}`);for(let t of pe.missing)ge.warn(`${BG} ${t}`);pe.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${BG} ${S.runtimeGap}`),S.fontGap!==void 0&&be.some(t=>isUnder(t.path,yH.fonts))&&ge.warn(`${BG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${BG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let Ce=scanGiRequirements(se),we=Ce.namespaces,Te=Ce.optional;if(t.verbose){let t=we.filter(t=>!Te.includes(t));ge.log(`${BG} gi namespaces: ${we.join(`, `)||`(none)`}`),Te.length>0&&(ge.log(`${BG} gi optional namespaces: ${Te.join(`, `)}`),ge.log(`${BG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ee=new Map;for(let t of q)Ee.set(t.id,(await planOverlay(ae,t,_e)).map(t=>({...t,path:place(S,ae,t.path)})));let De=readPayloadFacts(be);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:we,optionalNamespaces:Te,hasIcons:De.hasIcons,hasSchemas:De.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:De.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${BG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${BG} ${t}`)}let Oe=writeStageManifest({stageDir:ye,settings:ae,formats:q,mtime:ce,namespaces:we,optionalNamespaces:Te,staged:Se,overlay:Ee});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Oe.formats.join(`, `)||t;ge.log(`${BG} stage manifest: ${formatTarget(Oe.target)}, formats ${n}`);return}let ke=[];for(let n of q)ke.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:Se,overlay:Ee.get(n.id)??[],stageDir:ye,outRoot:ve,namespaces:we,optionalNamespaces:Te,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,ke)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${BG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${BG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:HG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${BG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return[];let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${BG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${BG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${BG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${BG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>QW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>QW[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${BG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${BG} ${t}`);if(ge.log(`${BG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${BG} ${t.path}`);ge.log(`${BG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${BG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${BG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${BG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:wW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${BG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${BG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${BG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${BG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,iG),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${iG}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${BG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${BG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${BG} ${t}`)}),ce=!0):ge.warn(`${BG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${BG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${BG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
|
|
1193
|
+
`)]},{tag:PG.BUILDTIME,type:4,value:[t.mtime]},{tag:PG.BUILDHOST,type:6,value:`localhost`},{tag:PG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:PG.LICENSE,type:6,value:N.license},{tag:PG.GROUP,type:9,value:[N.group]},{tag:PG.OS,type:6,value:`linux`},{tag:PG.ARCH,type:6,value:t.archLabel},{tag:PG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:PG.RPMVERSION,type:6,value:`4.20.0`},{tag:PG.ENCODING,type:6,value:`utf-8`},{tag:PG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:PG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:PG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:PG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:PG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:PG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:PG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:PG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:PG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:PG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:PG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:PG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:PG.FILELANGS,type:8,value:n.map(()=>``)},{tag:PG.FILEDIGESTALGO,type:4,value:[LG]},{tag:PG.DIRINDEXES,type:4,value:H},{tag:PG.BASENAMES,type:8,value:W},{tag:PG.DIRNAMES,type:8,value:I},{tag:PG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:PG.PROVIDEFLAGS,type:4,value:[IG.EQUAL]},{tag:PG.PROVIDEVERSION,type:8,value:[F]},{tag:PG.REQUIRENAME,type:8,value:Y.names},{tag:PG.REQUIREFLAGS,type:4,value:Y.flags},{tag:PG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:PG.RECOMMENDNAME,type:8,value:X.names},{tag:PG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:PG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:PG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:PG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:PG.PAYLOADFLAGS,type:6,value:`9`},{tag:PG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:PG.PAYLOADDIGESTALGO,type:4,value:[LG]},{tag:PG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:PG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:PG.POSTIN,type:6,value:q.post}),Z.push({tag:PG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:PG.POSTUN,type:6,value:q.postun}),Z.push({tag:PG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([PG.FILESIZES,PG.FILEMODES,PG.FILERDEVS,PG.FILEMTIMES,PG.FILEDIGESTS,PG.FILELINKTOS,PG.FILEFLAGS,PG.FILEUSERNAME,PG.FILEGROUPNAME,PG.FILEVERIFYFLAGS,PG.FILEDEVICES,PG.FILEINODES,PG.FILELANGS,PG.DIRINDEXES,PG.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(IG.INTERP|IG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(IG.INTERP|IG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(IG.FIND_REQUIRES),F.push(``);for(let[t,n]of RG)C.push(t),N.push(IG.RPMLIB|IG.LESS|IG.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 IG.GREATER|IG.EQUAL;case`>`:return IG.GREATER;case`<=`:return IG.LESS|IG.EQUAL;case`<`:return IG.LESS;case`=`:return IG.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 PG,FG,IG,LG,RG,zG,BG=__esmMin(()=>{fl(),oH(),OG(),vH(),wU(),NG(),yH(),SH(),xH(),PG={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},FG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},IG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},LG=8,RG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],zG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${bH.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${bH.metainfo}`,`/usr/share/glib-2.0`,`/usr/${bH.schemas}`,`/usr/${bH.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(`${VG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${VG} \`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=>$W[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${VG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${VG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${VG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,desktopExecArgs:ae.desktopExecArgs,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()},ue=resolveHandMetainfo({shipMetainfo:N.metainfo,siteMetainfo:C.site?.metainfo,configReleases:N.releases,projectDir:n});if(ue!==void 0){for(let t of checkHandMetainfo(ue,{appId:ae.appId,kind:ae.kind,version:ae.version}))ge.warn(`${VG} ${t}`);ge.log(`${VG} AppStream metainfo from ${ue.path} (\`${ue.key}\`), staged as written`);for(let t of await lintMetainfo(ue.xml))ge.warn(`${VG} ${formatFinding(t,!1)}`)}if(ue===void 0)for(let t of validateAppMetadata(le))ge.warn(`${VG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${VG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let de=ue?.xml,fe=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),pe=await resolveCarriedRuntime(S,ae,n),me=carryNodeModules(pe,S,ae,n,N.nodeModules,N.nodeModulesExclude);me.length>0&&(ae.nodeModulesDirs=me);let he=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),_e={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,pe.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,pe.launcher)])),metainfo:de??fe.metainfo,desktopEntry:fe.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},ve=In(n,ae.outDir),ye=zn(ve,`stage`),be=[...planStage(ae,_e),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(ve,`schemas`)})],xe=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;xe!==void 0&&ge.log(`${VG} icon: ${iconSizes(xe).join(`/`)} px, ${xe.source}`);let Se=placeStage(S,{...ae,icon:xe,categories:oe.categories},be,[...pe.files,...he.files]);if(writeStage(ye,Se),ge.log(`${VG} staged ${Se.length} file(s) for ${S.name} in ${Bn(n,ye)}/`),t.verbose)for(let t of Se)ge.log(`${VG} ${t.path}`);if(assertPayloadMatchesArch(readStage([ye],Se),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(be);if(t.length>0){ge.warn(`${VG} 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(`${VG} ${n[C]??``}${S} — ${N}`)}for(let t of pe.found)ge.log(`${VG} carries its own ${t}`);for(let t of pe.missing)ge.warn(`${VG} ${t}`);pe.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${VG} ${S.runtimeGap}`),S.fontGap!==void 0&&be.some(t=>isUnder(t.path,bH.fonts))&&ge.warn(`${VG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${VG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let Ce=scanGiRequirements(se),we=Ce.namespaces,Te=Ce.optional;if(t.verbose){let t=we.filter(t=>!Te.includes(t));ge.log(`${VG} gi namespaces: ${we.join(`, `)||`(none)`}`),Te.length>0&&(ge.log(`${VG} gi optional namespaces: ${Te.join(`, `)}`),ge.log(`${VG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ee=new Map;for(let t of q)Ee.set(t.id,(await planOverlay(ae,t,_e)).map(t=>({...t,path:place(S,ae,t.path)})));let De=readPayloadFacts(be);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:we,optionalNamespaces:Te,hasIcons:De.hasIcons,hasSchemas:De.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:De.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${VG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${VG} ${t}`)}let Oe=writeStageManifest({stageDir:ye,settings:ae,formats:q,mtime:ce,namespaces:we,optionalNamespaces:Te,staged:Se,overlay:Ee});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Oe.formats.join(`, `)||t;ge.log(`${VG} stage manifest: ${formatTarget(Oe.target)}, formats ${n}`);return}let ke=[];for(let n of q)ke.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:Se,overlay:Ee.get(n.id)??[],stageDir:ye,outRoot:ve,namespaces:we,optionalNamespaces:Te,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,ke)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${VG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${VG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:UG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${VG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return[];let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${VG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${VG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${VG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${VG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>$W[t]),F,`stage`,defaultFormatIds(F.os).map(t=>$W[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(`${VG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${VG} ${t}`);if(ge.log(`${VG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${VG} ${t.path}`);ge.log(`${VG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${VG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${VG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${VG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:TW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${VG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${VG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${VG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${VG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,aG),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${aG}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${VG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${VG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${VG} ${t}`)}),ce=!0):ge.warn(`${VG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${VG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${VG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
|
|
1194
1194
|
\`gjsify ship ${n.name} --stage\` assembles the tree either way.`);let N=formatIdsFor(n.os).sort();if(N.length>0){let t=S===`stage`?`${n.name} --stage --target`:`${n.name} --target`;throw Error(`gjsify ship: this run records no formats for the ${n.name} layout, so there is nothing to pack — and it is not that none exist: ${N.join(`, `)} wrap it.\n An empty list means none were SELECTED. \`gjsify.ship.targets\` is filtered to the layout being assembled,
|
|
1195
1195
|
so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
|
|
1196
|
-
Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${
|
|
1196
|
+
Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${VG} running the project's build script`);let C=S===void 0&&n===void 0?void 0:{...process.env};C!==void 0&&(n!==void 0&&(C[Oh]=n),S!==void 0&&(C[jh]=S));let N=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,env:C,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(N.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(N)}.`)}var VG,HG,UG,WG=__esmMin(()=>{_e(),kh(),Mh(),af(),Xn(),vR(),DB(),vV(),qI(),xB(),Ch(),hv(),TU(),vH(),nW(),rW(),aW(),oW(),HU(),hW(),bW(),mV(),xW(),DH(),GV(),SW(),CW(),nG(),lU(),WU(),xH(),mU(),oG(),zW(),sG(),hG(),_G(),pP(),wU(),YU(),yG(),SG(),CG(),BG(),LU(),EW(),DW(),VG=`[gjsify ship]`,HG={command:`ship [os]`,description:`Build installable artifacts (${eG.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${sU.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`channel`,{type:`string`,choices:[...Eh],description:"Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. Passed to the project build, and gates the metainfo donation URL."}).option(`pricing`,{type:`string`,choices:[...Ah],description:`Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project build. Default 'free'.`}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}},UG=1440*7});function parseGithubRepo(t){let n=t.trim().replace(/^git\+/,``),S=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(n),C=/^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(n)??S;return C===null?void 0:`${C[1]}/${C[2].replace(/\.git$/,``)}`}function releaseDateOf(t){return new Date(t*1e3).toISOString().slice(0,10)}function readFlatparkSources(t){let n=[];if(existsSync(t.dir))for(let S of readdirSync(t.dir).sort()){if(!S.endsWith(`.gjsify-release.json`))continue;let C=JSON.parse(readFileSync(zn(t.dir,S),`utf-8`));C.format===`linux-tar-flatpak`&&C.os===`linux`&&n.push(C)}if(n.length===0)throw Error(`gjsify flatpark: no release record for \`${KG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${vG}\`, which \`gjsify ship --target ${KG}\` writes beside the archive. Run that first, or point --release-dir at the directory that holds the record.`);let S=`${t.tagPrefix}${t.version}`,C=n.map(n=>{let C=qG[n.arch===`noarch`?t.stageArch??n.arch:n.arch];if(C===void 0)throw Error(`gjsify flatpark: ${n.artifact} is built for \`${n.arch}\`, which has no Flatpak arch (known: ${Object.keys(qG).join(`, `)}).`);return{arch:C,artifact:n.artifact,url:`https://github.com/${t.repo}/releases/download/${S}/${n.artifact}`,sha256:n.sha256,size:n.size}}),N=new Set;for(let n of C){if(N.has(n.arch))throw Error(`gjsify flatpark: two release records for ${n.arch} in ${t.dir}; keep one.`);N.add(n.arch)}return C.sort((t,n)=>t.arch.localeCompare(n.arch))}function renderApplyExtra(t){return`#!/bin/sh
|
|
1197
1197
|
set -eu
|
|
1198
1198
|
|
|
1199
1199
|
extra_root="\${EXTRA_ROOT:-/app/extra}"
|
|
1200
1200
|
cd "$extra_root"
|
|
1201
1201
|
|
|
1202
|
-
[ -f ${
|
|
1202
|
+
[ -f ${GG} ] || { echo "missing extra-data: ${GG}" >&2; exit 1; }
|
|
1203
1203
|
|
|
1204
1204
|
rm -rf stage app
|
|
1205
1205
|
mkdir stage
|
|
1206
|
-
bsdtar --no-same-owner -xf ${
|
|
1206
|
+
bsdtar --no-same-owner -xf ${GG} -C stage
|
|
1207
1207
|
|
|
1208
1208
|
top="$(find stage -mindepth 1 -maxdepth 1 -type d)"
|
|
1209
1209
|
[ "$(printf '%s\\n' "$top" | wc -l)" -eq 1 ] || { echo "expected one top-level directory" >&2; exit 1; }
|
|
1210
1210
|
mv "$top" app
|
|
1211
1211
|
[ -x app/bin/${shellWord(t)} ] || { echo "${shellWord(t)} launcher not found in the tarball" >&2; exit 1; }
|
|
1212
1212
|
|
|
1213
|
-
rm -rf stage ${
|
|
1213
|
+
rm -rf stage ${GG}
|
|
1214
1214
|
`}function renderWrapper(t){return`#!/bin/sh
|
|
1215
1215
|
set -eu
|
|
1216
1216
|
exec /app/extra/app/bin/${shellWord(t)} "$@"
|
|
1217
|
-
`}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${
|
|
1217
|
+
`}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${GG}`,` only-arches:`,` - ${t.arch}`,` url: ${yamlString(t.url)}`,` sha256: ${t.sha256}`,` size: ${t.size}`]),` # END MANAGED EXTRA-DATA`,...C.flatMap(t=>[` - type: file`,` path: ${yamlString(t)}`])].join(`
|
|
1218
1218
|
`)}\n`}function firstCategory(t){return/<category>([^<]+)<\/category>/.exec(t)?.[1]?.trim()??`Utility`}function keywords(t){return[...t.matchAll(/<keyword>([^<]+)<\/keyword>/g)].map(t=>t[1].trim())}function renderDescriptor(t){let n=keywords(t.metainfo);return`${[`id: ${yamlString(t.appId)}`,`name: ${yamlString(t.name)}`,`summary: ${yamlString(t.summary)}`,`website: ${yamlString(t.homepage??`https://github.com/${t.repo}`)}`,`source_url: https://github.com/${t.repo}`,`build:`,` manifest: ${t.appId}.yml`,` branch: stable`,` mode: extra-data`,` arches: [${t.sources.map(t=>t.arch).join(`, `)}]`,`catalog:`,` category: ${yamlString(firstCategory(t.metainfo))}`,` upstream_approved: false`,...n.length===0?[]:[` tags:`,...n.map(t=>` - ${yamlString(t)}`)],`update:`,` command: ./resolve-update.sh`,`policy:`,` proprietary: false`,` dangerous_permissions: []`].join(`
|
|
1219
|
-
`)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${
|
|
1219
|
+
`)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${GG}", arch:"${t.arch}", url:$u_${n}}`),N=n.map(({key:t})=>`--arg u_${t} "$url_${t}"`);return`#!/usr/bin/env bash
|
|
1220
1220
|
# Update resolver for ${t.name}, written by \`gjsify flatpark\`.
|
|
1221
1221
|
#
|
|
1222
1222
|
# Prints the latest release on stdout as JSON:
|
|
1223
1223
|
# { "version": "…", "releaseDate": "YYYY-MM-DD",
|
|
1224
|
-
# "sources": [ { "filename": "${
|
|
1224
|
+
# "sources": [ { "filename": "${GG}", "arch": "…", "url": "…" } ] }
|
|
1225
1225
|
# Logs go to stderr. No hashing and no manifest rewriting: FlatPark downloads
|
|
1226
1226
|
# each URL and computes the extra-data sha256 and size itself.
|
|
1227
1227
|
set -euo pipefail
|
|
@@ -1244,8 +1244,8 @@ echo "resolved ${t.name} $version ($date)" >&2
|
|
|
1244
1244
|
|
|
1245
1245
|
jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
|
|
1246
1246
|
'{version:$v, releaseDate:$d, sources:[${C.join(`, `)}]}'
|
|
1247
|
-
`}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var WG,GG,KG,qG=__esmMin(()=>{af(),Xn(),vG(),TU(),WG=`app.tar.gz`,GG=`linux-tar-flatpak`,KG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${JG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${JG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${JG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var JG,YG,XG=__esmMin(()=>{_e(),af(),Xn(),vR(),qI(),qG(),TW(),JG=`[gjsify flatpark]`,YG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${JG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${JG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${JG} ${t.arch}: ${t.url}`);ge.log(`${JG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var ZG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return QG===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===tK&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[tK];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,tK,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
|
|
1248
|
-
`)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n
|
|
1247
|
+
`}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var GG,KG,qG,JG=__esmMin(()=>{af(),Xn(),yG(),EU(),GG=`app.tar.gz`,KG=`linux-tar-flatpak`,qG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${YG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${YG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${YG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var YG,XG,ZG=__esmMin(()=>{_e(),af(),Xn(),vR(),qI(),JG(),EW(),YG=`[gjsify flatpark]`,XG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${YG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${YG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${YG} ${t.arch}: ${t.url}`);ge.log(`${YG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var QG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return $G===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===nK&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[nK];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,nK,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
|
|
1248
|
+
`)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,$G)};for(let t=0;t<Math.min(32,S.length);t++)F.push((async()=>{for(;;){let t=C++;if(t>=S.length)return;let n=S[t];if(!n)return;await wireOne(n.linkPath,n.relTarget)}})());await Promise.all(F),ge.log(`gjsify install: wired ${q.length} workspace symlink(s)`)}let n=zn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=zn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(Hn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,$G),S++)}S>0&&ge.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let X=C.find(n=>n.location===t)?.manifest,Z=extractOverrides(X),te=Z?.global,ne=new Map,re=new Set;if(Z&&Z.scoped.size>0){for(let t of F?.workspaces??C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){let C=scopedOverrideFor(t,n,Z);if(!C)continue;let N=C,F=t.location,I=ne.get(F);I||(I=new Set,ne.set(F,I)),I.add(`${n}@${N}`),re.add(`${n}@${S}`)}}}let t=new Set;for(let n of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(n,S,Z)||t.add(`${S}@${N}`)}for(let n of re)t.has(n)||H.delete(n);ne.size>0&&ge.log(`gjsify install: ${ne.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(H.size>0){let I=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1});await installPackages({prefix:t,specs:[...H],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],overrides:te,signal:S,progress:I,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,specOrigins:new Map([...W].map(([t,n])=>[t,[...n]])),optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest)),focusSpecs:F?.specs})}else n.verbose&&ge.log(`gjsify install: no external deps to fetch`);for(let[t,F]of ne){if(F.size===0)continue;let I=C.find(n=>n.location===t)?.name??t;n.verbose&&ge.log(`gjsify install: ${I} — installing ${F.size} scoped-override spec(s) into ${t}/node_modules/`),await installPackages({prefix:t,specs:[...F],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,signal:S,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest))})}await wireWorkspaceSymlinks(),reportRewiredDevLinks(Y);let ie=writeWorkspaceBinShims(t,F?.workspaces??C);ie>0&&ge.log(`gjsify install: linked ${ie} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(t,n){let S=zn(t,`node_modules`,`.bin`),C=detectNativePackages(t).map(t=>t.prebuildsDir),N=0;for(let F of n){let n=F.manifest,I=n.gjsify?.bin,H=n.bin,W=mergeWorkspaceBins(F.name,I,H);if(W.size!==0){mkdirSync(S,{recursive:!0});for(let[n,{nodeTarget:I,gjsTarget:H}]of W){let W=zn(S,n);for(let t of[W,`${W}.cmd`,`${W}.ps1`])try{rmSync(t,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(W,buildBinShim(F.location,I,H,C,process.platform,t),{mode:493}),chmodSync(W,493),process.platform===`win32`)for(let[t,n]of Object.entries(buildWorkspaceBinShimsForWindows(F.location,I,H,C)))writeFileSync(`${W}.${t}`,n,{mode:493});N++}}}return N}function extractOverrides(t){if(!t)return;let n={},S=new Map,merge=(t,C)=>{if(t){for(let[N,F]of Object.entries(t))if(!N.startsWith(`_`)){if(typeof F==`string`){let t=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(t=N.slice(0,S)),n[t]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let t={};for(let[n,S]of Object.entries(F)){if(n.startsWith(`_`))continue;if(typeof S!=`string`){ge.warn(`gjsify install: ${C}["${N}"]["${n}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=n,I=n.startsWith(`@`)?n.indexOf(`@`,1):n.indexOf(`@`);I>0&&(F=n.slice(0,I)),t[F]=S}if(Object.keys(t).length>0){let n=S.get(N)??{};S.set(N,{...n,...t})}continue}ge.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(t.overrides,`overrides`),merge(t.resolutions,`resolutions`),!(Object.keys(n).length===0&&S.size===0))return{global:n,scoped:S}}function scopedOverrideFor(t,n,S){if(!S||S.scoped.size===0)return;let C=[t.name,t.relativeLocation];for(let t of C){let C=S.scoped.get(t);if(C?.[n])return C[n]}}function buildBinShim(t,n,S,C=[],N=process.platform,F=t){let I=n?zn(t,n):null,H=S?zn(t,S):null,W=buildNativeEnvPreamble(F,C,{platform:N});if(I&&H){let t=N===`darwin`||N===`win32`,n=`if command -v gjs >/dev/null 2>&1 && [ -f "${H}" ]; then\n${W}exec gjs -m "${H}" "$@"\nfi\nexec node "${I}" "$@"\n`,S=`if command -v node >/dev/null 2>&1 && [ -f "${I}" ]; then\nexec node "${I}" "$@"\nfi\n${W}exec gjs -m "${H}" "$@"\n`;return`#!/bin/sh
|
|
1249
1249
|
`+(t?S:n)}if(I)return`#!/bin/sh\nexec node "${I}" "$@"\n`;if(H)return`#!/bin/sh\n${W}exec gjs -m "${H}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(t,n,S,C=[]){let N=n?zn(t,n):null,F=S?zn(t,S):null;if(N)return buildLauncherShims({interpreter:`node`,target:N});if(F){let t=C.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:F,prependEnv:C.length===0?{}:{GI_TYPELIB_PATH:t,PATH:t}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(t,n,S){let C=new Map,N=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t,get=t=>{let n=C.get(t);return n||(n={},C.set(t,n)),n};if(typeof S==`string`)get(N).nodeTarget=S;else if(S&&typeof S==`object`)for(let[t,n]of Object.entries(S))typeof n==`string`&&n.length>0&&(get(t).nodeTarget=n);if(typeof n==`string`)get(N).gjsTarget=n;else if(n&&typeof n==`object`)for(let[t,S]of Object.entries(n))typeof S==`string`&&S.length>0&&(get(t).gjsTarget=S);return C}async function projectInstallViaNpm(t){let n=[`install`];t[`save-dev`]&&n.push(`--save-dev`),t[`save-peer`]&&n.push(`--save-peer`),t[`save-optional`]&&n.push(`--save-optional`),t.verbose&&n.push(`--loglevel`,`verbose`),t.packages&&t.packages.length>0&&n.push(...t.packages),await spawnNpm(n)}async function spawnNpm(t){return spawnToCompletion(`npm`,t,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:t})=>{if(t!==0)throw Error(`npm install exited with code ${t}`)}).catch(t=>{let n=t.code;ge.error(n===void 0?t.message:`npm install failed: ${t.message}`),process.exit(1)})}async function installGlobalAndLink(t,n){let S=defaultGlobalLayout();mkdirSync(S.prefix,{recursive:!0}),ge.log(`gjsify install --global → ${S.prefix}`),ge.log(` bins → ${S.binDir}`);let C=await acquireInstallLock(S.prefix,{});try{let C=await installPackages({prefix:S.prefix,specs:t,verbose:n.verbose}),N=t.map(specToPackageName);if(N.includes(`@gjsify/cli`)){let t=C.installed.find(t=>t.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(S.prefix,t,{verbose:n.verbose})}n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(N,S),S.binDir)}finally{C.release()}}function pruneProjectPrefix(t){t.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:t.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(t,n){if(t.length===0)ge.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ge.log(`\nLinked ${t.length} bin(s):`);for(let n of t)ge.log(` • ${n.link} → ${n.target}`)}t.length>0&&!binDirOnPath(n)&&ge.warn(`\nNote: ${n} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${n}:$PATH"`)}async function ensureProjectGjsEngine(t,n,S={}){let C=S.cwd??process.cwd(),N=S.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${Jz} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
|
|
1250
1250
|
gjsify install ${Jz}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let F=readCliVersionFrom(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ge.log(`\n${Jz} is missing and this host can run gjs, so \`gjsify build\` would have no\n bundler engine (there is no npm \`rolldown\` fallback under GJS). Installing the GJS engine set at\n ${F}, in lockstep with the CLI.`),await(S.installFn??installGjsEnginePackages)(C,F,{verbose:t.verbose})}async function runPostInstallChecks(t){ge.log(`
|
|
1251
1251
|
--- gjsify post-install checks ---`);let n=runMinimalChecks(),S=n.filter(t=>!t.found&&t.severity===`required`);if(S.length>0){ge.warn(`Missing required system dependencies:
|
|
@@ -1257,27 +1257,27 @@ jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
|
|
|
1257
1257
|
A bridge lost that way is silently absent from the next build rather than
|
|
1258
1258
|
reported, so the first symptom can be an unrelated-looking bundler error
|
|
1259
1259
|
(\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
|
|
1260
|
-
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var QG,$G,eK,tK,nK=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),ZG(),KI(),fL(),_L(),PR(),Kz(),QR(),_z(),WR(),hv(),JI(),MV(),Xz(),jz(),Nz(),XR(),Iz(),QG=process.platform===`win32`?`junction`:void 0,$G=18e5,eK={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:$G}).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)}}},tK=`@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 rK,iK,aK=__esmMin(()=>{_e(),af(),Xn(),Iz(),rK={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Bn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H),re=[];try{re=readDevLinkOverride(n)?.closure??[]}catch{}writeDevLinkOverride(n,{version:1,checkout:C,packages:I,closure:syncDevLinkClosure(H,C,re)});let ie=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}`),ie===`added`&&ge.log(` git: ${Pz} added to .git/info/exclude (local, never committed)`),ie===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),ie===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${Pz} 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`.")}},iK={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 ${Pz}).`);return}let N=[],F=[];try{let t=readDevLinkOverride(n);t?.checkout&&N.push(t.checkout),F=t?.closure??[]}catch{}let I=[];try{I=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 H=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${H} in ${n}`),S){let t=new Set(I.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}`);for(let t of F)ge.log(` would remove link ${t}`);ge.log(` would remove ${C}`),ge.log(` would remove ${Pz} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${H}: nothing changed. Drop --dry-run to apply.`);return}let W=removeDevLinks(I),q=new Set(W.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))q.has(t.name)||W.push(t);for(let t of W)ge.log(` unlinked ${t.name}`);for(let t of removeDevLinkClosure(F))ge.log(` unlinked ${t}`);let Y=scanDevLinks(n,N);if(Y.length>0)return ge.error(`gjsify unlink: ${Y.length} link(s) still point into a checkout and could not be removed:\n`+Y.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
|
|
1261
|
-
`)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${Pz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${W.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${W.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:X}=await Promise.resolve().then(()=>(
|
|
1262
|
-
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),lK).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,sK.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&&sK.delete(N)}}var sK,cK,lK,uK,dK=__esmMin(()=>{_e(),hv(),cz(),o_(),KI(),JI(),oK(),lB(),ER(),pB(),gB(),sK=new Set,cK=5e3,lK=15e3,uK={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var fK=__esmMin(()=>{Xn(),hv(),JI()});async function packWorkspace(t,n={}){let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1260
|
+
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var $G,eK,tK,nK,rK=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),QG(),KI(),fL(),_L(),PR(),Kz(),QR(),_z(),WR(),hv(),JI(),NV(),Xz(),jz(),Nz(),XR(),Iz(),$G=process.platform===`win32`?`junction`:void 0,eK=18e5,tK={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:eK}).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)}}},nK=`@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 iK,aK,oK=__esmMin(()=>{_e(),af(),Xn(),Iz(),iK={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Bn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H),re=[];try{re=readDevLinkOverride(n)?.closure??[]}catch{}writeDevLinkOverride(n,{version:1,checkout:C,packages:I,closure:syncDevLinkClosure(H,C,re)});let ie=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}`),ie===`added`&&ge.log(` git: ${Pz} added to .git/info/exclude (local, never committed)`),ie===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),ie===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${Pz} 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`.")}},aK={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 ${Pz}).`);return}let N=[],F=[];try{let t=readDevLinkOverride(n);t?.checkout&&N.push(t.checkout),F=t?.closure??[]}catch{}let I=[];try{I=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 H=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${H} in ${n}`),S){let t=new Set(I.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}`);for(let t of F)ge.log(` would remove link ${t}`);ge.log(` would remove ${C}`),ge.log(` would remove ${Pz} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${H}: nothing changed. Drop --dry-run to apply.`);return}let W=removeDevLinks(I),q=new Set(W.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))q.has(t.name)||W.push(t);for(let t of W)ge.log(` unlinked ${t.name}`);for(let t of removeDevLinkClosure(F))ge.log(` unlinked ${t}`);let Y=scanDevLinks(n,N);if(Y.length>0)return ge.error(`gjsify unlink: ${Y.length} link(s) still point into a checkout and could not be removed:\n`+Y.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
|
|
1261
|
+
`)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${Pz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${W.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${W.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:X}=await Promise.resolve().then(()=>(GX(),WX));await X([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var sK=__esmMin(()=>{af(),Xn(),pP(),Ch()});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of cK){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of cK){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},lK).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
|
|
1262
|
+
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),uK).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,cK.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&&cK.delete(N)}}var cK,lK,uK,dK,fK=__esmMin(()=>{_e(),hv(),cz(),o_(),KI(),JI(),sK(),lB(),ER(),pB(),gB(),cK=new Set,lK=5e3,uK=15e3,dK={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var pK=__esmMin(()=>{Xn(),hv(),JI()});async function packWorkspace(t,n={}){let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1263
1263
|
`,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(zn(t,n)));let C=statSync(zn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?In(n.destination):t,ce=zn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(zn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=zn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
|
|
1264
1264
|
`)+`
|
|
1265
|
-
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(
|
|
1266
|
-
`);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of
|
|
1265
|
+
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(hK.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=n?`${n}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(t,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(t,n){let S=new Set,C=null;for(let N of n){let n=N.replace(/^\.\//,``).replace(/\/$/,``);if(!n)continue;if(!/[*?[\]]/.test(n)){let C=zn(t,n);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(t,n))S.add(C);else N.isFile()&&S.add(n);continue}C??=walkAll(t);let F=filesGlobToRegExp(n),I=filesGlobToRegExp(`${n}/**`);for(let t of C)(F.test(t)||I.test(t))&&S.add(t)}return[...S]}function filesGlobToRegExp(t){let n=`^`;for(let S=0;S<t.length;S++){let C=t[S];if(C===`*`)t[S+1]===`*`?(n+=`.*`,S++,t[S+1]===`/`&&S++):n+=`[^/]*`;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(t[C]===`!`&&(N+=`^`,C++);C<t.length&&t[C]!==`]`;C++)N+=t[C];C<t.length?(n+=`${N}]`,S=C):n+=`\\[`}else".+^${}()|\\]".includes(C)?n+=`\\${C}`:n+=C}return RegExp(`${n}$`)}function loadIgnore(t){let n=zn(t,`.npmignore`),S=zn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
|
|
1266
|
+
`);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of gK){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=zn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=In(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of gK){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 mK,hK,gK,_K=__esmMin(()=>{af(),fl(),Xn(),sz(),KI(),JI(),qI(),pK(),mK={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(In(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},hK=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`]),gK=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function parseRetryAfter(t,n=Date.now()){if(!t)return;let S=t.trim();if(/^\d+(?:\.\d+)?$/.test(S))return Math.round(Number(S)*1e3);let C=Date.parse(S);return Number.isNaN(C)?void 0:Math.max(0,C-n)}function retryDelayMs(t,n,S){let C=parseRetryAfter(S);return Math.min(C??n*2**t,yK)}async function fetchWithTransientRetry(t,n={}){let S=n.retries??5,C=n.baseMs??2e3,N=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),F=n.random??Math.random;for(let I=0;;I++){let H,W;try{H=await t()}catch(t){W=t}if(H&&!isTransientStatus(H.status))return{response:H,retried:I};if(I>=S){if(H)return{response:H,retried:I};throw W}let q=H?.headers.get(`retry-after`),Y=retryDelayMs(I,C,q),X=parseRetryAfter(q)===void 0?Math.round(Y*(.5+.5*F())):Y,Z=H?`${H.status} ${H.statusText}`:`network error: ${W instanceof Error?W.message:String(W)}`;n.log?.(`transient ${Z} (attempt ${I+1}/${S+1}), retrying in ${X}ms`),await N(X)}}var vK,isTransientStatus,yK,bK=__esmMin(()=>{vK=new Set([408,425,429,500,502,503,504]),isTransientStatus=t=>vK.has(t),yK=3e4});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n,S={}){let C=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,N=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!C||!N)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let F=`${C}${C.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I;try{({response:I}=await fetchWithTransientRetry(()=>fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}}),{...retryOptions(S),log:n&&(t=>n(`gjsify oidc: id_token ${t}`))}))}catch(t){throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: network error — ${t instanceof Error?t.message:String(t)}`,`fetch-id-token`)}if(!I.ok){let t=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let H=await I.json().catch(()=>({}));if(!H.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return H.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I,H;try{({response:I,retried:H}=await fetchWithTransientRetry(()=>fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`}),{...retryOptions(t),log:N&&(t=>N(`gjsify oidc: ${t} for ${n}`))}))}catch(t){throw new OidcExchangeError(`npm OIDC token exchange network error for ${n}: ${t instanceof Error?t.message:String(t)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await I.text().catch(()=>``);if(!I.ok)throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${I.status} ${I.statusText} — ${W.slice(0,300)}${H?` (after ${H} retries)`:``}`,I.status,W,n,decodeJwtPayload(C)??void 0);let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,I.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,I.status,W,n,decodeJwtPayload(C)??void 0);return q.token}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log,t);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var retryOptions,OidcUnavailableError,OidcExchangeError,xK,SK=__esmMin(()=>{bK(),retryOptions=t=>({retries:t.maxRetries??5,baseMs:t.retryBaseMs??2e3,sleep:t.sleep,random:t.random}),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}},xK="Trust entries are stored but the OIDC exchange is only verifiable in CI: run `gh workflow run release.yml --ref main -f verify_only=true -f skip_publish=true` and check for ✗ lines."});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
|
|
1267
1267
|
`)}function formatLiveToken404(t,n,S){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`Authenticated as: ${S}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${t} is not (yet) on npmjs.com. Two cases:`,``,` 1. First publish of a brand-new scoped package — do the one-time bootstrap`,` (see AGENTS.md > "New @gjsify/* package: first-publish + Trusted`,` Publisher bootstrap"). The npm registry can also 404 *transiently*`,` while provisioning a brand-new package: simply re-run, or do the very`," first publish with `npm publish` (then configure the Trusted Publisher)."," 2. You lack publish access to the scope — verify with `npm access ls-packages`."].join(`
|
|
1268
|
-
`)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var
|
|
1269
|
-
`)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++
|
|
1270
|
-
`))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:
|
|
1271
|
-
`)}var
|
|
1268
|
+
`)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var CK=__esmMin(()=>{xh()});function backoffFor(t){return wK[Math.min(Math.max(t,0),wK.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,TK))}function budgetForPayload(t,n){if(t<6e5||n<=DK)return t;let S=(n-DK)/(1024*1024);return t+Math.ceil(S)*OK}function cacheBustedUrl(t,n){return`${t}${t.includes(`?`)?`&`:`?`}__gjsify_readback=${encodeURIComponent(n)}`}async function verifyPublishedVersion(t){let{registry:n,name:S,version:C,budgetMs:N}=t,F=t.fetchImpl??((...t)=>globalThis.fetch(...t)),I=t.sleep??(t=>new Promise(n=>setTimeout(n,t))),H=t.now??(()=>Date.now()),W=t.probeTimeoutMs??3e4,q=`${n.endsWith(`/`)?n.slice(0,-1):n}/${escapePackageName(S)}`,Y=H(),X=0,Z={state:`error`,detail:`no probe was sent`};for(let n=0;X++,Z=await probeOnce({url:q,version:C,doFetch:F,probeTimeoutMs:probeTimeoutFor(W,N-(H()-Y)),authorization:t.authorization,nonce:`${Y}-${X}`}),t.log?.(`gjsify publish: read-back probe ${X} of ${S}@${C} → ${Z.state}`+(Z.state===`present`?``:` (${Z.detail})`)),Z.state!==`present`;n++){let t=N-(H()-Y);if(t<=0)break;await I(Math.min(backoffFor(n),t))}let te={attempts:X,elapsedMs:H()-Y,url:q,last:Z};if(Z.state===`present`)return{...te,confirmed:!0,verdict:`confirmed`,verdictDetail:`${q} serves ${C} with a tarball`};if(Z.state===`error`)return{...te,confirmed:!1,verdict:`unknown`,verdictDetail:`the read-back could not reach a verdict — ${Z.detail}`};let ne=await probeRegistryRecord({url:q,version:C,doFetch:F,probeTimeoutMs:W,authorization:t.authorization,nonce:`${Y}-record`});return t.log?.(`gjsify publish: read-back record probe of ${S}@${C} → ${ne.state} (${ne.detail})`),ne.state===`recorded`?{...te,confirmed:!1,verdict:`recorded-not-served`,verdictDetail:ne.detail,recordedAt:ne.recordedAt}:ne.state===`no-record`?{...te,confirmed:!1,verdict:`not-published`,verdictDetail:ne.detail}:{...te,confirmed:!1,verdict:`unknown`,verdictDetail:ne.detail}}async function probeRegistryRecord(t){let{url:n,version:S,doFetch:C,probeTimeoutMs:N}=t,F=new AbortController,I=setTimeout(()=>F.abort(),N),H;try{H=await C(cacheBustedUrl(n,t.nonce),{headers:{"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},signal:F.signal})}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record was unreadable (${t instanceof Error?t.message:String(t)})`}}finally{clearTimeout(I)}if(H.status===404)return{state:`no-record`,detail:`the registry has no packument for this name at all (404)`};if(!H.ok)return{state:`unknown`,detail:`the registry serves no ${S} and its own record answered ${H.status} ${H.statusText}`};let W;try{W=await H.json()}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record is not JSON (${t instanceof Error?t.message:String(t)})`}}let q=W?.time,Y=q&&typeof q==`object`?q[S]:void 0;return typeof Y==`string`&&Y.length>0?{state:`recorded`,recordedAt:Y,detail:`the registry RECORDS ${S} at ${Y} and its install document does not serve it`}:{state:`no-record`,detail:`the registry has no record of ${S} — neither in its install document nor in its own \`time\` map`}}async function sendPackumentRequest(t){let{url:n,doFetch:S,probeTimeoutMs:C}=t,N={accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},send=async t=>{let n=new AbortController,F=setTimeout(()=>n.abort(),C);try{return await S(t,{headers:N,signal:n.signal})}finally{clearTimeout(F)}},F;try{F=await send(cacheBustedUrl(n,t.nonce)),!F.ok&&F.status!==404&&F.status>=400&&F.status<500&&(F=await send(n))}catch(t){return{error:`request failed (${t instanceof Error?t.message:String(t)})`}}return F}async function probeOnce(t){let{version:n}=t,S=await sendPackumentRequest(t);if(`error`in S)return{state:`error`,detail:S.error};let C=S;if(C.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!C.ok)return{state:`error`,status:C.status,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`error`,status:C.status,detail:`packument is not JSON (${n})`}}let F=N?.versions,I=F&&typeof F==`object`?Object.keys(F):[],H=F&&typeof F==`object`&&Object.hasOwn(F,n)?F[n]:void 0;if(!H){let t=I.length>0?I[I.length-1]:`(none)`;return{state:`absent`,status:C.status,detail:`packument carries ${I.length} version(s), newest ${t} — ${n} is not among them`}}let W=H.dist?.tarball;return typeof W!=`string`||W.length===0?{state:`absent`,status:C.status,detail:`packument has ${n} but its \`dist.tarball\` is missing`}:{state:`present`,status:C.status,tarball:W}}function formatUnconfirmedPublish(t){let{name:n,version:S,putUrl:C,putStatus:N,putStatusText:F,payloadBytes:I,readback:H}=t,W=t.claim??`accepted`,q=(H.elapsedMs/1e3).toFixed(1),Y=H.last.state===`present`?`served`:H.last.detail,X=W===`already-published`?`npm says ${S} is ALREADY PUBLISHED`:`npm ACCEPTED the upload`,Z=H.verdict===`unknown`?H.last.state===`absent`?`${X}; its install document does not serve ${S} and the registry's own record could NOT be read.`:`${X} and the read-back could NOT establish whether the registry serves it.`:H.verdict===`recorded-not-served`?`${X}; the registry RECORDS ${S} and its install document does not serve it.`:`${X} and the registry has no record of ${S}.`,te=H.verdict===`unknown`?[` This is NOT a report that the publish failed, and it is not one that it worked. The read-back`,` reached no answer it could act on, so the version may or may not be installable — confirm it`," before releasing anything that depends on it (`npm view <name>@<version> dist.tarball`)."]:H.verdict===`recorded-not-served`?[` Do NOT re-publish: the registry holds the write, so a re-run is answered 409 and changes`,` nothing. The document npm installs from is behind the registry's own record — measured on`,` the ts-for-gir v5.1.0 release, @ts-for-gir/reporter was recorded at 21:43:00.983Z and a`,` cache-busted read of its install document still did not carry 5.1.0 ~40 min later. Wait and`,` re-read; if it persists, check https://status.npmjs.org/.`]:W===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it:`,` in the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and`,` the registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it`," cannot fix this — wait and re-read (`npm view <name>@<version>`), or check",` https://status.npmjs.org/.`]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${n}@${S} — ${Z}`,` PUT ${C} (${I} bytes) → ${N} ${F}`,` read-back GET ${H.url} (accept: application/vnd.npm.install-v1+json, per-probe cache buster)`,` answered ${H.last.state}: ${Y}`,` after ${H.attempts} probe(s) over ${q}s`,` verdict ${H.verdict} — ${H.verdictDetail}`,...te].join(`
|
|
1269
|
+
`)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++kK}`});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 wK,TK,EK,DK,OK,kK,AK=__esmMin(()=>{Ch(),wK=[2e3,4e3,8e3,15e3,3e4],TK=2e3,EK=6e5,DK=32*1024*1024,OK=1e4,kK=0});function collectWorkspacePins(t,n){let S=[];for(let C of jK){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 jK,MK,depsOf,NK=__esmMin(()=>{jK=[`dependencies`,`optionalDependencies`,`peerDependencies`],MK=`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`||!PK.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 PK,FK=__esmMin(()=>{Ch(),PK=[`published`,`validating`,`staged`,`blocked`,`deleted`]});function appendLedger(t,n){t&&appendFileSync(t,`${JSON.stringify(n)}\n`)}function readLedger(t){if(!t||!existsSync(t))return[];let n=[];for(let S of readFileSync(t,`utf-8`).split(`
|
|
1270
|
+
`))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:LK});if(I.confirmed)return confirmedServed(t,N,n,S);let ask=()=>fetchVersionStatus({registry:t.registry,name:n,version:S,token:t.statusToken,fetchImpl:t.fetchImpl}),H=classifyUnserved(I.verdict,await ask());if(!H.terminal&&t.waitBudgetMs>0){if(I=await verifyPublishedVersion({...F,budgetMs:t.waitBudgetMs}),I.confirmed)return confirmedServed(t,N,n,S);H=classifyUnserved(I.verdict,await ask())}return{...C,cls:H.cls,detail:H.detail}}function confirmedServed(t,n,S,C){return n?.ev===`unserved`&&appendLedger(t.ledgerPath,{ev:`served`,name:S,version:C}),null}function summariseReasons(t){return t.map(t=>`${t.name}@${t.version} is ${t.cls===`held`?`held`:describeClass(t.cls)}`).join(`; `)}async function recordUnserved(t){let n=await fetchVersionStatus({registry:t.registry,name:t.name,version:t.version,token:t.statusToken,fetchImpl:t.fetchImpl}),S=classifyUnserved(t.verdict,n);return appendLedger(t.ledgerPath,{ev:`unserved`,name:t.name,version:t.version,cls:S.cls,detail:S.detail}),S}function pendingEntries(t){let n=new Map;for(let S of t)n.set(`${S.name}@${S.version}`,S);let S=[...n.values()];return{unserved:S.filter(t=>t.ev===`unserved`),held:S.filter(t=>t.ev===`held`)}}function markHeldPublished(t,n,S){[...readLedger(t)].reverse().find(t=>t.name===n&&t.version===S)?.ev===`held`&&appendLedger(t,{ev:`served`,name:n,version:S})}async function settleUnserved(t){let n=pendingEntries(t.entries).unserved.filter(t=>!isTerminalClass(t.cls));return(await Promise.all(n.map(async n=>{if((await verifyPublishedVersion({registry:t.registryFor(n.name),name:n.name,version:n.version,budgetMs:t.budgetMs,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log})).confirmed)return appendLedger(t.ledgerPath,{ev:`served`,name:n.name,version:n.version}),`${n.name}@${n.version}`}))).filter(t=>t!==void 0)}function renderLedgerSummary(t,n){let{unserved:S,held:C}=pendingEntries(t);if(S.length===0&&C.length===0)return;let N=[`### npm versions that were accepted but are not installable`,``];if(S.length>0){N.push(`| Package | Version | State | Detail |`,`| --- | --- | --- | --- |`);for(let t of S)N.push(`| \`${t.name}\` | ${t.version} | ${describeClass(t.cls)} | ${t.detail} |`);N.push(``)}if(C.length>0){N.push(`### Held — NOT published in this run`,``,`Each package below depends on a version npm does not serve, so publishing it would have shipped a package that cannot be installed.`,``,`| Package | Version | Because |`,`| --- | --- | --- |`);for(let t of C)N.push(`| \`${t.name}\` | ${t.version} | ${summariseReasons(t.reasons)} |`);N.push(``,"Once the dependencies above are served by npm (a `validating` version appears on its own, or is approved/released by a maintainer), publish the held set with:",``,"```sh",`gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${[...new Set(C.map(t=>t.name))].join(` `)}'`,"```"),S.some(t=>t.cls===`blocked`||t.cls===`deleted`)&&N.push(``,"A `blocked` or `deleted` version is a spent number: re-running the release cannot serve it, the package needs a version bump.")}return N.join(`
|
|
1271
|
+
`)}var IK,LK,holdsPublish,RK=__esmMin(()=>{af(),NK(),AK(),FK(),IK=3e5,LK=1,holdsPublish=t=>t.block===MK});function beginPrompt(){zK++}function endPrompt(t=defaultWrite){if(zK=Math.max(0,zK-1),zK>0||BK.length===0)return;let n=BK.splice(0,BK.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(zK>0){BK.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var zK,BK,VK=__esmMin(()=>{zK=0,BK=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
|
|
1272
1272
|
`?{buf:t,echo:`
|
|
1273
|
-
`,done:!0,interrupt:!1}:n===
|
|
1274
|
-
`,done:!1,interrupt:!0}:n===
|
|
1275
|
-
Enter OTP: `,
|
|
1276
|
-
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?YK
|
|
1277
|
-
`)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(sz(),oz)),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 ZK,QK=__esmMin(()=>{_e(),af(),o_(),Xn(),CW(),xh(),Ch(),gK(),xK(),SK(),kK(),MK(),LK(),PK(),OB(),XK(),WK(),yK(),ZK={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:TK/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:FK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:TK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=$K[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,$K,clean,eq=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,$K={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
|
|
1273
|
+
`,done:!0,interrupt:!1}:n===HK?{buf:t,echo:`
|
|
1274
|
+
`,done:!1,interrupt:!0}:n===UK||n===WK?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 HK,UK,WK,GK=__esmMin(()=>{VK(),HK=``,UK=``,WK=`\b`});function isOtpCacheEnabled(){let t=process.env[KK];return!(t===`1`||t===`true`||t===`yes`)}function normalizeRegistry(t){return t.endsWith(`/`)?t.slice(0,-1):t}function cacheBaseDir(t){if(t?.dir)return t.dir;let n=process.env.XDG_RUNTIME_DIR;return zn(n&&n.length>0?n:tmpdir(),qK)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return zn(cacheBaseDir(n),`otp-${S||`default`}.json`)}function readCachedOtp(t,n){if(!isOtpCacheEnabled())return;let S=n?.now??Date.now(),C=cacheFileFor(t,n);try{if(!existsSync(C))return;let n=JSON.parse(readFileSync(C,`utf8`));if(!n||typeof n.otp!=`string`||typeof n.expiresAt!=`number`){deleteCacheFile(C);return}if(n.registry!==normalizeRegistry(t))return;if(S>=n.expiresAt){deleteCacheFile(C);return}return n.otp.length>0?n.otp:void 0}catch{deleteCacheFile(C);return}}function writeCachedOtp(t,n,S){if(!isOtpCacheEnabled()||!n||n.length===0)return;let C=S?.now??Date.now(),N=S?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(S),{recursive:!0,mode:448});let F=cacheFileFor(t,S),I={otp:n,expiresAt:C+N,registry:normalizeRegistry(t)};writeFileSync(F,JSON.stringify(I),{mode:384}),chmodSync(F,384)}catch{}}function clearCachedOtp(t,n){deleteCacheFile(cacheFileFor(t,n))}function deleteCacheFile(t){try{existsSync(t)&&rmSync(t,{force:!0})}catch{}}var KK,qK,JK=__esmMin(()=>{af(),o_(),Xn(),KK=`GJSIFY_NO_OTP_CACHE`,qK=`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 YK,XK,OtpProvider,ZK=__esmMin(()=>{GK(),JK(),YK=`This operation requires a one-time password.
|
|
1275
|
+
Enter OTP: `,XK=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
|
|
1276
|
+
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?XK:YK));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(t){let n=(await this.promptFn(t)).trim();return n&&(this.cached=n,this.generation++,this.registry&&writeCachedOtp(this.registry,n)),n}invalidate(t){t!==void 0&&this.generation!==t||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});function remainingHoldDeadlineMs(){let t=Number(process.env.GJSIFY_HOLD_DEADLINE);return Number.isFinite(t)&&t>0?Math.max(0,t-Date.now()):1/0}function acceptsRepublish(t,n,S,C){return(t===409||t===403&&/previously published/i.test(n))&&(S||C)}async function publishWorkspace(t){let{wsDir:n,tag:S,access:C,provenance:N,tolerate:F,tolerateUntrustedNew:I,trustedFlag:H,verbose:W,json:q,otpProvider:Y}=t,X=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:q?`inherit-stderr`:`inherit`}),Z=await packWorkspaceToBytes(n),te=readFileSync(zn(n,`package.json`),`utf-8`),ne=JSON.parse(te),re=await loadRewrittenManifest(n,ne),ie=await loadNpmrc(n),ae=t.registry??process.env.npm_config_registry??registryFor(X.name,ie)??ph,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,Q=`${oe}/${escapePackageName(X.name)}`,se=`${X.name.includes(`/`)?X.name.slice(X.name.indexOf(`/`)+1):X.name}-${X.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:S,access:C,tarballBytes:Z,tarballUrl:`${oe}/${X.name}/-/${se}`,packed:{...X,wireFilename:se},provenance:N}),le=buildPublishHeaders(Q,{npmrc:ie}),ue=new Set(t.assumePresent??[]),de=collectWorkspacePins(ne,re).filter(t=>!ue.has(t.name));if(de.length>0){let t=await Promise.all(de.map(async t=>({pin:t,presence:await probePackageName({registry:ae,name:t.name,authorization:le.authorization})}))),n=[];for(let{pin:S,presence:C}of t){if(C.state===`present`)continue;let t=`${S.block}.${S.name}@${S.spec}`;if(C.state===`unknown`){ge.error(`gjsify publish: could not establish whether ${S.name} exists (${C.detail}) — not blocking on ${t}`);continue}if(S.block!==`dependencies`){ge.error(`gjsify publish: ${t} names a package ${ae} does not have — npm installs around it, Yarn (\`YN0035\`) does not`);continue}n.push(S)}if(n.length>0)return{ok:I,action:`blocked-missing-dependency`,name:X.name,version:X.version,registry:ae,tolerated:I,missing:n}}let fe=process.env.GJSIFY_PUBLISH_LEDGER;if(de.length>0){let n=await findUnavailablePins({registry:oe,pins:de,ledger:readLedger(fe),ledgerPath:fe,authorization:le.authorization,statusToken:statusTokenFromEnv(process.env),waitBudgetMs:t.holdWaitMs??3e5,log:W?t=>ge.error(t):void 0});for(let t of n.filter(t=>!holdsPublish(t)))ge.error(`gjsify publish: ${t.block}.${t.name}@${t.version} is not served (${t.detail}) — optional edge, publishing anyway`);let S=n.filter(holdsPublish);if(S.length>0)return appendLedger(fe,{ev:`held`,name:X.name,version:X.version,reasons:S}),{ok:!1,action:`held-unpublished-dependency`,name:X.name,version:X.version,registry:oe,reasons:S}}let pe=H===!0||H===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,me=`token`;if(pe)try{let{token:t,audience:n}=await getNpmTrustedToken({packageName:X.name,registry:ae,log:W?t=>ge.error(t):void 0});le.authorization=`Bearer ${t}`,me=`oidc`,W&&ge.error(`gjsify publish: OIDC token obtained (audience=${n})`)}catch(t){if(t instanceof OidcExchangeError&&t.status===404&&/package not found/i.test(t.body)&&I)return{ok:!0,action:`skipped-untrusted-new`,name:X.name,version:X.version};if(H===!0)return{ok:!1,action:`oidc-failed`,name:X.name,version:X.version,error:t};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:X.name,version:X.version,error:t};if(W){let n=t instanceof Error?t.message:String(t);ge.error(`gjsify publish: OIDC auto-detect failed (${n}) — falling back to token auth`)}}W&&(ge.error(`gjsify publish: PUT ${Q} (${X.name}@${X.version})`),ge.error(` auth-mode: ${me}`),ge.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ge.error(` payload size: ${JSON.stringify(ce).length} bytes`));let he=JSON.stringify(ce),_e=!1,doPut=async n=>{let S={...le};n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`);let{response:C,retried:N}=await fetchWithTransientRetry(()=>fetch(Q,{method:`PUT`,headers:S,body:he}),{log:t=>ge.error(`gjsify publish: PUT ${X.name}@${X.version}: ${t}`),...t.putRetry});return N>0&&(_e=!0),C},ve=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${ve.status} ${ve.statusText}`);let t=await ve.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(n<=0)return;let S=budgetForPayload(n,he.length);return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:S,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(ve))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:ve.status};if(ve.ok){let t=await readBack();return t?.confirmed&&W&&ge.error(` read-back: confirmed after ${t.attempts} probe(s) in ${t.elapsedMs} ms`),t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`published`,name:X.name,version:X.version,filename:X.filename,size:X.size,integrity:X.integrity,tag:S,registry:oe,readback:t})}let ye=await ve.text().catch(()=>`<no body>`);if(acceptsRepublish(ve.status,ye,F,_e)){let t=await readBack();return t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:ve.status,registry:oe,readback:t})}if(ve.status===404&&me===`token`&&is404DiagnosticCandidate(ye)){let t=await diagnose404({packageName:X.name,version:X.version,registry:oe,npmrc:ie});if(t.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:X.name,version:X.version,status:404,diag:t}}return{ok:!1,action:`error`,name:X.name,version:X.version,status:ve.status,statusText:ve.statusText,text:ye}}function describeVerification(t,n){if(!t?.confirmed)return{verified:!1,clause:`(UNVERIFIED — read-back disabled by --verify-timeout 0)`,json:null};let S=(t.elapsedMs/1e3).toFixed(1);return{verified:!0,clause:`(verified on ${n} — ${t.attempts} probe(s), ${S}s)`,json:{registry:n,verdict:t.verdict,probes:t.attempts,elapsedMs:t.elapsedMs,tarball:t.last.state===`present`?t.last.tarball:null}}}function warnUnverified(t,n,S){process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Publish unverified::${t}@${n} was published with the read-back disabled (--verify-timeout 0) — nothing confirmed that ${S} serves it\n`)}function reportPublishOutcome(t,n,S=!1){switch(t.action){case`published`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,name:t.name,version:t.version,filename:t.filename,size:t.size,integrity:t.integrity,tag:t.tag,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${t.name}@${t.version} ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`held-unpublished-dependency`:{let C=summariseReasons(t.reasons);return n?process.stdout.write(`${JSON.stringify({ok:!1,action:`held-unpublished-dependency`,name:t.name,version:t.version,registry:t.registry,reasons:t.reasons,deferred:S},null,2)}\n`):process.stderr.write(`~ ${t.name}@${t.version} (HELD — not published: ${C})\n`),process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Package held::${t.name}@${t.version} was NOT published: ${C}\n`),S?void 0:process.exit(1)}case`publish-unconfirmed`:{let C=`${formatUnconfirmedPublish(t)}\n state: ${describeClass(t.classification.cls)} — ${t.classification.detail}`;if(n?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:t.name,version:t.version,registry:t.registry,claim:t.claim,putStatus:t.putStatus,probes:t.readback.attempts,elapsedMs:t.readback.elapsedMs,readbackUrl:t.readback.url,readbackState:t.readback.last.state,verdict:t.readback.verdict,verdictDetail:t.readback.verdictDetail,recordedAt:t.readback.recordedAt??null,deferred:S,class:t.classification.cls,classDetail:t.classification.detail},null,2)}\n`):process.stderr.write(`${C}\n`),S){if(process.env.GITHUB_ACTIONS){let n=t.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${t.name}@${t.version} ${n} (HTTP ${t.putStatus}) but did not resolve on ${t.registry} within ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}; ${describeClass(t.classification.cls)}] — the release-closure job must confirm it
|
|
1277
|
+
`)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(sz(),oz)),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 QK,$K=__esmMin(()=>{_e(),af(),o_(),Xn(),wW(),xh(),Ch(),_K(),SK(),CK(),AK(),NK(),RK(),FK(),OB(),ZK(),GK(),bK(),QK={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:EK/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:IK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:EK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=eq[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,eq,clean,tq=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,eq={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
|
|
1278
1278
|
`))}return S.join(`
|
|
1279
1279
|
|
|
1280
|
-
`)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var
|
|
1280
|
+
`)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var nq=__esmMin(()=>{vV(),tq()}),rq,iq=__esmMin(()=>{vR(),qI(),nq(),af(),Xn(),rq={command:`release-notes [release]`,description:"Print the `releases` entry for a version as GitHub Markdown (from the config or a metainfo file). Fails when there is no entry or no description.",builder:t=>t.positional(`release`,{description:"Version or tag (a leading `v` is accepted). Default: the version in package.json.",type:`string`}).option(`compare`,{description:"Append a `**Full changelog:**` compare link to the previous entry (needs `vcsBrowserUrl`).",type:`boolean`,default:!1}).option(`metainfo`,{description:"Read the `<release>` entries from this AppStream metainfo file instead of the config. Default without `releases` in the config: the file named by `gjsify.site.metainfo`.",type:`string`}),handler:async t=>{let n=process.cwd();try{let S=await new Config().forCommand(n),C=S.ship??{},N=S.flatpak??{},F=t.release??readPackageJson$2(zn(n,`package.json`))?.version;if(!F)throw Error(`no version given and package.json has none`);let{releases:I,source:H}=resolveReleases({metainfo:t.metainfo,configReleases:C.releases??N.releases,siteMetainfo:S.site?.metainfo,readMetainfo:t=>{try{return readFileSync(In(n,t),`utf8`)}catch{throw Error(`cannot read the metainfo file ${t}`)}}}),W=t.compare===!0?C.vcsBrowserUrl??N.vcsBrowserUrl:void 0;process.stdout.write(renderReleaseNotes({releases:I,source:H,version:stripVersionPrefix(F),repoUrl:W}))}catch(t){return process.stderr.write(`gjsify release-notes: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function px(t,n){return Math.round(t*n)}function planAndroidIcons(t){let n=[];for(let{name:S,scale:C}of oq){let N=`mipmap-${S}`;n.push({path:`${N}/ic_launcher.png`,kind:`legacy`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_round.png`,kind:`round`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_foreground.png`,kind:`foreground`,size:px(108,C)}),t.monochrome&&n.push({path:`${N}/ic_launcher_monochrome.png`,kind:`monochrome`,size:px(108,C)})}for(let{name:t,scale:S}of sq)n.push({path:`drawable-${t}/logo.png`,kind:`splash`,size:px(96,S)});let S=adaptiveIconXml(t.monochrome);return{png:n,text:[{path:`values/ic_launcher_background.xml`,content:backgroundXml(t.background)},{path:`mipmap-anydpi-v26/ic_launcher.xml`,content:S},{path:`mipmap-anydpi-v26/ic_launcher_round.xml`,content:S}]}}function backgroundXml(t){return`<?xml version="1.0" encoding="utf-8"?>
|
|
1281
1281
|
<resources>
|
|
1282
1282
|
<color name="ic_launcher_background">${t}</color>
|
|
1283
1283
|
</resources>
|
|
@@ -1287,12 +1287,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
|
|
|
1287
1287
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
|
1288
1288
|
${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
|
1289
1289
|
`:``}</adaptive-icon>
|
|
1290
|
-
`}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*
|
|
1290
|
+
`}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*cq,N=(100-t)/2;return`<svg ${C} width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="50" fill="${S}"/><image x="${N}" y="${N}" width="${t}" height="${t}" xlink:href="${dataUri(n)}"/></svg>`}return`<svg ${C} width="108" height="108" viewBox="0 0 108 108"><image x="21" y="21" width="66" height="66" xlink:href="${dataUri(n)}"/></svg>`}function sha256(t){return createHash(`sha256`).update(t).digest(`hex`)}function hashInputs(t){return sha256(JSON.stringify({generator:1,icon:sha256(t.icon),symbolic:t.symbolic===null?null:sha256(t.symbolic),background:t.background}))}function buildStamp(t,n,S){return{generator:1,inputs:t,files:[...n.png.map(t=>t.path),...n.text.map(t=>t.path)].map(t=>On.join(S,t)).sort()}}function checkStamp(t,n,S){if(t===null)return{current:!1,reason:`was never generated`};let C;try{C=JSON.parse(t)}catch{return{current:!1,reason:`has an unreadable stamp`}}if(C.generator!==1||C.inputs!==n)return{current:!1,reason:`is out of date with the icon, colour or generator`};let N=(C.files??[]).find(t=>!S(t));return N===void 0?{current:!0}:{current:!1,reason:`lacks ${N}`}}var aq,oq,sq,cq,lq=__esmMin(()=>{fl(),Xn(),DH(),aq=`.gjsify-android-icons.json`,oq=[{name:`mdpi`,scale:1},{name:`hdpi`,scale:1.5},{name:`xhdpi`,scale:2},{name:`xxhdpi`,scale:3},{name:`xxxhdpi`,scale:4}],sq=[{name:`ldpi`,scale:.75},...oq],cq=.72});function walk(t,n=[]){if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){let C=zn(t,S.name);S.isDirectory()?walk(C,n):n.push(C)}return n}function discoverIcon(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`the icon ${n} does not exist`);let C=symbolicSibling(S);return{icon:S,symbolic:existsSync(C)?C:null}}let S=[zn(t,`data`,`icons`),...siblingIconRoots(t)];for(let t of S){let n=pickIconSources(walk(t).filter(t=>t.toLowerCase().endsWith(`.svg`)).sort());if(n.icon!==null)return{icon:n.icon,symbolic:n.symbolic}}throw Error("no app icon found; pass --icon <svg> or set `gjsify.androidIcons.icon`")}function siblingIconRoots(t){let n=Hn(t);return existsSync(n)?readdirSync(n).sort().map(t=>zn(n,t,`data`,`icons`)).filter(n=>n!==zn(t,`data`,`icons`)&&existsSync(n)&&statSync(n).isDirectory()):[]}function findMetainfoColor(t,n){let S=new Set([zn(n,`data`)]);S.add(In(Hn(t),`..`,`..`,`..`,`..`));for(let t of S){let n=walk(zn(t,`metainfo`)).filter(t=>/\.metainfo\.xml(\.in)?$/.test(t)).sort();for(let t of n){let n=parseMetainfoBranding(readFileSync(t,`utf8`));if(n!==null)return n}}return null}var uq,dq,fq=__esmMin(()=>{af(),o_(),Xn(),vR(),lq(),DH(),uq=`Android/src/main/res`,dq={command:`android-icons`,description:`Generate the Android launcher icon and splash logo of a NativeScript app from its one app icon.`,builder:t=>t.option(`resources`,{description:"The App_Resources directory. Default: `gjsify.androidIcons.resources`, else `appResourcesPath` of nativescript.config.ts, else App_Resources.",type:`string`}).option(`icon`,{description:"The scalable app icon SVG. Default: `gjsify.androidIcons.icon`, else the hicolor icon under data/icons (here or in a sibling package).",type:`string`}).option(`background`,{description:"Adaptive-icon background colour. Default: `gjsify.androidIcons.background`, else the metainfo light `<branding>` colour, else white.",type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the generated files are missing or the inputs changed.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).androidIcons??{},C=[`nativescript.config.ts`,`nativescript.config.js`].map(t=>zn(n,t)).find(t=>existsSync(t)),N=resolveResourcesName({flag:t.resources,configured:S.resources,nativescriptConfig:C===void 0?null:readFileSync(C,`utf8`)}),F=In(n,N),{icon:I,symbolic:H}=discoverIcon(n,t.icon??S.icon),W=resolveBackground({flag:t.background,configured:S.background,fromMetainfo:findMetainfoColor(I,n)}),q=new Uint8Array(readFileSync(I)),Y=H===null?null:new Uint8Array(readFileSync(H)),X=hashInputs({icon:q,symbolic:Y,background:W}),Z=planAndroidIcons({background:W,monochrome:Y!==null}),te=zn(F,aq);if(t.check===!0){let t=checkStamp(existsSync(te)?readFileSync(te,`utf8`):null,X,t=>existsSync(zn(F,...t.split(`/`))));return t.current?void 0:(process.stderr.write(`gjsify android-icons: ${N} ${t.reason}; run \`gjsify android-icons\` and commit it\n`),process.exit(1))}let ne=zn(F,...uq.split(`/`)),re=mkdtempSync(zn(tmpdir(),`gjsify-android-icons-`));try{let t=new Map([[`plain`,I]]);for(let n of[`round`,`foreground`]){let S=zn(re,`${n}.svg`);writeFileSync(S,wrapperSvg(n,q,W)),t.set(n,S)}if(Y!==null){let n=zn(re,`monochrome.svg`);writeFileSync(n,wrapperSvg(`monochrome`,Y,W)),t.set(`monochrome`,n)}for(let[n,S]of t){let t=Z.png.filter(t=>n===`plain`?t.kind===`legacy`||t.kind===`splash`:t.kind===n),C=await rasterizeSvg({svg:S,sizes:[...new Set(t.map(t=>t.size))],command:`gjsify android-icons`});for(let n of t){let t=zn(ne,n.path);mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,C.get(n.size))}}}finally{rmSync(re,{recursive:!0,force:!0})}for(let t of Z.text){let n=zn(ne,t.path);mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,t.content)}rmSync(zn(ne,`drawable`,`ic_launcher_foreground.xml`),{force:!0}),writeFileSync(te,`${JSON.stringify(buildStamp(X,Z,uq),null,2)}\n`),process.stdout.write(`gjsify android-icons: wrote ${Z.png.length+Z.text.length} files under ${Bn(n,ne).split(qn).join(`/`)} from ${Bn(n,I)}\n`)}catch(t){return process.stderr.write(`gjsify android-icons: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function globToRegExp(t){let n=t.split(`*`).map(t=>t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)).join(`.*`);return RegExp(`^${n}$`,`i`)}function isIgnored(t,n){return n.some(n=>{let S=globToRegExp(n);return S.test(t.name)||t.email!==``&&S.test(t.email)})}function parsePerson(t){let n=/^(.*?)\s*<([^>]*)>\s*$/.exec(t.trim());return n?{name:n[1].trim(),email:n[2].trim()}:{name:t.trim(),email:``}}function poLanguage(t){let n=On.basename(t);return/\.po$/i.test(n)?n.slice(0,-3):void 0}function bump(t,n){t.set(n,(t.get(n)??0)+1)}function rank(t){return[...t.entries()].sort(([t,n],[S,C])=>C-n||(t<S?-1:+(t>S))).map(([t])=>t)}function appendUnseen(t,n,S){let C=new Set(t);for(let N of n??[]){let n=N.trim();n&&!C.has(n)&&!S(n)&&(C.add(n),t.push(n))}}function buildCredits(t,n={}){let S=n.ignore??pq,C=n.overrides??{},N=C.exclude??[],excluded=t=>isIgnored({name:t,email:``},N),F=new Map,I=new Map,H=t.map(t=>{let n=new Set;for(let C of[t.author,...t.coAuthors])C.name&&!isIgnored(C,S)&&!excluded(C.name)&&n.add(C.name);let C=new Set,N=!1;for(let n of t.files){isTranslationFile(n)||(N=!0);let t=poLanguage(n);t&&C.add(t)}return{names:n,languages:C,touchesCode:N}}),W=new Map;for(let{names:t,languages:n}of H){if(t.size!==1||n.size!==1)continue;let[S]=t,[C]=n,N=W.get(S);N||W.set(S,N=new Set),N.add(C)}for(let{names:t,languages:n,touchesCode:S}of H){let C=t.size>1||n.size>1;for(let N of t){S&&bump(F,N);let t=W.get(N);for(let S of n){if(C&&t&&!t.has(S))continue;let n=I.get(S);n||I.set(S,n=new Map),bump(n,N)}}}let q={developers:rank(F),translators:{},supporters:[]},Y=C.excludeTranslators??{};for(let t of[...I.keys()].sort()){let n=[...Y[`*`]??[],...Y[t]??[]],S=rank(I.get(t)).filter(t=>!isIgnored({name:t,email:``},n));S.length&&(q.translators[t]=S)}appendUnseen(q.developers,C.developers,excluded);for(let t of Object.keys(C.translators??{}).sort()){let n=q.translators[t]??[];appendUnseen(n,C.translators[t],excluded),n.length&&(q.translators[t]=n)}return q.translators=Object.fromEntries(Object.entries(q.translators).sort(([t],[n])=>t<n?-1:1)),appendUnseen(q.supporters,C.supporters,excluded),q}function parseGitLog(t){let n=[];for(let S of t.split(hq)){if(!S.trim())continue;let[t=``,C=``,N=``,F=``]=S.split(mq);n.push({author:{name:t.trim(),email:C.trim()},coAuthors:N.split(gq).map(t=>t.trim()).filter(Boolean).map(parsePerson),files:F.split(`
|
|
1291
1291
|
`).map(t=>t.trim()).filter(Boolean)})}return n}function git(t,n,S){let C=spawnSync(`git`,[...n],{cwd:t,encoding:`utf8`,input:S,maxBuffer:1<<30});if(C.error)throw Error(`cannot run git: ${C.error.message}`);if(C.status!==0)throw Error(`git ${n.join(` `)} failed: ${String(C.stderr).trim()}`);return String(C.stdout)}function mapTrailers(t,n){let S=new Set;for(let t of n)for(let n of t.coAuthors)n.email&&S.add(`${n.name} <${n.email}>`);if(S.size===0)return;let C=[...S],N=git(t,[`check-mailmap`,`--stdin`],C.join(`
|
|
1292
1292
|
`)+`
|
|
1293
1293
|
`).split(`
|
|
1294
|
-
`).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,
|
|
1295
|
-
`}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var
|
|
1294
|
+
`).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,_q));return mapTrailers(t,n),n}function asStringList(t,n){if(!Array.isArray(t)||t.some(t=>typeof t!=`string`))throw Error(`${n} must be an array of strings`);return t}function parseOverrides(t,n=`overrides`){let S;try{S=JSON.parse(t)}catch(t){throw Error(`${n} is not valid JSON: ${t instanceof Error?t.message:String(t)}`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n} must be a JSON object`);let C=S,N=new Set([...vq,...yq]);for(let t of Object.keys(C))if(!N.has(t))throw Error(`${n} has an unknown key "${t}" (known: ${[...N].join(`, `)})`);let F={};for(let t of vq)C[t]!==void 0&&(F[t]=asStringList(C[t],`${n}.${t}`));for(let t of yq){let S=C[t];if(S===void 0)continue;if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n}.${t} must map a language to an array of names`);let N={};for(let[C,F]of Object.entries(S))N[C]=asStringList(F,`${n}.${t}.${C}`);F[t]=N}return F}function serializeCredits(t){return JSON.stringify(t,null,2)+`
|
|
1295
|
+
`}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var pq,mq,hq,gq,isTranslationFile,_q,vq,yq,bq=__esmMin(()=>{cv(),Xn(),pq=[`*[bot]`,`github-actions`,`Weblate`,`Weblate (bot)`,`Hosted Weblate`,`Weblate Translation Memory`,`LibreTranslate`,`Claude`,`*@anthropic.com`,`noreply-mt-*@weblate.org`,`hosted@weblate.org`,`*[bot]@users.noreply.github.com`],mq=``,hq=``,gq=``,isTranslationFile=t=>/\.pot?$/i.test(t),_q=[`-c`,`core.quotepath=off`,`log`,`--no-merges`,`--use-mailmap`,`--name-only`,`--format=${hq}%aN${mq}%aE${mq}%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x1d)${mq}`],vq=[`developers`,`supporters`,`exclude`],yq=[`translators`,`excludeTranslators`]}),xq,Sq,Cq,wq=__esmMin(()=>{vR(),bq(),af(),Xn(),xq=`credits.json`,Sq=`credits.overrides.json`,Cq={command:`credits`,description:`Write the project’s contributors (developers, translators per language) from the git history as JSON, names only.`,builder:t=>t.option(`output`,{alias:`o`,description:`File to write. Default: \`gjsify.credits.output\`, else ${xq}.`,type:`string`}).option(`overrides`,{description:`Hand-kept additions and exclusions. Default: \`gjsify.credits.overrides\`, else ${Sq} when it exists.`,type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the file on disk differs from what the history gives.`,type:`boolean`,default:!1}).option(`stdout`,{description:`Print the JSON instead of writing it.`,type:`boolean`,default:!1}).conflicts(`check`,`stdout`),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).credits??{},C=In(n,t.output??S.output??xq),N=t.overrides??S.overrides,F=In(n,N??Sq),I;if(existsSync(F))I=parseOverrides(readFileSync(F,`utf8`),N??Sq);else if(N!==void 0)throw Error(`cannot read the overrides file ${N}`);let H=buildCredits(readCommits(n),{ignore:S.ignore??pq,overrides:I}),W=serializeCredits(H);if(t.stdout===!0)process.stdout.write(W);else if(t.check===!0){let n=existsSync(C)?readFileSync(C,`utf8`):null;if(isStale(n,H))return process.stderr.write(`gjsify credits: ${t.output??S.output??xq} is ${n===null?`missing`:`stale`}; run \`gjsify credits\` and commit it\n`),process.exit(1)}else writeFileSync(C,W)}catch(t){return process.stderr.write(`gjsify credits: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}}),Tq,Eq=__esmMin(()=>{xh(),OB(),Tq={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??ph,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1296
1296
|
`)+`
|
|
1297
1297
|
`),process.exit(1);let F;try{F=await whoami(S,n)}catch(t){let n=t instanceof Error?t.message:String(t);return N?process.stdout.write(`${JSON.stringify({error:n,registry:C})}\n`):(process.stderr.write(`gjsify whoami: ${n}\n`),process.stderr.write(`Registry: ${C}\n`)),process.exit(1)}if(F.username&&F.username.length>0){N?process.stdout.write(`${JSON.stringify({username:F.username,registry:C})}\n`):(process.stdout.write(`Logged in as: ${F.username}\n`),process.stdout.write(`Registry: ${C}\n`));return}N?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:C})}\n`):process.stderr.write([`gjsify whoami: token appears dead or revoked (registry returned an empty whoami response).`,``,`Refresh via: npm login`,`Then verify: gjsify whoami`,``,`For the @gjsify scope, see AGENTS.md > "New @gjsify/* package: first-publish + Trusted Publisher bootstrap".`].join(`
|
|
1298
1298
|
`)+`
|
|
@@ -1301,12 +1301,12 @@ ${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
|
|
1301
1301
|
`)+`
|
|
1302
1302
|
`),S}function removeAuthToken(t){let n=userconfigNpmrcPath(),S=authTokenKey(t),C=readUserconfig(n);if(!C)return{path:n,removed:!1};let N=C.split(`
|
|
1303
1303
|
`),F=N.filter(t=>!t.replace(/\s+/g,``).startsWith(`${S}=`)),I=F.length!==N.length;return I&&writeUserconfig(n,F.join(`
|
|
1304
|
-
`)),{path:n,removed:I}}var
|
|
1305
|
-
Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,
|
|
1306
|
-
`)[0].slice(0,200)}var
|
|
1307
|
-
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=zn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??ph,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);return W||(ge.log(),ge.log(
|
|
1304
|
+
`)),{path:n,removed:I}}var Dq=__esmMin(()=>{af(),o_(),Xn()});async function runLogin(t){let n=await loadNpmrc(t.cwd??process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,{username:N,password:F}=await promptCredentials(t.username);if(!N)throw new LoginError(`gjsify login: a username is required.`);if(!F)throw new LoginError(`gjsify login: a password is required.`);let I=`Basic ${btoa(`${N}:${F}`)}`,H=`${C}-/user/org.couchdb.user:${encodeURIComponent(N)}`,W={_id:`org.couchdb.user:${N}`,name:N,password:F,type:`user`,roles:[],date:void 0};function authHeaders(t){let n={authorization:I,"content-type":`application/json`,accept:`*/*`};return t&&(n[`npm-otp`]=t),n}async function putUser(t,n){return fetch(`${H}${t}`,{method:`PUT`,headers:authHeaders(n),body:JSON.stringify(W)})}let q=typeof t.otp==`string`&&t.otp.length>0,Y=t.otp??readCachedOtp(C),X=await putUser(``,Y);if(X.status===401&&!q){let t=(X.headers.get(`www-authenticate`)??``).toLowerCase(),n=await X.clone().text().catch(()=>``);if(t.includes(`otp`)||/one-time pass/i.test(n)){if(clearCachedOtp(C),Y=await promptLine(`This operation requires a one-time password.
|
|
1305
|
+
Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,Oq,kq=__esmMin(()=>{_e(),xh(),OB(),Dq(),GK(),JK(),LoginError=class extends Error{constructor(t){super(t),this.name=`LoginError`}},Oq={command:`login`,description:"Log in to an npm registry (Node-free `npm login`). Prompts for username + password (hidden) and writes the token to ~/.npmrc. Use --otp for 2FA. Web-OAuth flow is not supported — this is npm's legacy credentials flow.",builder:t=>t.option(`registry`,{description:`Registry URL to log in to. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Associate the login with a scope (e.g. @gjsify) — resolves that scope's registry from .npmrc.`,type:`string`}).option(`username`,{description:`Username (prompted if omitted).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code (prompted on demand if omitted).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` JSON on success.",type:`boolean`}),handler:async t=>{try{let{username:n,registry:S,npmrcPath:C}=await runLogin({registry:t.registry,scope:t.scope,username:t.username,otp:t.otp});t.json?process.stdout.write(`${JSON.stringify({username:n,registry:S})}\n`):process.stdout.write(`Logged in as ${n} on ${S}\n(token written to ${C})\n`)}catch(t){if(t instanceof LoginError)return ge.error(t.message),process.exit(1);throw t}}}}),Aq,jq=__esmMin(()=>{xh(),OB(),Dq(),JK(),Aq={command:`logout`,description:"Log out of an npm registry (Node-free `npm logout`). Revokes the token on the registry (best-effort) and removes it from ~/.npmrc.",builder:t=>t.option(`registry`,{description:`Registry URL to log out of. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Log out of a scope's registry (e.g. @gjsify) — resolved from .npmrc.`,type:`string`}).option(`json`,{description:"Emit `{registry, revoked, removed}` JSON.",type:`boolean`}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,N=resolveAuthForUrl(`${C}-/whoami`,n),F=!1;if(N?.startsWith(`Bearer `)){let t=N.slice(7);try{F=(await fetch(`${C}-/user/token/${encodeURIComponent(t)}`,{method:`DELETE`,headers:{authorization:N,accept:`*/*`}})).ok}catch{}}clearCachedOtp(C);let{path:I,removed:H}=removeAuthToken(C);t.json?process.stdout.write(`${JSON.stringify({registry:C,revoked:F,removed:H})}\n`):H?process.stdout.write(`Logged out of ${C}${F?` (token revoked)`:``}\n(removed from ${I})\n`):process.stdout.write(`No token for ${C} found in ${I} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(t){let n=t,S=Mq[0];for(let t=0;t<8&&!existsSync(zn(n,...S));t++){let t=Hn(n);if(t===n)return[];n=t}let C=[];for(let t of Mq){let S=zn(n,...t);if(!existsSync(S))continue;let N;try{N=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let n of N){if(!n.isDirectory())continue;let N=zn(S,n.name),F=zn(N,`package.json`);if(existsSync(F))try{let S=JSON.parse(readFileSync(F,`utf8`));if(!S||typeof S.name!=`string`||S.name.length===0)continue;C.push({location:N,relativeLocation:zn(...t,n.name),name:S.name,version:typeof S.version==`string`?S.version:`0.0.0`,manifest:S,private:S.private===!0})}catch{}}}return C}function mergePublishables(t,n){let S=new Set(t.map(t=>t.name));return[...t,...discoverNonWorkspacePublishables(n).filter(t=>!S.has(t.name))]}var Mq,Nq=__esmMin(()=>{af(),Xn(),Mq=[[`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:[Pq]}]}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 Pq,Fq=__esmMin(()=>{Ch(),Pq=`createPackage`});function createTrustRequester(t){return async(n,S,C)=>{let doFetch=N=>{let F=buildHeaders(S,{npmrc:t.npmrc});F.accept=`application/json`,C!==void 0&&(F[`content-type`]=`application/json`),N&&(F[`npm-otp`]=N);let I={method:n,headers:F};return C!==void 0&&(I.body=JSON.stringify(C)),fetch(S,I)},N=await withOtpRetry(doFetch,t.otpProvider),F=await N.text().catch(()=>``),I;try{I=F?JSON.parse(F):void 0}catch{}return{status:N.status,json:I,text:F,headers:N.headers}}}function firstLine(t){return t.split(`
|
|
1306
|
+
`)[0].slice(0,200)}var Iq,Lq=__esmMin(()=>{_e(),cv(),af(),Xn(),xh(),KI(),Nq(),OB(),SK(),ZK(),Fq(),Iq={command:`trust [packages..]`,description:"Configure npm Trusted Publishers (OIDC/GitHub Actions) for publishable workspace packages so release.yml can publish without a token. Native — no `npm` needed. Incremental: skips already-configured packages.",builder:t=>t.positional(`packages`,{description:`Optional package-name globs to limit the sweep (default: all publishable workspaces).`,type:`string`,array:!0}).option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as `npm-otp`. Prompted on demand if omitted.",type:`string`}).option(`dry-run`,{description:`List what would be configured without writing anything.`,type:`boolean`,default:!1}).option(`force`,{description:`Re-POST the config even for packages already trusted for this repo+workflow.`,type:`boolean`,default:!1}).option(`list`,{description:`Only report each package’s current trust state; configure nothing.`,type:`boolean`,default:!1}).option(`private`,{description:`Include private workspaces (default false — private packages are not publishable).`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await loadNpmrc(n);if(!hasAnyCredential(S))return ge.error("gjsify trust: no npm token configured. Run `gjsify login` first."),process.exit(1);let C=t.registry??process.env.npm_config_registry??S.registry??ph;if(t[`dry-run`]!==!0){let t;try{t=await whoami(C,S)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`gjsify trust: npm auth check failed (${n}).\nYour ~/.npmrc token is dead or revoked — refresh it with \`npm login\`, then re-run.
|
|
1307
|
+
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=zn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??ph,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);return W||(ge.log(),ge.log(xK)),process.exit(1)}W||(ge.log(),ge.log(xK))}}}});function resolveRepoRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,encoding:`utf8`});if(S.status===0){let t=S.stdout.trim();if(t&&existsSync(t))return t}return t}function assertEveryPatternMatches(t,n){let S=n.filter(n=>{try{return discoverWorkspaces(t,{patterns:[n]}).length===0}catch{return!0}});if(S.length===0)return;let C=[`gjsify onboard: --packages matched no package directory (${S.length} of ${n.length} pattern(s)) under ${t}:`];for(let t of S)C.push(` ${JSON.stringify(t)}`);throw C.push(" Patterns are DIRECTORY globs resolved against the repo root, and only `*` is supported",` (one path segment). A matched directory needs a package.json with a "name".`),Error(C.join(`
|
|
1308
1308
|
`))}function collectOnboardPackages(t,n,S={}){let C=[],N=[],F=new Set,take=(t,n,S)=>{let I=0;for(let t of n)!t.name||F.has(t.name)||(F.add(t.name),N.push(t),I++);C.push({kind:t,patterns:S,count:I})};if(existsSync(zn(t,`package.json`)))try{take(`workspaces`,discoverWorkspaces(t,{includeRoot:!0}))}catch{}return S.patterns&&S.patterns.length>0&&take(`packages`,discoverWorkspaces(t,{patterns:[...S.patterns]}),S.patterns),take(`scanned-dirs`,mergePublishables([],n)),{packages:N,sources:C}}function describeSources(t){return t.filter(t=>t.count>0).map(t=>t.patterns?`${t.kind}(${t.patterns.join(`,`)})=${t.count}`:`${t.kind}=${t.count}`).join(` + `)}function declaredRepository(t){let n=t.manifest.repository,S=typeof n==`string`?n:n?.url;return typeof S!=`string`||S.length===0?null:parseRepoFromGitRemote(S)}function assertRepositoryAgreement(t,n){let S=n.toLowerCase(),C=t.map(t=>({ws:t,declared:declaredRepository(t)})).filter(t=>t.declared!==null&&t.declared.toLowerCase()!==S);if(C.length===0)return;let N=new Map;for(let{ws:t,declared:n}of C){let S=N.get(n)??[];S.push(t.name),N.set(n,S)}let F=[`gjsify onboard: ${C.length} selected package(s) declare a DIFFERENT repository than ${n}:`];for(let[t,n]of N){let S=n.slice(0,5).join(`, `),C=n.length>5?`, … (+${n.length-5} more)`:``;F.push(` ${t}: ${n.length} package(s) — ${S}${C}`)}throw F.push(` A Trusted Publisher scoped to the wrong repository points that package's OIDC exchange`,` at a workflow that does not publish it, which breaks the release this sweep protects.`,` Either exclude them (--exclude), select only what belongs here (--include), or point`,` --repository at the repo that actually publishes them.`),Error(F.join(`
|
|
1309
|
-
`))}var Lq=__esmMin(()=>{af(),cv(),KI(),Xn(),Mq(),Pq(),JI()});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,Rq),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??ph,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var Rq,RateLimitGate,zq=__esmMin(()=>{xh(),Pq(),Rq=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Bq,Vq,Hq=__esmMin(()=>{_e(),cv(),xh(),KI(),OB(),XK(),xK(),BK(),QK(),Iq(),Oq(),gB(),hv(),Lq(),Pq(),zq(),Bq=4,Vq={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:Bq}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??ph,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),S||(log(),log(bK)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,Wq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${Wq}`,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`&&Uq.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 Uq,Wq,Gq=__esmMin(()=>{Xn(),Uq=[`/usr/`,`/opt/`,`/snap/`],Wq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${Kq}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function isNextChannelVersion(t){return t?(parse(t)?.prerelease??[]).some(t=>t===`next`):!1}function nextChannelNotice(t){return t.requestedTag!==void 0||!isNextChannelVersion(t.currentVersion)?null:`Note: v${t.currentVersion} is a \`next\` prerelease; updating without --tag moves you to \`${qq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===Kq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===Kq&&typeof n.version==`string`)return n.version}n=Hn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var Kq,qq,Jq,Yq,Xq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),WI(),Kz(),Gq(),Xz(),eB(),jz(),Nz(),Kq=`@gjsify/cli`,qq=`latest`,Jq={command:`self-update`,description:`Update the installed ${Kq} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=zn(zn(n.prefix,`node_modules`,Kq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${Kq}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`);let I=t.tag??qq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${Kq}@${I} ...`);let W;try{W=await fetchPackument(Kq)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let q=resolveTag(W,I);if(!q)return ge.error(`Unknown dist-tag '${I}' on ${Kq}. Known tags: ${Object.keys(W[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${I}: v${q}`);let Y=N&&!hasBundlerEngineInstalled(n.prefix),X=Y&&!t.skipDeps&&!t.check;if(C===q&&!t.force&&!X){ge.log(`Already up to date (v${q}).`),Y&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(X&&C===q&&!t.force&&ge.log(`@gjsify/cli is at v${q} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${q}`:`Install required: → v${q}`),process.exit(1);let Z=!t.skipDeps,te=Z?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${Kq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${Kq}@${q}`],verbose:!1,skipDeps:!Z,progress:ne})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Z&&await installGjsEnginePackages(n.prefix,q,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let re=linkGlobalBins([Kq],n);if(re.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of re)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:Yq,binDir:n.binDir,resolvedBin:resolveBinOnPath(Yq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${Kq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${Kq} to v${q}.`),Z?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},Yq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1309
|
+
`))}var Rq=__esmMin(()=>{af(),cv(),KI(),Xn(),Nq(),Fq(),JI()});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,zq),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??ph,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var zq,RateLimitGate,Bq=__esmMin(()=>{xh(),Fq(),zq=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Vq,Hq,Uq=__esmMin(()=>{_e(),cv(),xh(),KI(),OB(),ZK(),SK(),VK(),$K(),Lq(),kq(),gB(),hv(),Rq(),Fq(),Bq(),Vq=4,Hq={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:Vq}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??ph,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),S||(log(),log(xK)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,Gq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${Gq}`,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`&&Wq.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 Wq,Gq,Kq=__esmMin(()=>{Xn(),Wq=[`/usr/`,`/opt/`,`/snap/`],Gq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${qq}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function isNextChannelVersion(t){return t?(parse(t)?.prerelease??[]).some(t=>t===`next`):!1}function nextChannelNotice(t){return t.requestedTag!==void 0||!isNextChannelVersion(t.currentVersion)?null:`Note: v${t.currentVersion} is a \`next\` prerelease; updating without --tag moves you to \`${Jq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===qq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===qq&&typeof n.version==`string`)return n.version}n=Hn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var qq,Jq,Yq,Xq,Zq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),WI(),Kz(),Kq(),Xz(),eB(),jz(),Nz(),qq=`@gjsify/cli`,Jq=`latest`,Yq={command:`self-update`,description:`Update the installed ${qq} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=zn(zn(n.prefix,`node_modules`,qq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${qq}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`);let I=t.tag??Jq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${qq}@${I} ...`);let W;try{W=await fetchPackument(qq)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let q=resolveTag(W,I);if(!q)return ge.error(`Unknown dist-tag '${I}' on ${qq}. Known tags: ${Object.keys(W[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${I}: v${q}`);let Y=N&&!hasBundlerEngineInstalled(n.prefix),X=Y&&!t.skipDeps&&!t.check;if(C===q&&!t.force&&!X){ge.log(`Already up to date (v${q}).`),Y&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(X&&C===q&&!t.force&&ge.log(`@gjsify/cli is at v${q} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${q}`:`Install required: → v${q}`),process.exit(1);let Z=!t.skipDeps,te=Z?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${qq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${qq}@${q}`],verbose:!1,skipDeps:!Z,progress:ne})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Z&&await installGjsEnginePackages(n.prefix,q,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let re=linkGlobalBins([qq],n);if(re.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of re)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:Xq,binDir:n.binDir,resolvedBin:resolveBinOnPath(Xq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${qq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${qq} to v${q}.`),Z?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},Xq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1310
1310
|
/**
|
|
1311
1311
|
* gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
|
|
1312
1312
|
* on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
|
|
@@ -1882,28 +1882,28 @@ async function main() {
|
|
|
1882
1882
|
}
|
|
1883
1883
|
|
|
1884
1884
|
await main();
|
|
1885
|
-
`}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var
|
|
1886
|
-
`).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var
|
|
1885
|
+
`}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var Qq,$q,eJ=__esmMin(()=>{_e(),af(),Xn(),Qq=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,$q={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:t=>t.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:t=>{let n=In(process.cwd(),t.output);if(existsSync(n)&&!t.force)return ge.error(`${t.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let S=In(process.cwd(),`package.json`),C=null;if(existsSync(S))try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{}let N=t.target??C?.name;if(!N)return ge.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let F=t[`bin-name`]??pickDefaultBinName(C,N),I=t[`bootstrap-url`]??Qq;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`)}}}),tJ,nJ=__esmMin(()=>{_e(),af(),_z(),Xz(),jz(),Nz(),tJ={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:t=>t.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async t=>{let n=t.global?defaultGlobalLayout():null,S=n?n.prefix:process.cwd();if(!existsSync(`${S}/node_modules`)){ge.log(`gjsify prune: nothing installed at ${S}`);return}let C=resolveHostPlatform({env:{...t.os?{npm_config_os:t.os}:{},...t.cpu?{npm_config_cpu:t.cpu}:{},...t.libc?{npm_config_libc:t.libc}:{}}}),N=await acquireInstallLock(S,{}),F;try{F=executePrune(planPrune({prefix:S,target:C}),{dryRun:t.dryRun})}finally{N.release()}if(ge.log(formatPruneReport(F,{dryRun:t.dryRun,verbose:t.verbose})),F.failed.length>0)return process.exit(1)}}});function isInside(t,n){let S=Bn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${qn}`)&&!Rn(S)}function findBinShimsForPackage(t,n,S){if(!existsSync(t))return[];let C=[],N;try{N=readdirSync(t)}catch{return[]}for(let F of N){let N=zn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
|
|
1886
|
+
`).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var rJ,iJ=__esmMin(()=>{_e(),af(),Xn(),Xz(),rJ={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:t=>t.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:t=>{if(!t.global)return ge.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let n=defaultGlobalLayout(),S=t[`dry-run`]??!1,C=t.verbose??!1,N=`gjsify uninstall${S?` (dry-run)`:``} --global`;ge.log(`${N} ← ${n.prefix}`),ge.log(`${` `.repeat(N.length)} bins ← ${n.binDir}`);let F=!1;for(let N of t.packages){let t=specToPackageName(N),I=zn(n.prefix,`node_modules`,t);if(!existsSync(I)){ge.warn(` ✗ ${t} — not installed at ${I}`);continue}let H=findBinShimsForPackage(n.binDir,I,C);if(S){ge.log(` • would remove ${I}`);for(let t of H)ge.log(` • would remove ${t}`)}else{rmSync(I,{recursive:!0,force:!0}),ge.log(` • removed ${I}`);for(let t of H)unlinkSync(t),ge.log(` • removed ${t}`)}F=!0}F||(ge.error(`
|
|
1887
1887
|
No packages removed.`),process.exit(1))}}});function globToRegexSource(t){let n=``,S=0;for(;S<t.length;){let C=t[S];if(C===`*`&&t[S+1]===`*`&&(S===0||t[S-1]===`/`)){if(S+2===t.length){n+=`.*`,S+=2;continue}if(t[S+2]===`/`){n+=`(?:.*/)?`,S+=3;continue}}if(C===`*`)for(n+=`[^/]*`;t[S+1]===`*`;)S++;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=findClassEnd(t,S);if(C===-1)n+=`\\[`;else{let N=t.slice(S+1,C),F=!1;(N.startsWith(`!`)||N.startsWith(`^`))&&(F=!0,N=N.slice(1)),N=N.replace(/\]/g,`\\]`),n+=`[${F?`^/`:``}${N}]`,S=C}}else C===`\\`&&S+1<t.length?(S++,n+=escapeRegex(t[S])):n+=escapeRegex(C);S++}return n}function findClassEnd(t,n){let S=n+1;for((t[S]===`!`||t[S]===`^`)&&S++,t[S]===`]`&&S++;S<t.length;S++)if(t[S]===`]`)return S;return-1}function escapeRegex(t){return/[.+^${}()|[\]\\*?]/.test(t)?`\\${t}`:t}function parseLine(t){let n=t.replace(/\r$/,``);if(n=n.replace(/(?<!\\)\s+$/,``),n===``||n.startsWith(`#`))return null;let S=!1;n.startsWith(`!`)?(S=!0,n=n.slice(1)):(n.startsWith(`\\!`)||n.startsWith(`\\#`))&&(n=n.slice(1));let C=!1;if(n.endsWith(`/`)&&!n.endsWith(`\\/`)&&(C=!0,n=n.slice(0,-1)),n===``)return null;let N=n.includes(`/`);n.startsWith(`/`)&&(n=n.slice(1));let F=globToRegexSource(n);return{re:RegExp(`^${N?``:`(?:.*/)?`}${F}$`),negate:S,dirOnly:C}}function compileGitignore(t,n){let S=[];for(let n of t){let t=parseLine(n);t&&S.push(t)}let relOf=t=>{let S=Bn(n,t);return S===``||S===`..`||S.startsWith(`..${qn}`)||Rn(S)?null:qn===`/`?S:S.split(qn).join(`/`)},decide=(t,n)=>{for(let C=S.length-1;C>=0;C--){let N=S[C];if(!(N.dirOnly&&!n)&&N.re.test(t))return N.negate?`whitelist`:`ignore`}return null};return{base:n,matched(t,n){if(S.length===0)return null;let C=relOf(t);return C===null?null:decide(C,n)},matchedPathOrAnyParents(t,n){if(S.length===0)return null;let C=relOf(t);if(C===null)return null;let N=n;for(;;){let t=decide(C,N);if(t!==null)return t;let n=C.lastIndexOf(`/`);if(n===-1)return null;C=C.slice(0,n),N=!0}}}}function readGitignoreFile(t,n=Hn(t)){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}return compileGitignore(S.split(`
|
|
1888
|
-
`),n)}var
|
|
1889
|
-
`,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,
|
|
1890
|
-
`);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),
|
|
1891
|
-
[gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return
|
|
1892
|
-
Select upgrades: comma- or space-separated indices, `+
|
|
1888
|
+
`),n)}var aJ=__esmMin(()=>{af(),Xn()});function externalParserFor(t,n=!1){if(cJ.has(t))return null;let S=Wn(t).slice(1),C=sJ[t]??(S?oJ[S]:void 0)??null;return C===`svelte`&&!n?null:C}function scanForNativeSkips(t,n=process.cwd(),S={}){let C=[],N=0,F=t.filter(t=>t.startsWith(`!`)).map(t=>t.slice(1)),I=[],H=readGitignoreFile(zn(n,`.prettierignore`));H&&I.push(H),F.length&&I.push(compileGitignore(F,n));let globallyIgnored=(t,n,S)=>I.some(C=>(S?C.matchedPathOrAnyParents(t,n):C.matched(t,n))===`ignore`),W=S.configPath?In(n,S.configPath):null,q=loadScope(W??discoverConfig(n)),Y=W===null,scopeFor=t=>Y?nearestScope(t,q):q,expandBraces=t=>{let n=/\{([^{}]*)\}/.exec(t);return n?n[1].split(`,`).flatMap(S=>expandBraces(t.slice(0,n.index)+S+t.slice(n.index+n[0].length))):[t]},X=[],Z=new Set;for(let S of t){if(S.startsWith(`!`))continue;let t=In(n,S);if(/[*?[{]/.test(S)&&!existsSync(t))for(let t of expandBraces(S))X.push(RegExp(`^${globToRegexSource(t.includes(`/`)?t:`**/${t}`)}$`));else Z.add(t)}(X.length||Z.size===0)&&Z.add(In(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Un(t),n?.svelte)&&C.push(t))},te=[];for(let t of Z){let n;try{n=statSync(t)}catch{continue}globallyIgnored(t,n.isDirectory(),!0)||(n.isDirectory()?te.push(t):n.isFile()&&record(t,scopeFor(Hn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Bn(n,t).split(qn).join(`/`);return X.some(t=>t.test(S))},ne=new Set,walk=(t,n,S)=>{if(ne.has(t))return;ne.add(t);let C=readGitignoreFile(zn(t,`.gitignore`)),N=C?[C,...n]:n;Y&&t!==S?.dir&&(S=scopeAt(t)??S);let F;try{F=readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of F){let C=zn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(lJ.has(n.name)||n.name===`node_modules`)||globallyIgnored(C,F,!1)||gitIgnored(N,C,F)||(F?walk(C,N,S):matchesGlob(C)&&record(C,S))}},re=te.every(t=>repoRootOf(t)!==null);for(let t of te)walk(t,parentGitignores(t,re?repoRootOf(t):null,re),scopeFor(t));return{skipped:C,total:N}}function gitIgnored(t,n,S){for(let C of t){let t=C.matched(n,S);if(t!==null)return t===`ignore`}return!1}function parentGitignores(t,n,S){if(S&&n===null)return[];let C=[];for(let S=t;S!==n;){let t=Hn(S);if(t===S)break;S=t;let n=readGitignoreFile(zn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(zn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=Hn(n)){if(existsSync(zn(n,`.git`))||existsSync(zn(n,`.jj`)))return n;if(Hn(n)===n)return null}}function configIn(t){for(let n of uJ){let S=zn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=In(t);;n=Hn(n)){let t=configIn(n);if(t)return t;if(Hn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=Hn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(Hn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=Hn(t),S={};try{S=parseJsonc(readFileSync(t,`utf-8`))}catch{S={}}let C=Array.isArray(S.ignorePatterns)?S.ignorePatterns.filter(t=>typeof t==`string`):[];return{dir:n,ignore:C.length?compileGitignore(C,n):null,svelte:S.svelte!==void 0&&S.svelte!==null&&S.svelte!==!1}}function parseJsonc(t){let pass=(t,n)=>{let S=``;for(let C=0;C<t.length;){if(t[C]===`"`){let n=C+1;for(;n<t.length&&t[n]!==`"`;)n+=t[n]===`\\`?2:1;S+=t.slice(C,n+1),C=n+1;continue}let N=n(t,C);N>0?C+=N:S+=t[C++]}return S},n=pass(t,(t,n)=>{if(t.startsWith(`//`,n)){let S=t.indexOf(`
|
|
1889
|
+
`,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,oJ,sJ,cJ,lJ,uJ,dJ=__esmMin(()=>{af(),Xn(),aJ(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),oJ={...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`},sJ={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},cJ=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`]),lJ=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),uJ=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=In(t,S);if(existsSync(N)&&!n){ge.log(`[gjsify format] ${S} exists at ${N} — pass --force to overwrite.`);return}writeFileSync(N,C,`utf-8`),ge.log(`[gjsify format] wrote ${N}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ge.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var fJ,pJ=__esmMin(()=>{_e(),af(),Xn(),CV(),dJ(),fJ={command:`format [paths..]`,description:`Format source files via oxfmt (Markdown/YAML/HTML/Vue need the napi build).`,builder:t=>t.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();if(t.init){handleInit({cwd:n,force:t.force??!1});return}let S=t.paths?.length?t.paths:[`.`],C=[];t.check?C.push(`--check`):t.write===!1?C.push(`--list-different`):C.push(`--write`);let N=t.configPath??findOxfmtConfig(n)??void 0;if(N&&C.push(`--config`,In(N)),C.push(...S),t.check&&await shouldUseNativeOxfmt()){let t=scanForNativeSkips(S,n,{configPath:N});if(t.skipped.length>0){let S=t.skipped.map(t=>` ${Bn(n,t)||t}`).join(`
|
|
1890
|
+
`);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),mJ,hJ=__esmMin(()=>{Xn(),CV(),mJ={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:t=>t.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=[];t.fix&&C.push(`--fix`);let N=t.configPath??findOxlintConfig(n)??void 0;N&&C.push(`--config`,In(N)),C.push(...S);try{setOxcExitCode(await runOxlint(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),gJ,_J=__esmMin(()=>{Xn(),CV(),gJ={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:t=>t.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=t.verbose??!1,N=t.write!==!1;try{let F=[N?`--write`:`--list-different`],I=t.configPath??findOxfmtConfig(n)??void 0;I&&F.push(`--config`,In(I)),F.push(...S);let H=await runOxfmt(F,{cwd:n,verbose:C}),W=[];N&&W.push(`--fix`);let q=t.configPath??findOxlintConfig(n)??void 0;q&&W.push(`--config`,In(q)),W.push(...S);let Y=await runOxlint(W,{cwd:n,verbose:C});setOxcExitCode(H||Y)}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}});function createInterface(t,n){return typeof t==`object`&&t&&!(`read`in t&&typeof t.read==`function`)?new Interface(t):new Interface({input:t,output:n})}var Interface,vJ=__esmMin(()=>{Xd(),Interface=class extends Interface$1{question(t,n){return new Promise(n=>{super.question(t,n)})}}});function semverGt(t,n){try{return compare(t,n)===1}catch{return!1}}function groupByDependency(t){let n=new Map;for(let S of t){let t=n.get(S.name);t||(t={name:S.name,occurrences:[],declaredRanges:new Set,dominantRange:S.currentRange,highestVersion:S.currentVersion},n.set(S.name,t)),t.occurrences.push(S),t.declaredRanges.add(S.currentRange),S.currentVersion&&(!t.highestVersion||semverGt(S.currentVersion,t.highestVersion))&&(t.highestVersion=S.currentVersion)}for(let t of n.values()){let n=new Map;for(let S of t.occurrences)n.set(S.currentRange,(n.get(S.currentRange)??0)+1);let S=t.occurrences[0].currentRange,C=-1,N=null;for(let[t,F]of n.entries()){let n=parse(t.replace(/^[\^~>=<]+/,``))?.version??null;(F>C||F===C&&n&&N&&semverGt(n,N)||F===C&&t<S)&&(S=t,C=F,N=n)}t.dominantRange=S}return[...n.values()].sort((t,n)=>t.name.localeCompare(n.name))}function isInconsistent(t){return t.declaredRanges.size>1}function findInconsistencies(t){return t.filter(isInconsistent)}var yJ=__esmMin(()=>{WI()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`[gjsify upgrade] no package.json at ${S}`);let C=JSON.parse(readFileSync(S,`utf-8`));return{root:t,workspaces:[{name:C.name??`<root>`,location:t,relativeLocation:`.`,version:C.version??`0.0.0`,manifest:C,private:C.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(t,n,S){let C=n?.split(`,`).map(t=>t.trim()).filter(Boolean),N=S?.split(`,`).map(t=>t.trim()).filter(Boolean);return(!C||C.length===0)&&(!N||N.length===0)?t:filterWorkspaces(t,{include:C,exclude:N})}function parseFilterList(t){return t?t.split(`,`).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(t,n){let S=[];for(let C of t)for(let t of collectFromWorkspace(C,n))S.push(t);return S}function collectFromWorkspace(t,n){let S=[],C=t.manifest;for(let N of xJ){let F=C[N];if(!(!F||typeof F!=`object`))for(let[C,I]of Object.entries(F)){if(typeof I!=`string`||n.length&&!n.some(t=>C.toLowerCase().includes(t))||isDistTagSpec(I)||I.startsWith(`workspace:`)||I.startsWith(`file:`)||I.startsWith(`link:`)||I.startsWith(`git+`)||I.startsWith(`git:`)||I.startsWith(`http:`)||I.startsWith(`https:`)||I.startsWith(`npm:`)||I.startsWith(`portal:`))continue;let{prefix:F,version:H}=splitRange(I);S.push({workspace:t.name,workspaceLocation:t.location,name:C,field:N,currentRange:I,currentVersion:H,prefix:F})}}return S}function isDistTagSpec(t){let n=t.trim();return SJ.has(n)||!/^[A-Za-z]/.test(n)||/^v\d/.test(n)||/^v[xX*]/.test(n)?!1:/^[A-Za-z][\w.-]*$/.test(n)}function splitRange(t){let n=t.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!n)return{prefix:``,version:null};let S=n[1]??``,C=n[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:S,version:(C?parse(C):null)?.version??null}}function reportInexactRanges(t){let n=t.map(t=>({name:t.name,loose:t.occurrences.filter(t=>t.prefix!==``)})).filter(t=>t.loose.length>0);if(n.length===0)return 0;let S=n.reduce((t,n)=>t+n.loose.length,0);ge.error(`gjsify upgrade --check --exact: FAIL. ${S} declaration(s) across ${n.length} dep(s) carry a range operator:\n`);for(let t of n){let n=new Map;for(let S of t.loose){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${CJ.bold}${t.name}${CJ.reset}`);for(let[t,S]of n.entries()){let n=S.length>6?`${S.slice(0,6).join(`, `)} … +${S.length-6}`:S.join(`, `);ge.error(` ${t.padEnd(16)} — ${n}`)}}return S}function checkLockfileRangeViolations(t,n){let S=zn(n,`gjsify-lock.json`);if(!existsSync(S))return 0;let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{return 0}if(!C.packages)return 0;let N=new Map;for(let n of t){let t=N.get(n.name)??new Set;for(let S of n.occurrences)t.add(S.currentRange);N.set(n.name,t)}let F=0;for(let[t,n]of Object.entries(C.packages)){if(!n.version)continue;let S=t.split(`node_modules/`);if(S.length!==2)continue;let C=S[1],I=N.get(C);if(!I||I.size===0)continue;let H=!1;for(let t of I)try{if(n.version&&satisfies(n.version,t)){H=!0;break}}catch{}H||(ge.error(` ${C}: lockfile has ${n.version}, but declared ranges are ${[...I].join(`, `)}`),F++)}return F>0&&ge.error(`gjsify upgrade --check: FAIL. ${F} lockfile entr${F===1?`y`:`ies`} violate declared ranges:\n`),F}function runCheckMode(t,n=!1,S=process.cwd()){checkLockfileRangeViolations(t,S);let C=n?reportInexactRanges(t):0,N=findInconsistencies(t);if(N.length===0&&C>0)return ge.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ge.log(`gjsify upgrade --check: OK. ${t.length} dep(s) consistently declared across workspaces`+(n?`, every declaration pinned exactly.`:`.`));return}ge.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let t of N){let n=new Map;for(let S of t.occurrences){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${CJ.bold}${t.name}${CJ.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(` ${CJ.bold}${n.name}${CJ.reset} ${[...n.declaredRanges].join(`, `)}`);return ge.error("\nThose ranges name no single version. Edit them by hand, or resolve one with `--latest`."),process.exit(1)}function runAlignMode(t,n){let S=n.exact??!1,C=alignTargets(t,S);if(C.length===0){ge.log(`gjsify upgrade --align: nothing to do. ${t.length} dep(s) already consistent`+(S?`, every declaration pinned exactly.`:`.`));return}let N=[],F=[];for(let t of C){if(!t.highestVersion){F.push(t);continue}let n=t.occurrences.find(n=>n.currentRange===t.dominantRange)?.prefix||`^`;N.push({...t,latestVersion:t.highestVersion,diff:`none`,occurrences:t.occurrences.map(t=>({...t,prefix:n}))})}if(N.length>0){ge.log(S?`gjsify upgrade --align --exact: pinning ${N.length} dep(s) to their highest declared version, without a range operator:\n`:`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let t of N){let n=t.occurrences[0]?.prefix??`^`;ge.log(` ${t.name.padEnd(28)} ranges: ${[...t.declaredRanges].join(`, `)} → ${targetRange(n,t.latestVersion,S)}`)}if(n.dryRun)ge.log(`
|
|
1891
|
+
[gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return CJ.red;case`minor`:return CJ.yellow;case`patch`:return CJ.green;case`prerelease`:return CJ.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)+CJ.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+CJ.reset;ge.log(I),ge.log(` `.repeat(F+2)+CJ.dim+`─`.repeat(n+S+C+N+16)+CJ.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${CJ.magenta}⚠ ${CJ.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+CJ.dim+`${H.occurrences.length}`.padEnd(S)+CJ.reset+` `+CJ.dim+renderDeclaredCell(H).padEnd(C)+CJ.reset+` `+Y+H.latestVersion.padEnd(N)+CJ.reset+` `+Y+H.diff+CJ.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${CJ.magenta}⚠${CJ.reset} ${H} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(t){return renderDeclaredCell(t).length}function renderDeclaredCell(t){if(t.declaredRanges.size===1)return[...t.declaredRanges][0];let n=[...t.declaredRanges].sort().join(`, `);return n.length<=32?n:n.slice(0,29)+`…`}function printChangePlan(t,n=!1){for(let S of t)for(let t of S.occurrences)ge.log(` ${t.workspace.padEnd(38)} ${S.name.padEnd(28)} ${t.currentRange.padEnd(12)} → ${targetRange(t.prefix,S.latestVersion,n)}`)}async function promptSelection(t){if(!process.stdin.isTTY)return ge.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let n=createInterface({input:process.stdin,output:process.stdout});try{ge.log(`
|
|
1892
|
+
Select upgrades: comma- or space-separated indices, `+CJ.bold+`a`+CJ.reset+` for all, ranges like `+CJ.bold+`1-3`+CJ.reset+`, or `+CJ.bold+`ENTER`+CJ.reset+` to skip:`);let S=(await n.question(`> `)).trim();if(!S)return[];if(S.toLowerCase()===`a`||S.toLowerCase()===`all`)return[...t];let C=new Set;for(let t of S.split(/[\s,]+/).filter(Boolean)){let n=t.match(/^(\d+)-(\d+)$/);if(n){let t=Number(n[1]),S=Number(n[2]);for(let n=Math.min(t,S);n<=Math.max(t,S);n++)C.add(n-1)}else/^\d+$/.test(t)&&C.add(Number(t)-1)}return[...C].filter(n=>n>=0&&n<t.length).map(n=>t[n])}finally{n.close()}}function targetRange(t,n,S){return S?n:`${t}${n}`}function applyToFiles(t,n=!1){let S=new Map;for(let n of t)for(let t of n.occurrences){let C=S.get(t.workspaceLocation)??[];C.push({...n,occurrences:[t]}),S.set(t.workspaceLocation,C)}let C=0;for(let[t,N]of S.entries()){let S=zn(t,`package.json`),F=readFileSync(S,`utf-8`),I=JSON.parse(F),H=!1,W=[];for(let t of N){let S=t.occurrences[0],C=I[S.field];if(!C)continue;let N=targetRange(S.prefix,t.latestVersion,n);C[t.name]!==N&&(C[t.name]=N,H=!0,W.push(t.name))}if(H){let t=detectIndent(F);writeFileSync(S,keepUntouchedLines(F,JSON.stringify(I,null,t)+(F.endsWith(`
|
|
1893
1893
|
`)?`
|
|
1894
1894
|
`:``),W),`utf-8`),C++}}return C}function keepUntouchedLines(t,n,S){let C=t.split(`
|
|
1895
1895
|
`),N=n.split(`
|
|
1896
1896
|
`);return C.length===N.length?N.map((t,n)=>S.some(n=>t.includes(`"${n}"`))?t:C[n]).join(`
|
|
1897
|
-
`):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var
|
|
1897
|
+
`):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var bJ,xJ,SJ,CJ,wJ=__esmMin(()=>{_e(),af(),Xn(),o_(),vJ(),WI(),xh(),KI(),JI(),yJ(),bJ={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:t=>t.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:"Offline repair mode: find deps declared at multiple ranges across the workspace and align them to the highest. With `--exact`, also drop the range operator from declarations that already agree. No registry calls.",type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one; with `--align`, repairs exactly that. Pair with `--filter` — a repository-wide exactness run touches every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async t=>{let n=discoverContext(In(t.cwd??process.cwd())),S=applyWorkspaceFilter(n.workspaces,t.workspace,t.excludeWorkspace);if(S.length===0){ge.log(`[gjsify upgrade] no matching workspaces.`);return}let C=collectAllDeclarations(S,parseFilterList(t.filter));if(C.length===0){ge.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let N=groupByDependency(C);if(t.check)return runCheckMode(N,t.exact);if(t.align)return runAlignMode(N,t);let F=await loadNpmrcLight(n.root),I=t.latest?`latest`:t.minor?`minor`:t.patch?`patch`:`interactive`;ge.log(`[gjsify upgrade] checking ${N.length} unique deps across ${S.length} workspace(s) against ${F.registry}…`);let H=await resolveCandidateGroups(N,F,t.verbose??!1,I);if(H.length===0){ge.log(`✅ all dependencies are up to date`);let t=findInconsistencies(N);t.length>0&&ge.log(`\n⚠ ${t.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(H);let W;if(I===`interactive`&&!t.yes?W=await promptSelection(H):(t.yes&&I===`interactive`&&ge.log(`[gjsify upgrade] -y / --yes: selecting all`),W=H),W.length===0){ge.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(t.dryRun){let n=uniqueLocations(W).length;ge.log(`[gjsify upgrade] --dry-run: would update ${W.length} deps across ${n} package.json file(s).`),printChangePlan(W,t.exact);return}let q=applyToFiles(W,t.exact);ge.log(`✏️ updated ${W.length} dep(s) across ${q} package.json file(s). Run \`gjsify install\` to apply.`)}},xJ=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],SJ=new Set([`x`,`X`,`*`,``]),CJ={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function unscannableBarrelPaths(t,n){let S=[];for(let C of n){let n=In(t,C);try{(await stat$1(n)).isDirectory()||S.push(`${n} is not a directory`)}catch(t){S.push(`${n}: ${t.message}`)}}return S}async function generateBarrels(t){let n=t.singleQuotes?`'`:`"`,S=t.noSemicolon?``:`;`,C=t.extension===`none`?``:`.${t.extension}`,N=0;for(let F of t.paths){let I=In(t.baseDir,F),H=Un(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>EJ.test(t.name)).filter(t=>t.name!==`index.ts`).filter(n=>!t.exclude.some(t=>t.test(n.name))).sort((t,n)=>t.name.localeCompare(n.name))}catch(n){t.verbose&&ge.error(`[gjsify barrels] skip ${I}: ${n.message}`);continue}let q=W.map(t=>{let N=Un(t.name,Wn(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
|
|
1898
1898
|
`)}\n`:`export {};
|
|
1899
|
-
`,X=`${t.header}\n\n${Y}`,Z=zn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var
|
|
1900
|
-
`).map(t=>t.trim()).filter(Boolean)}var
|
|
1899
|
+
`,X=`${t.header}\n\n${Y}`,Z=zn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var TJ,EJ,DJ=__esmMin(()=>{_e(),Vd(),Xn(),TJ=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],EJ=/\.(ts|tsx|mts|cts)$/}),OJ,kJ=__esmMin(()=>{_e(),DJ(),OJ={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:[...TJ],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)}}}),AJ,jJ=__esmMin(()=>{_e(),Xl(),Xn(),cr(),_L(),fL(),af(),QG(),WR(),JI(),hv(),Iz(),AJ={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:t=>t.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async t=>{let n=(t._??[]).slice(1).map(String),S=t.tscArgs??[],C=process.cwd(),N=tscArgsUnderLink(n.length>0?n:S,existsSync(devLinkPath(devLinkRoot(C)))),F=[pathToFileURL(`${findWorkspaceRoot(C)??C}/__gjsify_tsc__.js`).href,import.meta.url],I;for(let t of F)try{I=createRequire(t).resolve(`@gjsify/tsc/bundle`);break}catch{}let H;for(let t of F)try{H=zn(Hn(createRequire(t).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!I&&!H)return ge.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ge.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let W=buildNativeEnv(detectNativePackages(C)),q={...process.env,...W},runNodeTsc=async()=>{let t=nodeBinary();if(!(t.includes(`/`)||t.includes(`\\`)?existsSync(t):isOnPath(t)))return ge.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${t}\` cannot be run, so upstream \`typescript\` cannot run either.`),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ge.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((n,S)=>{spawnToCompletion(t,[H,...N],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(S)})}catch(t){let n=t;return n.code===`ENOENT`?(ge.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ge.error(`gjsify tsc (node typescript): ${n.message}`),forceExit(1)}};if(I)try{await new Promise((t,n)=>{spawnToCompletion(`gjs`,[`-m`,I,...N],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(n)})}catch(t){let n=t;return n.code===`ENOENT`&&H?await runNodeTsc():(n.code===`ENOENT`?(ge.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ge.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ge.error(`gjsify tsc: ${n.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(t){return t.split(`
|
|
1900
|
+
`).map(t=>t.trim()).filter(Boolean)}var MJ=__esmMin(()=>{af()});function isResolvableScript(t){return LJ.test(t)&&!NJ.some(n=>n.test(t))&&!IJ.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))PJ.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)PJ.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 NJ)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 IJ){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=>FJ.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 NJ,PJ,FJ,IJ,LJ,RJ=__esmMin(()=>{KI(),NJ=[/^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$/],PJ=[/\.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$/],FJ=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],IJ=[{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`}],LJ=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
|
|
1901
1901
|
`).filter(t=>!S.test(t)).join(`
|
|
1902
1902
|
`)}function scriptNamePattern(t){let n=On.basename(t),S=/^(.*?)(\.d)?\.[mc]?[jt]sx?$/.exec(n),C=S?`${escapeRe(S[1])}(\\.d)?\\.[mc]?[jt]sx?\\b`:`${escapeRe(n)}\\b`;return RegExp(`(^|[^\\w.-])${C}`)}function gatedJobs(t){let n=new Map,S=new Set;for(let{job:C,text:N}of t){if(!C)continue;n.has(C)||n.set(C,[]);let t=/^ {4}needs:\s*\[(.*)\]/.exec(N)??/^ {4}needs:\s*([A-Za-z0-9_-]+)\s*$/.exec(N);t&&n.set(C,t[1].split(`,`).map(t=>t.trim()).filter(Boolean)),(/needs\.changes\b/.test(N)||/^ {4}needs:\s*$/.test(N))&&S.add(C)}let C=new Set([`changes`,...S]),N=!0;for(;N;){N=!1;for(let[t,S]of n)!C.has(t)&&S.some(t=>C.has(t))&&(C.add(t),N=!0)}return C.delete(`changes`),C}function workflowLines(t){let n=t.split(`
|
|
1903
|
-
`),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===
|
|
1903
|
+
`),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===zJ||S===BJ||n.set(S,stripCommentLines(S,C));let S=t.get(zJ),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(BJ);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(HJ.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(zJ),manifestReads(S)&&C.push(BJ),C.sort()}}function readTrackedTexts(t){let n=spawnSync(`git`,[`ls-files`,`-z`],{cwd:t,encoding:`utf8`});if(n.status!==0)throw Error(`git ls-files failed (${n.status}): ${String(n.stderr).trim()}`);let S=new Map;for(let C of n.stdout.split(`\0`)){if(!C||C.startsWith(`refs/`))continue;let n=zn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>VJ)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var zJ,BJ,VJ,HJ,escapeRe,UJ=__esmMin(()=>{cv(),af(),Xn(),zJ=`.github/workflows/main.yml`,BJ=`package.json`,VJ=2*1024*1024,HJ=/^(pre|post)?(install|prepare|build|test)(:|$)/,escapeRe=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)});function scriptReadersFor(t,n){if(n.some(t=>/^scripts\/[^/]+$/.test(t.replace(/\\/g,`/`))))try{return buildScriptReferrers(readTrackedTexts(t))}catch(t){process.stderr.write(`gjsify affected: cannot index the tree for script readers (${String(t)}); root scripts stay unmatched\n`);return}}function runGitDiff(t,n,S){let C=spawnSync(`git`,[`diff`,`--no-renames`,`--name-only`,`${n}...${S}`],{cwd:t,encoding:`utf8`});if(C.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${C.status}): ${C.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${C.status})`);return C.stdout.split(`
|
|
1904
1904
|
`).filter(Boolean)}function emit(t,n){if(t===`json`){process.stdout.write(JSON.stringify(n)+`
|
|
1905
1905
|
`);return}if(t===`globs`){for(let t of n.workspaces)process.stdout.write(`${t}\n`);return}if(t===`github-actions`){let t=n.global?``:n.workspaces.map(t=>`--include ${assertShellSafeWorkspaceName(t)}`).join(` `),S=process.env.GITHUB_OUTPUT,C=[`skip-all=${n.skipAll}`,`global=${n.global}`,`include-args=${t}`,`run-integration=${n.runIntegration}`,`run-e2e=${n.runE2E}`,`reason=${n.reason}`];if(S)for(let t of C)appendFileSync(S,`${t}\n`);else for(let t of C)process.stdout.write(`${t}\n`);return}process.stdout.write(`affected:
|
|
1906
|
-
`),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(
|
|
1906
|
+
`),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(GJ.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 WJ,GJ,KJ=__esmMin(()=>{cv(),af(),MJ(),KI(),RJ(),UJ(),JI(),WJ={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)}},GJ=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),qJ=__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(()=>(WR(),UR));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(()=>(HR(),VR)),{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(()=>(WR(),UR));return spawnSupervised(t(),[n],I)}let[H,W]=_v[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=In(t,S),N=In(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=Hn(N);return F===In(t)?!1:C===F||C.startsWith(`${F}${qn}`)}async function runWatchLoop(t){let{dir:n,label:S,prepare:C,build:N,spawnChild:F,output:I,ignore:H,debounceMs:W=200}=t;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{C&&await C(),q&&=(q.kill(),null),await N(),F&&(q=await F())}catch(t){ge.error(`[${S}] rebuild failed: ${t.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=(t.watch??[{path:n,recursive:!0}]).map(t=>watch(t.path,{recursive:t.recursive},(n,S)=>{let C=typeof S==`string`?S:null;isSelfWrite(t.path,I,C)||H&&C!==null&&H(In(t.path,C))||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))}));holdMainLoop();let ne=!1,shutdown=()=>{if(!ne){ne=!0,Z&&clearTimeout(Z),q?.kill();for(let t of te)t.close();process.exit(0)}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ge.log(`[${S}] watching ${t.dirLabel??n} — press Ctrl+C to stop`)}var JJ=__esmMin(()=>{_e(),af(),Xn(),Ue(),nB(),hv(),vv()});function readPackage$4(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(t){let n=[];if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){if(S.name===`node_modules`||S.name.startsWith(`.`))continue;let C=zn(t,S.name);S.isDirectory()?n.push(...findStoryFiles(C)):/\.story\.(ts|js|mts|mjs)$/.test(S.name)&&n.push(C)}return n}function generateEntry$4(t,n,S){let C=t.map((t,n)=>`import * as m${n} from ${JSON.stringify(t)};`).join(`
|
|
1907
1907
|
`),N=t.map((t,n)=>`m${n}`).join(`, `),F=S?`\n title: ${JSON.stringify(S)},`:``;return`// Auto-generated by \`gjsify storybook\` — do not edit by hand.
|
|
1908
1908
|
import { collectStoryModules, runStorybook } from '@gjsify/storybook';
|
|
1909
1909
|
${C}
|
|
@@ -1912,10 +1912,10 @@ await runStorybook({
|
|
|
1912
1912
|
applicationId: ${JSON.stringify(n)},${F}
|
|
1913
1913
|
stories: collectStoryModules([${N}]),
|
|
1914
1914
|
});
|
|
1915
|
-
`}var
|
|
1915
|
+
`}var YJ,XJ=__esmMin(()=>{_e(),af(),Xn(),P_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),YJ={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=In(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$4(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Bn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(GX(),WX)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(HR(),VR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(WR(),UR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(WR(),UR));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(()=>(JJ(),qJ));await re({dir:N,dirLabel:Bn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function resolveSitePackage(t){let n=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
|
|
1916
1916
|
publishes a page or a store listing. Add it, then run this again:
|
|
1917
1917
|
|
|
1918
|
-
npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(hR(),fR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
1918
|
+
npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(hR(),fR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(GX(),WX));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(HR(),VR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(WR(),UR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(WR(),UR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var ZJ=__esmMin(()=>{_e(),cv(),af(),Xn(),P_(),WR(),__name$1(generateEntry$3,`generateEntry`)}),QJ,$J=__esmMin(()=>{Xn(),ZJ(),QJ={command:`site <operation>`,description:`Render this project's static landing page from its AppStream metainfo (downloads, screenshots, release notes, support links), or sync the page catalogues.`,builder:t=>t.positional(`operation`,{description:`build — render the pages; i18n — update the page catalogues`,type:`string`,choices:[`build`,`i18n`],demandOption:!0}).option(`root`,{description:`Repository to read from (default: the working directory)`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: <root>/dist)`,type:`string`}).option(`offline`,{description:`Skip every network call`,type:`boolean`,default:!1}).option(`drafts`,{description:"build: include blog posts marked `draft: true`",type:`boolean`,default:!1}).option(`cache`,{description:`Use the one-hour HTTP response cache (--no-cache to ignore it)`,type:`boolean`,default:!0}).option(`cache-dir`,{description:`Where the response cache and the image renditions live`,defaultDescription:`<root>/node_modules/.cache/gjsify-site`,type:`string`}).option(`check`,{description:`i18n: report what is out of date instead of writing it`,type:`boolean`,default:!1}).option(`package`,{description:`i18n: sync @gjsify/site's own catalogues instead of this project's`,type:`boolean`,default:!1}).option(`runtime`,{description:"Runtime to build for and run on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle and require @gjsify/node-gi in the project; without it the default falls back to gjs.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}),handler:async t=>{let n=process.cwd(),S=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??Hn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var eY=__esmMin(()=>{Xn(),cR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var tY,nY=__esmMin(()=>{_e(),af(),Xn(),eY(),vv(),P_(),__name$1(readPackage$3,`readPackage`),tY={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:gv,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(GX(),WX)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(JJ(),qJ));await X({dir:W,dirLabel:Bn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
|
|
1919
1919
|
import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
|
|
1920
1920
|
|
|
1921
1921
|
await runDevtoolsMcp(storybookProfile(${F}${I}));
|
|
@@ -1935,24 +1935,24 @@ await runDevtoolsMcp({
|
|
|
1935
1935
|
version: ${JSON.stringify(C)},
|
|
1936
1936
|
busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
|
|
1937
1937
|
});
|
|
1938
|
-
`}var
|
|
1938
|
+
`}var rY,iY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),rY={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(GX(),WX));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(()=>(HR(),VR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
|
|
1939
1939
|
import system from 'system';
|
|
1940
1940
|
|
|
1941
1941
|
import { runDevtoolsCli } from '@gjsify/devtools-mcp';
|
|
1942
1942
|
|
|
1943
1943
|
system.exit(await runDevtoolsCli(system.programArgs));
|
|
1944
|
-
`}var
|
|
1944
|
+
`}var aY,oY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),aY={command:`devtools <operation> [operands..]`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(GX(),WX));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(()=>(HR(),VR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
|
|
1945
1945
|
import { runBrowserDevtools } from '@gjsify/devtools-browser';
|
|
1946
1946
|
|
|
1947
1947
|
await runBrowserDevtools({
|
|
1948
1948
|
applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
|
|
1949
1949
|
});
|
|
1950
|
-
`}var
|
|
1951
|
-
`)}`);let W=`en`in I?`en`:Object.keys(I)[0];return{input:{description:C,...Object.keys(N).length>0?{privacyPolicy:N}:{},...W===void 0?{}:{approvalNotesText:I[W]}},locales:F}}var
|
|
1952
|
-
`).trim(),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(dY,t),I=n.now??(()=>Date.now()),H=`${fY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,pY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(dY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(dY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?hY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(dY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(dY,n):new StoreApiError(dY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(dY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${fY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(dY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(dY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${fY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(dY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}let versionRef=t=>/^\d+$/.test(t)?t:`v${encodeURIComponent(t)}`;async function readBack(t,n){try{return{body:await json(await send(`GET`,t),n)}}catch(t){if(t instanceof StoreApiError)return{unread:t.message};throw t}}function compareLocales(t,n,S,C){return Object.entries(n).map(([n,N])=>{let F={field:t,locale:n,sent:N.length};if(C!==null)return{...F,verdict:`unread`,detail:C.unread};if(typeof S!=`object`||!S)return{...F,verdict:`unread`,detail:`AMO returned no per-locale ${t}.`};let I=S[n];return typeof I==`string`?sameText(I,N)?{...F,verdict:`match`,detail:`read back ${I.length} chars.`}:{...F,verdict:`mismatch`,detail:`AMO holds ${I.length} chars, sent ${N.length}.`}:{...F,verdict:`mismatch`,detail:`AMO holds no ${t} for ${n}.`}})}async function updateListing(t){await send(`PATCH`,`${H}/`,{json:{description:t.description}}),t.privacyPolicy!==void 0&&await send(`PATCH`,`${H}/eula_policy/`,{json:{privacy_policy:t.privacyPolicy}});let n=t.approvalNotes,S=n===void 0?``:`${H}/versions/${versionRef(n.version)}/`;n!==void 0&&await send(`PATCH`,S,{json:{approval_notes:n.text}});let C=[],N=await readBack(`${H}/`,`the add-on detail`),F=`unread`in N?N:null,I=`body`in N?N.body:{};if(C.push(...compareLocales(`description`,t.description,I.description,F)),t.privacyPolicy!==void 0){let n=await readBack(`${H}/eula_policy/`,`the eula_policy`);C.push(...compareLocales(`privacy_policy`,t.privacyPolicy,`body`in n?n.body.privacy_policy:void 0,`unread`in n?n:null))}if(n!==void 0){let t=await readBack(S,`the version detail`),N={field:`approval_notes`,sent:n.text.length};`unread`in t?C.push({...N,verdict:`unread`,detail:t.unread}):typeof t.body.approval_notes==`string`?sameText(t.body.approval_notes,n.text)?C.push({...N,verdict:`match`,detail:`read back ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`mismatch`,detail:`AMO holds ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`unread`,detail:`AMO returned no approval_notes.`})}return{fields:C}}return{store:dY,upload,publish,status,operation,verifyCredentials,updateListing}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(vY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${bY}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${yY}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${yY}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${bY}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${yY}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${yY}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${xY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var vY,yY,bY,xY,versionOf,SY=__esmMin(()=>{af(),FY(),vY=`https://oauth2.googleapis.com/token`,yY=`https://chromewebstore.googleapis.com`,bY=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,xY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var CY,wY,TY,EY,DY,createEdgeBackend,OY=__esmMin(()=>{af(),FY(),CY=`edge`,wY=`https://api.addons.microsoftedge.microsoft.com`,TY=`00000000-0000-0000-0000-000000000000`,EY=400,DY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(CY,t),C],I=`${wY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,EY),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(CY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(CY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?DY:`${DY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(CY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(CY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(CY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(CY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(CY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(CY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${TY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:CY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return kY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=AY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return AY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=NY.includes(t)||/token|secret|key/.test(t)?MY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(MY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=PY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var kY,AY,jY,MY,NY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,PY,FY=__esmMin(()=>{_Y(),SY(),OY(),kY=[`chrome`,`edge`,`amo`],AY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},jY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},MY=`<redacted>`,NY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${jY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
|
|
1950
|
+
`}var sY,cY=__esmMin(()=>{_e(),af(),Xn(),sY={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(GX(),WX));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(()=>(HR(),VR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function amoLocale(t){let[n=``,S]=t.replace(/_/g,`-`).split(`-`),C=n.toLowerCase(),N=lY.find(t=>t.toLowerCase()===(S===void 0?C:`${C}-${S.toLowerCase()}`));if(N!==void 0)return N;if(C===`en`)return`en-US`;if(lY.includes(C))return C;let F=lY.filter(t=>t.startsWith(`${C}-`));return F.length===1?F[0]:null}function readAmoListing(t){let n=zn(t,`amo`);if(!existsSync(n))throw Error(`${n} does not exist. Run \`gjsify webext listing --store amo\` first.`);let S=[],C={},N={},F={},I={},H=readdirSync(n).filter(t=>statSync(zn(n,t)).isDirectory()&&existsSync(zn(n,t,`description.txt`))).sort();for(let t of H){let H=zn(n,t),W=amoLocale(t);if(W===null){S.push(`language "${t}" has no AMO locale (known: ${lY.join(`, `)}).`);continue}let q=Object.entries(F).find(([,t])=>t===W);if(q!==void 0){S.push(`languages "${q[0]}" and "${t}" both map to AMO locale ${W}.`);continue}F[t]=W;let Y=readText(H,`description.txt`);Y===void 0||Y===``?S.push(`${t}/description.txt is missing or empty.`):C[W]=Y;let X=readText(H,`privacy.txt`);X!==void 0&&X!==``&&(N[W]=X);let Z=readText(H,`reviewer-notes.txt`);Z!==void 0&&Z!==``&&(I[t]=Z)}if(H.length===0&&S.push(`${n} holds no language directory with a description.txt.`),S.length>0)throw Error(`the AMO listing in ${n} cannot be sent:\n ${S.join(`
|
|
1951
|
+
`)}`);let W=`en`in I?`en`:Object.keys(I)[0];return{input:{description:C,...Object.keys(N).length>0?{privacyPolicy:N}:{},...W===void 0?{}:{approvalNotesText:I[W]}},locales:F}}var lY,readText,uY=__esmMin(()=>{af(),Xn(),lY=`ar.bg.ca.cak.cs.da.de.dsb.el.en-CA.en-GB.en-US.es.eu.fa.fi.fr.fy-NL.ga-IE.he.hsb.hu.id.it.ja.ka.kab.ko.mk.mn.nl.pl.pt-BR.pt-PT.ro.ru.sk.sl.sq.sv-SE.tr.uk.vi.zh-CN.zh-TW`.split(`.`),readText=(t,n)=>{let S=zn(t,n);return existsSync(S)?readFileSync(S,`utf8`).trim():void 0}});async function runListingUpload(t){let{approvalNotesText:n,...S}=readAmoListing(In(t.listingRoot)).input;if(t.notesVersion!==void 0&&n===void 0)throw Error(`--notes-version is set but no amo/<lang>/reviewer-notes.txt exists.`);let C={...S,...t.notesVersion!==void 0&&n!==void 0?{approvalNotes:{version:t.notesVersion,text:n}}:{}};if(t.dryRun){t.out(`addons.mozilla.org listing: dry run — nothing is sent, no request is made.`);let lines=(n,S)=>{for(let[C,N]of Object.entries(S))t.out(` would send ${n} [${C}]: ${N.length} chars`)};return lines(`description`,C.description),C.privacyPolicy!==void 0&&lines(`privacy_policy (eula_policy)`,C.privacyPolicy),C.approvalNotes!==void 0&&t.out(` would send approval_notes (version ${C.approvalNotes.version}): ${C.approvalNotes.text.length} chars`),t.out(` name and summary are never sent: AMO takes the name from the manifest, and the store summary is the manifest description.`),0}let N=t.backend();if(N.updateListing===void 0)throw Error(`this store has no listing API; only AMO takes listing texts.`);let F=await N.updateListing(C),I=0;for(let n of F.fields)n.verdict!==`match`&&(I+=1),t.out(` ${n.field}${n.locale===void 0?``:` [${n.locale}]`}: ${n.verdict} — ${n.detail}`);return t.out(I===0?`addons.mozilla.org listing: ${F.fields.length} field(s) written and read back, all match.`:`addons.mozilla.org listing: ${I} of ${F.fields.length} field(s) NOT confirmed by the read-back.`),I===0?0:1}var dY=__esmMin(()=>{Xn(),uY()});function signJwt(t,n,S){let C=Math.floor(S/1e3),N=b64url(JSON.stringify({alg:`HS256`,typ:`JWT`})),F=b64url(JSON.stringify({iss:t,jti:randomBytes(16).toString(`hex`),iat:C,exp:C+hY})),I=createHmac(`sha256`,n).update(`${N}.${F}`).digest();return`${N}.${F}.${b64url(I)}`}function validationLines(t){if(typeof t!=`object`||!t)return[];let n=t.messages;if(!Array.isArray(n))return[];let S=[];for(let t of n){if(typeof t!=`object`||!t)continue;let n=t;n.type!==void 0&&n.type!==`error`||(typeof n.message==`string`?S.push(n.message):typeof n.description==`string`&&S.push(n.description))}return S}var fY,pY,mY,hY,gY,b64url,sameText,_Y,normalizeText,createAmoBackend,vY=__esmMin(()=>{fl(),af(),Xn(),IY(),fY=`amo`,pY=`https://addons.mozilla.org/api/v5`,mY=400,hY=60,gY=`the JWT was rejected — check AMO_WEB_EXT_API_KEY / AMO_WEB_EXT_API_SECRET (addons.mozilla.org → Developer Hub → Manage API Keys) and that this machine's clock is correct; AMO refuses a JWT whose iat/exp are off.`,b64url=t=>Buffer.from(t).toString(`base64url`),sameText=(t,n)=>normalizeText(t)===normalizeText(n),_Y={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`},normalizeText=t=>t.replace(/<\/?a\b[^>]*>/gi,``).replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos));/gi,(t,n,S,C)=>{if(C!==void 0)return _Y[C.toLowerCase()];let N=n===void 0?parseInt(S,16):Number(n);return N<=1114111?String.fromCodePoint(N):t}).replace(/\r\n/g,`
|
|
1952
|
+
`).trim(),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(fY,t),I=n.now??(()=>Date.now()),H=`${pY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,mY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(fY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(fY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?gY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(fY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(fY,n):new StoreApiError(fY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(fY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${pY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(fY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(fY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${pY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(fY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}let versionRef=t=>/^\d+$/.test(t)?t:`v${encodeURIComponent(t)}`;async function readBack(t,n){try{return{body:await json(await send(`GET`,t),n)}}catch(t){if(t instanceof StoreApiError)return{unread:t.message};throw t}}function compareLocales(t,n,S,C){return Object.entries(n).map(([n,N])=>{let F={field:t,locale:n,sent:N.length};if(C!==null)return{...F,verdict:`unread`,detail:C.unread};if(typeof S!=`object`||!S)return{...F,verdict:`unread`,detail:`AMO returned no per-locale ${t}.`};let I=S[n];return typeof I==`string`?sameText(I,N)?{...F,verdict:`match`,detail:`read back ${I.length} chars.`}:{...F,verdict:`mismatch`,detail:`AMO holds ${I.length} chars, sent ${N.length}.`}:{...F,verdict:`mismatch`,detail:`AMO holds no ${t} for ${n}.`}})}async function updateListing(t){await send(`PATCH`,`${H}/`,{json:{description:t.description}}),t.privacyPolicy!==void 0&&await send(`PATCH`,`${H}/eula_policy/`,{json:{privacy_policy:t.privacyPolicy}});let n=t.approvalNotes,S=n===void 0?``:`${H}/versions/${versionRef(n.version)}/`;n!==void 0&&await send(`PATCH`,S,{json:{approval_notes:n.text}});let C=[],N=await readBack(`${H}/`,`the add-on detail`),F=`unread`in N?N:null,I=`body`in N?N.body:{};if(C.push(...compareLocales(`description`,t.description,I.description,F)),t.privacyPolicy!==void 0){let n=await readBack(`${H}/eula_policy/`,`the eula_policy`);C.push(...compareLocales(`privacy_policy`,t.privacyPolicy,`body`in n?n.body.privacy_policy:void 0,`unread`in n?n:null))}if(n!==void 0){let t=await readBack(S,`the version detail`),N={field:`approval_notes`,sent:n.text.length};`unread`in t?C.push({...N,verdict:`unread`,detail:t.unread}):typeof t.body.approval_notes==`string`?sameText(t.body.approval_notes,n.text)?C.push({...N,verdict:`match`,detail:`read back ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`mismatch`,detail:`AMO holds ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`unread`,detail:`AMO returned no approval_notes.`})}return{fields:C}}return{store:fY,upload,publish,status,operation,verifyCredentials,updateListing}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(yY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${xY}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${bY}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${bY}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${xY}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${bY}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${bY}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${SY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var yY,bY,xY,SY,versionOf,CY=__esmMin(()=>{af(),IY(),yY=`https://oauth2.googleapis.com/token`,bY=`https://chromewebstore.googleapis.com`,xY=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,SY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var wY,TY,EY,DY,OY,createEdgeBackend,kY=__esmMin(()=>{af(),IY(),wY=`edge`,TY=`https://api.addons.microsoftedge.microsoft.com`,EY=`00000000-0000-0000-0000-000000000000`,DY=400,OY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(wY,t),C],I=`${TY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,DY),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(wY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(wY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?OY:`${OY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(wY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(wY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(wY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(wY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(wY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(wY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${EY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:wY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return AY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=jY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return jY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=PY.includes(t)||/token|secret|key/.test(t)?NY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(NY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=FY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var AY,jY,MY,NY,PY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,FY,IY=__esmMin(()=>{vY(),CY(),kY(),AY=[`chrome`,`edge`,`amo`],jY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},MY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},NY=`<redacted>`,PY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${MY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
|
|
1953
1953
|
`)+`
|
|
1954
|
-
Set them in the environment, never in package.json (ADR 0077 § Amendment 1).`),this.store=t,this.missing=n,this.name=`StoreCredentialsMissingError`}},StoreUnsupportedError=class extends Error{store;constructor(t,n){super(`gjsify webext submit: ${jY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${jY[t].label}: version ${n} is already there — nothing to submit.`),this.store=t,this.version=n,this.name=`StoreVersionAlreadyThereError`}},StoreInReviewError=class extends Error{store;constructor(t,n){super(`${jY[t].label}: a submission is in review — ${n}`),this.store=t,this.name=`StoreInReviewError`}},StoreApiError=class extends Error{store;httpStatus;constructor(t,n,S){super(`${jY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},PY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(RY,t)}function retryBackoffFor(t,n){return stepFrom(n?BY:zY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||HY.includes(n)?!0:n>=500&&n<600}function isThrottled(t){return t instanceof StoreApiError&&t.httpStatus===429}function retryDecision(t,n){return isRepeatableFailure(t)?n===`publish`&&t instanceof StoreApiError&&t.httpStatus===void 0?`verify-first`:`retry`:`fatal`}async function driveSubmission(t,n={}){let{backend:S}=t,C=t.upload.version,N=n.now??(()=>Date.now()),F=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),I=n.timeoutMs??6e5,H=n.secrets??[],W=N(),q=[],Y=0,X=0,Z=0,clean=t=>redactSecrets(t,H),note=t=>n.log?.(clean(`gjsify webext submit: ${t}`)),remaining=()=>I-(N()-W),endPhase=(t,n)=>{q.push({phase:t,requests:Z,elapsedMs:N()-W,detail:clean(n)}),Z=0},finish=(t,n)=>({store:S.store,version:C,verdict:t,exitCode:IY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:LY.includes(t)}),fromError=(t,n,S)=>{let C=n instanceof Error?n.message:String(n);return endPhase(t,C),n instanceof StoreVersionAlreadyThereError?finish(`already-there`,C):n instanceof StoreInReviewError?finish(`in-review`,C):S?finish(`failed`,`${C} — repeated 3x or until the ${I} ms deadline; the failure class is repeatable, so calling again later may work.`):finish(`rejected`,C)},call=async(t,n)=>{for(let S=0;;S++){Y++,Z++;try{return{kind:`value`,value:await n()}}catch(n){if(isIdempotentSkip(n))return{kind:`error`,error:n,exhausted:!1};let C=retryDecision(n,t);if(C===`fatal`)return{kind:`error`,error:n,exhausted:!1};if(C===`verify-first`)return{kind:`lost`,error:n};let N=remaining();if(S>=3||N<=0)return{kind:`error`,error:n,exhausted:!0};let I=Math.min(retryBackoffFor(S,isThrottled(n)),N);note(`${t} failed with a repeatable error, retry ${S+1} of 3 in ${I} ms — `+(n instanceof Error?n.message:String(n))),X++,await F(I)}}},aboutOurVersion=t=>t.version===void 0||t.version===C,waitFor=async(t,n,I,H)=>{let q=S.operation;if(q===void 0&&I!==void 0&&t===`publish`)return endPhase(n,H),{kind:`end`,result:finish(`unverifiable`,`${H} The publish was accepted and the ${S.store} backend declares no operation() to read ${I} with, so whether a submission exists cannot be established from here. It may well be in review — check the dashboard; the fix is operation() on that backend.`)};for(let H=0;;H++){if(q!==void 0&&I!==void 0){let N=await call(`read`,()=>q.call(S,t,I,C));if(N.kind===`error`)return{kind:`end`,result:fromError(n,N.error,N.exhausted)};if(N.kind===`value`&&N.value.state===`succeeded`)return{kind:`done`,detail:N.value.detail};N.kind===`value`&¬e(`${t} operation ${I}: ${N.value.detail}`)}else{let C=await call(`read`,()=>S.status());if(C.kind===`error`)return{kind:`end`,result:fromError(n,C.error,C.exhausted)};if(C.kind===`value`){let S=C.value;if(S.state===`rejected`)return endPhase(n,S.detail),{kind:`end`,result:finish(`rejected`,S.detail)};if(t===`upload`&&S.ingesting!==!0||t===`publish`&&aboutOurVersion(S)&&(S.state===`published`||S.state===`in-review`))return{kind:`done`,detail:S.detail};note(`status while waiting for the ${t}: ${S.detail}`)}}let Y=remaining();if(Y<=0){let S=`the ${t} was accepted and had not resolved after ${N()-W} ms`+(I===void 0?``:` (operation ${I})`)+'. Nothing is lost: call `gjsify webext submit` again — it reads the store\'s state first and will report "already there" or "in review" if this one landed meanwhile. Raise --timeout to wait longer.';return endPhase(n,S),{kind:`end`,result:finish(`unresolved`,S)}}await F(Math.min(pollBackoffFor(H),Y))}};note(`${S.store}: uploading ${C} from ${t.upload.zipPath}`);let te=await call(`upload`,()=>S.upload(t.upload));if(te.kind===`error`)return fromError(`upload`,te.error,te.exhausted);if(te.kind===`lost`)return fromError(`upload`,te.error,!1);if(endPhase(`upload`,te.value.detail),!te.value.ingested){let t=await waitFor(`upload`,`await-upload`,te.value.operationId,te.value.detail);if(t.kind===`end`)return t.result;endPhase(`await-upload`,t.detail)}if(t.publish===void 0)return finish(`uploaded`,`${C} is in the ${S.store} draft and was NOT submitted — pass --submit to ask for review.`);let ne=t.publish,re=0;for(;;){note(`${S.store}: asking for review of ${C}`);let t=await call(`publish`,()=>S.publish(ne));if(t.kind===`error`)return fromError(`publish`,t.error,t.exhausted);if(t.kind===`lost`){let n=t.error instanceof Error?t.error.message:String(t.error);note(`the publish request got no answer (${n}) — asking the store whether it arrived`);let C=await call(`read`,()=>S.status());if(C.kind!==`value`)return fromError(`publish`,C.error,C.kind===`error`&&C.exhausted);let N=C.value;if(N.state===`rejected`)return endPhase(`publish`,N.detail),finish(`rejected`,N.detail);if(aboutOurVersion(N)&&(N.state===`in-review`||N.state===`published`))return endPhase(`publish`,N.detail),finish(N.state===`published`?`published`:`submitted`,`the publish request got no answer, and the store reports it arrived: ${N.detail}`);if(N.state===`draft`&&aboutOurVersion(N)&&re<VY&&remaining()>0){re++,X++,note(`the store still holds a draft (${N.detail}) — sending the publish request once more`);continue}let F=`the publish request got no answer (${n}) and the store's own state does not say whether it arrived: ${N.detail}. The request was NOT repeated — a second one would risk a second submission. Call \`gjsify webext submit\` again once the store settles; it reads the state first.`;return endPhase(`publish`,F),finish(`unresolved`,F)}let n=t.value;if(endPhase(`publish`,n.detail),n.state===`rejected`)return finish(`rejected`,n.detail);if(n.state===`published`)return finish(`published`,n.detail);if(n.state===`in-review`)return finish(`submitted`,n.detail);let N=await waitFor(`publish`,`await-publish`,n.operationId,n.detail);return N.kind===`end`?N.result:(endPhase(`await-publish`,N.detail),finish(`submitted`,N.detail))}}var IY,LY,RY,zY,BY,VY,stepFrom,HY,UY=__esmMin(()=>{FY(),IY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},LY=[`in-review`,`failed`,`unresolved`],RY=[2e3,4e3,8e3,15e3,3e4],zY=[1e3,2e3,4e3],BY=[5e3,15e3,3e4],VY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,HY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.id}.zip`)}function preflightStoreJson(t,n,S){let C;try{C=JSON.parse(t)}catch{return{problems:[`${S} is not valid JSON — regenerate it with \`gjsify webext listing\`.`],manual:[]}}let N=C;if(N.version!==1||!Array.isArray(N.fields))return{problems:[`${S} is not a store.json (version 1) — regenerate it with \`gjsify webext listing\`.`],manual:[]};if(N.store!==n)return{problems:[`${S} is for store "${String(N.store)}", expected "${n}".`],manual:[]};let F=[],I=[];for(let t of N.fields){let n=t.label??t.key??`(unnamed field)`;t.status===`manual`?I.push(n):t.required===!0&&t.status===`missing`&&F.push(`required field "${n}" is missing in ${S}.`)}return{problems:F,manual:I}}function findReviewerNotes(t,n){let S=zn(t,n);if(!existsSync(S))return;let C=readdirSync(S).filter(t=>statSync(zn(S,t)).isDirectory()).sort();for(let t of[`en`,...C.filter(t=>t!==`en`)]){if(!C.includes(t))continue;let n=readText(zn(S,t),`reviewer-notes.txt`);if(n!==void 0&&n!==``)return{text:n,path:zn(S,t,`reviewer-notes.txt`)}}}function secretsOf(t,n){return AY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function describeResult(t,n){let S=[`${n} ${t.version}: ${t.verdict} — ${t.detail}`];for(let n of t.phases)S.push(` ${n.phase}: ${n.detail} (${n.requests} request(s), ${n.elapsedMs} ms)`);return t.retryable&&S.push(` Calling again later, unchanged, can make progress.`),S}async function runSubmit(t){let{env:n,project:S}=t,C=asStoreId(t.store),N=C===null?[]:secretsOf(C,n),clean=t=>redactSecrets(t,N),out=n=>t.out(clean(n)),err=n=>t.err(clean(n));try{if(C===null)throw Error(`gjsify webext submit: unknown store "${t.store}".`);let F=jY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);if(t.submit&&!isTagRef(n.GITHUB_REF))throw Error(`gjsify webext submit: --submit asks the store for review and runs only on a tag ($GITHUB_REF must start with refs/tags/). Without --submit the zip is uploaded (AMO: validated, no version created).`);let I;if(t.timeoutSeconds!==void 0){if(!Number.isFinite(t.timeoutSeconds)||t.timeoutSeconds<0)throw Error(`gjsify webext submit: --timeout is a number of seconds, 0 or more.`);I=t.timeoutSeconds*1e3}if(t.listingOnly){if(C!==`amo`)throw Error(`gjsify webext submit: --listing-only applies to AMO only; Chrome and Edge have no listing API.`);if(t.submit||t.zip!==void 0||t.sourceZip!==void 0)throw Error(`gjsify webext submit: --listing-only sends texts only; drop --submit, --zip and --source.`);let N=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0;return await runListingUpload({listingRoot:In(S.root,t.listingDir??`dist/listing`),dryRun:t.dryRun,notesVersion:t.notesVersion,backend:()=>(t.createBackend??createStoreBackend)(C,n,{fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:N}),out})}if(t.notesVersion!==void 0)throw Error(`gjsify webext submit: --notes-version belongs to --listing-only.`);let H=WY[C],W=zn(In(S.root,t.listingDir??`dist/listing`),H,`store.json`);if(!existsSync(W))throw Error(`gjsify webext submit: ${W} does not exist. Run \`gjsify webext listing --store ${H}\` first; it is the preflight for the listing the dashboard will ask about.`);let q=preflightStoreJson(readFileSync(W,`utf8`),H,W);if(q.problems.length>0)throw Error(`gjsify webext submit: preflight failed, nothing was sent:\n ${q.problems.join(`
|
|
1955
|
-
`)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=C===`edge`||C===`amo`?findReviewerNotes(In(S.root,t.listingDir??`dist/listing`),H):void 0;Z===void 0&&C===`edge`&&t.submit&&err("warning: no reviewer-notes.txt under the listing dir; Edge reviewers expect certification notes. Run `gjsify webext listing --store edge` first. Continuing without notes.");let te=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,ne={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:te},re=(t.createBackend??createStoreBackend)(C,n,ne);if(t.dryRun)return re.verifyCredentials===void 0?(out(`${F.label}: dry run — credentials are set; this backend has no read-only check, so they are unverified. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0):(await re.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0);let ie=await driveSubmission({backend:re,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X,notes:Z?.text}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:te,secrets:N}),ae=ie.exitCode===0?out:err;for(let t of describeResult(ie,F.label))ae(t);return IY[ie.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var WY,GY=__esmMin(()=>{af(),Xn(),uY(),FY(),lY(),UY(),WY={chrome:`cws`,edge:`edge`,amo:`amo`}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Un(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Un(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var KY=__esmMin(()=>{af(),Xn(),EH()});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(()=>(hR(),fR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++qY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++qY}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var qY,JY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),qY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(tX.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(YY,n=>{let S=ZY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!nX.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:$Y.test(n)?`esm`:`iife`,output:F}),n.replace(ZY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(XY,t=>{if(!eX.test(t))return t;let n=QY.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace(QY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var YY,XY,ZY,QY,$Y,eX,tX,nX,rX=__esmMin(()=>{Xn(),YY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,XY=/<link\b[^>]*>/gi,ZY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,QY=/\bhref\s*=\s*(["'])([^"']+)\1/i,$Y=/\btype\s*=\s*["']module["']/i,eX=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,tX=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nX=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=iX?n:iX}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=zn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:zn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:zn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,zn(H,t.output))}writeFileSync(zn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=zn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,zn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(zn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
|
|
1956
|
-
- `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var
|
|
1957
|
-
- `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function resolveSubmitProject(t,n){let S=t.gjsify?.webext;if(S!==void 0&&!isRecord(S))throw Error("gjsify webext: `gjsify.webext` must be an object.");let C=S??{},N=[],F=C.targets??[...
|
|
1958
|
-
- `)}`);return{root:n,name:C.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,outDir:Rn(C.outDir??`.output`)?C.outDir:In(n,C.outDir??`.output`)}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var uX,dX,fX,pX=__esmMin(()=>{af(),Xn(),lX(),uX=[16,32,48,128],dX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],fX=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return zn(S.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var mX,hX=__esmMin(()=>{af(),o_(),Xn(),fL(),lX(),mX="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function loadSubmitProject(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveSubmitProject(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(WX(),UX)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?In(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var gX,_X,vX,yX,bX,xX,SX,CX,wX=__esmMin(()=>{_e(),af(),Xn(),XJ(),GY(),aX(),pX(),hX(),gX={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},_X={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},vX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},yX={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,gX).option(`out-dir`,_X).option(`define`,vX).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)},bX={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,gX).option(`out-dir`,_X).option(`define`,vX),handler:t=>runBuild(t,!0)},xX={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`,{...gX,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,vX).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(mX);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(qJ(),KJ));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(()=>(qJ(),KJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}},SX={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}},CX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,type:`string`,choices:[`chrome`,`edge`,`amo`],demandOption:!0}).option(`zip`,{description:"The zip to upload (default: what `webext zip` writes for the store's target).",type:`string`}).option(`dry-run`,{description:`Check the credentials with one read call; upload nothing.`,type:`boolean`,default:!1}).option(`submit`,{description:`Ask for review after the upload. Refused unless $GITHUB_REF is a tag.`,type:`boolean`,default:!1}).option(`timeout`,{description:`Seconds to wait for the store to resolve an upload or submission (default: 600).`,type:`number`}).option(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-only`,{description:`AMO only: send description and privacy policy from --listing-dir (not the zip), then read each back. With --dry-run: lengths only, no network.`,type:`boolean`,default:!1}).option(`notes-version`,{description:`With --listing-only: also send the reviewer notes (approval_notes) to this version id or number.`,type:`string`}).option(`listing-dir`,{description:"Where `webext listing` wrote store.json (default: dist/listing).",type:`string`}).epilog(`Credentials come from the environment only (see ADR 0077 § Amendment 1). Exit codes: 0 done or nothing to do, 1 rejected or failed, 3 accepted but unresolved (run again), 4 unverifiable. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. A submission stuck in review is cancelled in the Chrome dashboard (:cancelSubmission); this command never does.`),handler:async t=>{let n=process.cwd(),S=await runSubmit({store:t.store,zip:t.zip?In(n,t.zip):void 0,dryRun:t.dryRun,submit:t.submit,timeoutSeconds:t.timeout,listingDir:t.listingDir,sourceZip:t.source?In(n,t.source):void 0,listingOnly:t.listingOnly,notesVersion:t.notesVersion,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),TX,EX=__esmMin(()=>{wX(),TX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(yX.command,yX.description,yX.builder,yX.handler).command(bX.command,bX.description,bX.builder,bX.handler).command(xX.command,xX.description,xX.builder,xX.handler).command(SX.command,SX.description,SX.builder,SX.handler).command(CX.command,CX.description,CX.builder,CX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!OX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${DX} is not set. Create one with \`${DW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(DW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${DW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${DW} failed with ${describeExit(S)}.`)}var DX,OX,kX=__esmMin(()=>{af(),RW(),hv(),DX=`SNAPCRAFT_STORE_CREDENTIALS`,OX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),AX,jX,MX,NX=__esmMin(()=>{Xn(),kX(),AX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},jX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},MX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),PX,FX=__esmMin(()=>{NX(),PX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(AX.command,AX.description,AX.builder,AX.handler).command(jX.command,jX.description,jX.builder,jX.handler).command(MX.command,MX.description,MX.builder,MX.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())IX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var IX,LX,formatFor,RX,zX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),IX=new Set([`node_modules`,`dist`,`lib`,`.git`]),LX=new Map,formatFor=t=>{let n=LX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return LX.set(t,S),S},RX={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>Rn(t)?t:In(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Un(n),formatFor(Hn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),BX,VX=__esmMin(()=>{zX(),BX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(RX.command,RX.description,RX.builder,RX.handler).demandCommand(1).strict()}}),HX=__esmMin(()=>{bR(),SR(),TR(),kR(),KR(),YR(),iB(),oB(),cB(),vB(),jB(),XB(),$B(),rV(),oV(),iH(),UG(),XG(),DB(),nK(),aK(),dK(),gB(),gK(),QK(),rq(),dq(),Cq(),Tq(),Oq(),Aq(),Iq(),Hq(),Xq(),$q(),tJ(),rJ(),fJ(),mJ(),gJ(),CJ(),OJ(),AJ(),GJ(),YJ(),QJ(),tY(),rY(),aY(),sY(),EX(),FX(),VX()}),UX=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=ch(t);await n.scriptName(wh).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(YB.command,YB.description,YB.builder,YB.handler).command(eK.command,eK.description,eK.builder,eK.handler).command(rK.command,rK.description,rK.builder,rK.handler).command(iK.command,iK.description,iK.builder,iK.handler).command(yR.command,yR.description,yR.builder,yR.handler).command(xR.command,xR.description,xR.builder,xR.handler).command(wR.command,wR.description,wR.builder,wR.handler).command(OR.command,OR.description,OR.builder,OR.handler).command(GR.command,GR.description,GR.builder,GR.handler).command(JR.command,JR.description,JR.builder,JR.handler).command(rB.command,rB.description,rB.builder,rB.handler).command(EB.command,EB.description,EB.builder,EB.handler).command(aB.command,aB.description,aB.builder,aB.handler).command(sB.command,sB.description,sB.builder,sB.handler).command(_B.command,_B.description,_B.builder,_B.handler).command(AB.command,AB.description,AB.builder,AB.handler).command(QB.command,QB.description,QB.builder,QB.handler).command(nV.command,nV.description,nV.builder,nV.handler).command(aV.command,aV.description,aV.builder,aV.handler).command(rH.command,rH.description,rH.builder,rH.handler).command(VG.command,VG.description,VG.builder,VG.handler).command(YG.command,YG.description,YG.builder,YG.handler).command(uK.command,uK.description,uK.builder,uK.handler).command(hB.command,hB.description,hB.builder,hB.handler).command(pK.command,pK.description,pK.builder,pK.handler).command(ZK.command,ZK.description,ZK.builder,ZK.handler).command(wq.command,wq.description,wq.builder,wq.handler).command(nq.command,nq.description,nq.builder,nq.handler).command(uq.command,uq.description,uq.builder,uq.handler).command(Sq.command,Sq.description,Sq.builder,Sq.handler).command(Dq.command,Dq.description,Dq.builder,Dq.handler).command(kq.command,kq.description,kq.builder,kq.handler).command(Fq.command,Fq.description,Fq.builder,Fq.handler).command(Vq.command,Vq.description,Vq.builder,Vq.handler).command(Jq.command,Jq.description,Jq.builder,Jq.handler).command(Qq.command,Qq.description,Qq.builder,Qq.handler).command(nJ.command,nJ.description,nJ.builder,nJ.handler).command(eJ.command,eJ.description,eJ.builder,eJ.handler).command(yJ.command,yJ.description,yJ.builder,yJ.handler).command(dJ.command,dJ.description,dJ.builder,dJ.handler).command(pJ.command,pJ.description,pJ.builder,pJ.handler).command(hJ.command,hJ.description,hJ.builder,hJ.handler).command(DJ.command,DJ.description,DJ.builder,DJ.handler).command(kJ.command,kJ.description,kJ.builder,kJ.handler).command(UJ.command,UJ.description,UJ.builder,UJ.handler).command(JJ.command,JJ.description,JJ.builder,JJ.handler).command(ZJ.command,ZJ.description,ZJ.builder,ZJ.handler).command(eY.command,eY.description,eY.builder,eY.handler).command(nY.command,nY.description,nY.builder,nY.handler).command(iY.command,iY.description,iY.builder,iY.handler).command(oY.command,oY.description,oY.builder,oY.handler).command(TX.command,TX.description,TX.builder,TX.handler).command(PX.command,PX.description,PX.builder,PX.handler).command(BX.command,BX.description,BX.builder,BX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var WX=__esmMin(()=>{lh(),uh(),Ch(),HX(),Th(),P_(),eB()});WX(),P_(),nB();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),P_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const GX=globalThis.process,KX=Number(GX?.exitCode);Number.isInteger(KX)&&KX!==0&&GX.exit(KX);
|
|
1954
|
+
Set them in the environment, never in package.json (ADR 0077 § Amendment 1).`),this.store=t,this.missing=n,this.name=`StoreCredentialsMissingError`}},StoreUnsupportedError=class extends Error{store;constructor(t,n){super(`gjsify webext submit: ${MY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${MY[t].label}: version ${n} is already there — nothing to submit.`),this.store=t,this.version=n,this.name=`StoreVersionAlreadyThereError`}},StoreInReviewError=class extends Error{store;constructor(t,n){super(`${MY[t].label}: a submission is in review — ${n}`),this.store=t,this.name=`StoreInReviewError`}},StoreApiError=class extends Error{store;httpStatus;constructor(t,n,S){super(`${MY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},FY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(zY,t)}function retryBackoffFor(t,n){return stepFrom(n?VY:BY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||UY.includes(n)?!0:n>=500&&n<600}function isThrottled(t){return t instanceof StoreApiError&&t.httpStatus===429}function retryDecision(t,n){return isRepeatableFailure(t)?n===`publish`&&t instanceof StoreApiError&&t.httpStatus===void 0?`verify-first`:`retry`:`fatal`}async function driveSubmission(t,n={}){let{backend:S}=t,C=t.upload.version,N=n.now??(()=>Date.now()),F=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),I=n.timeoutMs??6e5,H=n.secrets??[],W=N(),q=[],Y=0,X=0,Z=0,clean=t=>redactSecrets(t,H),note=t=>n.log?.(clean(`gjsify webext submit: ${t}`)),remaining=()=>I-(N()-W),endPhase=(t,n)=>{q.push({phase:t,requests:Z,elapsedMs:N()-W,detail:clean(n)}),Z=0},finish=(t,n)=>({store:S.store,version:C,verdict:t,exitCode:LY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:RY.includes(t)}),fromError=(t,n,S)=>{let C=n instanceof Error?n.message:String(n);return endPhase(t,C),n instanceof StoreVersionAlreadyThereError?finish(`already-there`,C):n instanceof StoreInReviewError?finish(`in-review`,C):S?finish(`failed`,`${C} — repeated 3x or until the ${I} ms deadline; the failure class is repeatable, so calling again later may work.`):finish(`rejected`,C)},call=async(t,n)=>{for(let S=0;;S++){Y++,Z++;try{return{kind:`value`,value:await n()}}catch(n){if(isIdempotentSkip(n))return{kind:`error`,error:n,exhausted:!1};let C=retryDecision(n,t);if(C===`fatal`)return{kind:`error`,error:n,exhausted:!1};if(C===`verify-first`)return{kind:`lost`,error:n};let N=remaining();if(S>=3||N<=0)return{kind:`error`,error:n,exhausted:!0};let I=Math.min(retryBackoffFor(S,isThrottled(n)),N);note(`${t} failed with a repeatable error, retry ${S+1} of 3 in ${I} ms — `+(n instanceof Error?n.message:String(n))),X++,await F(I)}}},aboutOurVersion=t=>t.version===void 0||t.version===C,waitFor=async(t,n,I,H)=>{let q=S.operation;if(q===void 0&&I!==void 0&&t===`publish`)return endPhase(n,H),{kind:`end`,result:finish(`unverifiable`,`${H} The publish was accepted and the ${S.store} backend declares no operation() to read ${I} with, so whether a submission exists cannot be established from here. It may well be in review — check the dashboard; the fix is operation() on that backend.`)};for(let H=0;;H++){if(q!==void 0&&I!==void 0){let N=await call(`read`,()=>q.call(S,t,I,C));if(N.kind===`error`)return{kind:`end`,result:fromError(n,N.error,N.exhausted)};if(N.kind===`value`&&N.value.state===`succeeded`)return{kind:`done`,detail:N.value.detail};N.kind===`value`&¬e(`${t} operation ${I}: ${N.value.detail}`)}else{let C=await call(`read`,()=>S.status());if(C.kind===`error`)return{kind:`end`,result:fromError(n,C.error,C.exhausted)};if(C.kind===`value`){let S=C.value;if(S.state===`rejected`)return endPhase(n,S.detail),{kind:`end`,result:finish(`rejected`,S.detail)};if(t===`upload`&&S.ingesting!==!0||t===`publish`&&aboutOurVersion(S)&&(S.state===`published`||S.state===`in-review`))return{kind:`done`,detail:S.detail};note(`status while waiting for the ${t}: ${S.detail}`)}}let Y=remaining();if(Y<=0){let S=`the ${t} was accepted and had not resolved after ${N()-W} ms`+(I===void 0?``:` (operation ${I})`)+'. Nothing is lost: call `gjsify webext submit` again — it reads the store\'s state first and will report "already there" or "in review" if this one landed meanwhile. Raise --timeout to wait longer.';return endPhase(n,S),{kind:`end`,result:finish(`unresolved`,S)}}await F(Math.min(pollBackoffFor(H),Y))}};note(`${S.store}: uploading ${C} from ${t.upload.zipPath}`);let te=await call(`upload`,()=>S.upload(t.upload));if(te.kind===`error`)return fromError(`upload`,te.error,te.exhausted);if(te.kind===`lost`)return fromError(`upload`,te.error,!1);if(endPhase(`upload`,te.value.detail),!te.value.ingested){let t=await waitFor(`upload`,`await-upload`,te.value.operationId,te.value.detail);if(t.kind===`end`)return t.result;endPhase(`await-upload`,t.detail)}if(t.publish===void 0)return finish(`uploaded`,`${C} is in the ${S.store} draft and was NOT submitted — pass --submit to ask for review.`);let ne=t.publish,re=0;for(;;){note(`${S.store}: asking for review of ${C}`);let t=await call(`publish`,()=>S.publish(ne));if(t.kind===`error`)return fromError(`publish`,t.error,t.exhausted);if(t.kind===`lost`){let n=t.error instanceof Error?t.error.message:String(t.error);note(`the publish request got no answer (${n}) — asking the store whether it arrived`);let C=await call(`read`,()=>S.status());if(C.kind!==`value`)return fromError(`publish`,C.error,C.kind===`error`&&C.exhausted);let N=C.value;if(N.state===`rejected`)return endPhase(`publish`,N.detail),finish(`rejected`,N.detail);if(aboutOurVersion(N)&&(N.state===`in-review`||N.state===`published`))return endPhase(`publish`,N.detail),finish(N.state===`published`?`published`:`submitted`,`the publish request got no answer, and the store reports it arrived: ${N.detail}`);if(N.state===`draft`&&aboutOurVersion(N)&&re<HY&&remaining()>0){re++,X++,note(`the store still holds a draft (${N.detail}) — sending the publish request once more`);continue}let F=`the publish request got no answer (${n}) and the store's own state does not say whether it arrived: ${N.detail}. The request was NOT repeated — a second one would risk a second submission. Call \`gjsify webext submit\` again once the store settles; it reads the state first.`;return endPhase(`publish`,F),finish(`unresolved`,F)}let n=t.value;if(endPhase(`publish`,n.detail),n.state===`rejected`)return finish(`rejected`,n.detail);if(n.state===`published`)return finish(`published`,n.detail);if(n.state===`in-review`)return finish(`submitted`,n.detail);let N=await waitFor(`publish`,`await-publish`,n.operationId,n.detail);return N.kind===`end`?N.result:(endPhase(`await-publish`,N.detail),finish(`submitted`,N.detail))}}var LY,RY,zY,BY,VY,HY,stepFrom,UY,WY=__esmMin(()=>{IY(),LY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},RY=[`in-review`,`failed`,`unresolved`],zY=[2e3,4e3,8e3,15e3,3e4],BY=[1e3,2e3,4e3],VY=[5e3,15e3,3e4],HY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,UY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.id}.zip`)}function preflightStoreJson(t,n,S){let C;try{C=JSON.parse(t)}catch{return{problems:[`${S} is not valid JSON — regenerate it with \`gjsify webext listing\`.`],manual:[]}}let N=C;if(N.version!==1||!Array.isArray(N.fields))return{problems:[`${S} is not a store.json (version 1) — regenerate it with \`gjsify webext listing\`.`],manual:[]};if(N.store!==n)return{problems:[`${S} is for store "${String(N.store)}", expected "${n}".`],manual:[]};let F=[],I=[];for(let t of N.fields){let n=t.label??t.key??`(unnamed field)`;t.status===`manual`?I.push(n):t.required===!0&&t.status===`missing`&&F.push(`required field "${n}" is missing in ${S}.`)}return{problems:F,manual:I}}function findReviewerNotes(t,n){let S=zn(t,n);if(!existsSync(S))return;let C=readdirSync(S).filter(t=>statSync(zn(S,t)).isDirectory()).sort();for(let t of[`en`,...C.filter(t=>t!==`en`)]){if(!C.includes(t))continue;let n=readText(zn(S,t),`reviewer-notes.txt`);if(n!==void 0&&n!==``)return{text:n,path:zn(S,t,`reviewer-notes.txt`)}}}function secretsOf(t,n){return jY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function describeResult(t,n){let S=[`${n} ${t.version}: ${t.verdict} — ${t.detail}`];for(let n of t.phases)S.push(` ${n.phase}: ${n.detail} (${n.requests} request(s), ${n.elapsedMs} ms)`);return t.retryable&&S.push(` Calling again later, unchanged, can make progress.`),S}async function runSubmit(t){let{env:n,project:S}=t,C=asStoreId(t.store),N=C===null?[]:secretsOf(C,n),clean=t=>redactSecrets(t,N),out=n=>t.out(clean(n)),err=n=>t.err(clean(n));try{if(C===null)throw Error(`gjsify webext submit: unknown store "${t.store}".`);let F=MY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);if(t.submit&&!isTagRef(n.GITHUB_REF))throw Error(`gjsify webext submit: --submit asks the store for review and runs only on a tag ($GITHUB_REF must start with refs/tags/). Without --submit the zip is uploaded (AMO: validated, no version created).`);let I;if(t.timeoutSeconds!==void 0){if(!Number.isFinite(t.timeoutSeconds)||t.timeoutSeconds<0)throw Error(`gjsify webext submit: --timeout is a number of seconds, 0 or more.`);I=t.timeoutSeconds*1e3}if(t.listingOnly){if(C!==`amo`)throw Error(`gjsify webext submit: --listing-only applies to AMO only; Chrome and Edge have no listing API.`);if(t.submit||t.zip!==void 0||t.sourceZip!==void 0)throw Error(`gjsify webext submit: --listing-only sends texts only; drop --submit, --zip and --source.`);let N=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0;return await runListingUpload({listingRoot:In(S.root,t.listingDir??`dist/listing`),dryRun:t.dryRun,notesVersion:t.notesVersion,backend:()=>(t.createBackend??createStoreBackend)(C,n,{fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:N}),out})}if(t.notesVersion!==void 0)throw Error(`gjsify webext submit: --notes-version belongs to --listing-only.`);let H=GY[C],W=zn(In(S.root,t.listingDir??`dist/listing`),H,`store.json`);if(!existsSync(W))throw Error(`gjsify webext submit: ${W} does not exist. Run \`gjsify webext listing --store ${H}\` first; it is the preflight for the listing the dashboard will ask about.`);let q=preflightStoreJson(readFileSync(W,`utf8`),H,W);if(q.problems.length>0)throw Error(`gjsify webext submit: preflight failed, nothing was sent:\n ${q.problems.join(`
|
|
1955
|
+
`)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=C===`edge`||C===`amo`?findReviewerNotes(In(S.root,t.listingDir??`dist/listing`),H):void 0;Z===void 0&&C===`edge`&&t.submit&&err("warning: no reviewer-notes.txt under the listing dir; Edge reviewers expect certification notes. Run `gjsify webext listing --store edge` first. Continuing without notes.");let te=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,ne={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:te},re=(t.createBackend??createStoreBackend)(C,n,ne);if(t.dryRun)return re.verifyCredentials===void 0?(out(`${F.label}: dry run — credentials are set; this backend has no read-only check, so they are unverified. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0):(await re.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0);let ie=await driveSubmission({backend:re,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X,notes:Z?.text}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:te,secrets:N}),ae=ie.exitCode===0?out:err;for(let t of describeResult(ie,F.label))ae(t);return LY[ie.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var GY,KY=__esmMin(()=>{af(),Xn(),dY(),IY(),uY(),WY(),GY={chrome:`cws`,edge:`edge`,amo:`amo`}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Un(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Un(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var qY=__esmMin(()=>{af(),Xn(),DH()});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(()=>(hR(),fR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++JY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++JY}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var JY,YY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),JY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(nX.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(XY,n=>{let S=QY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!rX.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:eX.test(n)?`esm`:`iife`,output:F}),n.replace(QY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(ZY,t=>{if(!tX.test(t))return t;let n=$Y.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace($Y,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var XY,ZY,QY,$Y,eX,tX,nX,rX,iX=__esmMin(()=>{Xn(),XY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,ZY=/<link\b[^>]*>/gi,QY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,$Y=/\bhref\s*=\s*(["'])([^"']+)\1/i,eX=/\btype\s*=\s*["']module["']/i,tX=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,nX=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rX=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=aX?n:aX}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=zn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:zn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:zn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,zn(H,t.output))}writeFileSync(zn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=zn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,zn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(zn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
|
|
1956
|
+
- `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var aX,oX=__esmMin(()=>{_e(),af(),Xn(),hG(),qY(),YY(),iX(),aX=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!sX.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${sX.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?lX.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 sX,cX,lX,uX=__esmMin(()=>{sX=[`chrome`,`edge`,`firefox`,`opera`,`safari`],cX=[`chrome-mv3`,`firefox-mv3`],lX=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>Rn(t)?t:In(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...cX];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=fX.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${fX.join(`, `)} exists.`):W=zn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!pX.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??dX;(!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(!pX.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=zn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${C.join(`
|
|
1957
|
+
- `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function resolveSubmitProject(t,n){let S=t.gjsify?.webext;if(S!==void 0&&!isRecord(S))throw Error("gjsify webext: `gjsify.webext` must be an object.");let C=S??{},N=[],F=C.targets??[...cX],I=[];if(!Array.isArray(F)||F.length===0)N.push("`targets` must be a non-empty array of target names.");else for(let t of F)try{I.push(parseWebextTarget(String(t)))}catch(t){N.push(t.message.replace(/^gjsify webext: /,``))}if(N.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${N.join(`
|
|
1958
|
+
- `)}`);return{root:n,name:C.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,outDir:Rn(C.outDir??`.output`)?C.outDir:In(n,C.outDir??`.output`)}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var dX,fX,pX,mX=__esmMin(()=>{af(),Xn(),uX(),dX=[16,32,48,128],fX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],pX=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return zn(S.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var hX,gX=__esmMin(()=>{af(),o_(),Xn(),fL(),uX(),hX="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function loadSubmitProject(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveSubmitProject(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(GX(),WX)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?In(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var _X,vX,yX,bX,xX,SX,CX,wX,TX=__esmMin(()=>{_e(),af(),Xn(),ZJ(),KY(),oX(),mX(),gX(),_X={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},vX={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},yX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},bX={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,_X).option(`out-dir`,vX).option(`define`,yX).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)},xX={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,_X).option(`out-dir`,vX).option(`define`,yX),handler:t=>runBuild(t,!0)},SX={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`,{..._X,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,yX).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(hX);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(JJ(),qJ));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(()=>(JJ(),qJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}},CX={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}},wX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,type:`string`,choices:[`chrome`,`edge`,`amo`],demandOption:!0}).option(`zip`,{description:"The zip to upload (default: what `webext zip` writes for the store's target).",type:`string`}).option(`dry-run`,{description:`Check the credentials with one read call; upload nothing.`,type:`boolean`,default:!1}).option(`submit`,{description:`Ask for review after the upload. Refused unless $GITHUB_REF is a tag.`,type:`boolean`,default:!1}).option(`timeout`,{description:`Seconds to wait for the store to resolve an upload or submission (default: 600).`,type:`number`}).option(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-only`,{description:`AMO only: send description and privacy policy from --listing-dir (not the zip), then read each back. With --dry-run: lengths only, no network.`,type:`boolean`,default:!1}).option(`notes-version`,{description:`With --listing-only: also send the reviewer notes (approval_notes) to this version id or number.`,type:`string`}).option(`listing-dir`,{description:"Where `webext listing` wrote store.json (default: dist/listing).",type:`string`}).epilog(`Credentials come from the environment only (see ADR 0077 § Amendment 1). Exit codes: 0 done or nothing to do, 1 rejected or failed, 3 accepted but unresolved (run again), 4 unverifiable. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. A submission stuck in review is cancelled in the Chrome dashboard (:cancelSubmission); this command never does.`),handler:async t=>{let n=process.cwd(),S=await runSubmit({store:t.store,zip:t.zip?In(n,t.zip):void 0,dryRun:t.dryRun,submit:t.submit,timeoutSeconds:t.timeout,listingDir:t.listingDir,sourceZip:t.source?In(n,t.source):void 0,listingOnly:t.listingOnly,notesVersion:t.notesVersion,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),EX,DX=__esmMin(()=>{TX(),EX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(bX.command,bX.description,bX.builder,bX.handler).command(xX.command,xX.description,xX.builder,xX.handler).command(SX.command,SX.description,SX.builder,SX.handler).command(CX.command,CX.description,CX.builder,CX.handler).command(wX.command,wX.description,wX.builder,wX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!kX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${OX} is not set. Create one with \`${OW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(OW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${OW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${OW} failed with ${describeExit(S)}.`)}var OX,kX,AX=__esmMin(()=>{af(),zW(),hv(),OX=`SNAPCRAFT_STORE_CREDENTIALS`,kX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),jX,MX,NX,PX=__esmMin(()=>{Xn(),AX(),jX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},MX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},NX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),FX,IX=__esmMin(()=>{PX(),FX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(jX.command,jX.description,jX.builder,jX.handler).command(MX.command,MX.description,MX.builder,MX.handler).command(NX.command,NX.description,NX.builder,NX.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())LX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var LX,RX,formatFor,zX,BX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),LX=new Set([`node_modules`,`dist`,`lib`,`.git`]),RX=new Map,formatFor=t=>{let n=RX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return RX.set(t,S),S},zX={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>Rn(t)?t:In(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Un(n),formatFor(Hn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),VX,HX=__esmMin(()=>{BX(),VX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(zX.command,zX.description,zX.builder,zX.handler).demandCommand(1).strict()}}),UX=__esmMin(()=>{bR(),SR(),TR(),kR(),KR(),YR(),iB(),oB(),cB(),vB(),jB(),XB(),$B(),rV(),oV(),aH(),WG(),ZG(),DB(),rK(),oK(),fK(),gB(),_K(),$K(),iq(),fq(),wq(),Eq(),kq(),jq(),Lq(),Uq(),Zq(),eJ(),nJ(),iJ(),pJ(),hJ(),_J(),wJ(),kJ(),jJ(),KJ(),XJ(),$J(),nY(),iY(),oY(),cY(),DX(),IX(),HX()}),WX=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=ch(t);await n.scriptName(wh).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(YB.command,YB.description,YB.builder,YB.handler).command(tK.command,tK.description,tK.builder,tK.handler).command(iK.command,iK.description,iK.builder,iK.handler).command(aK.command,aK.description,aK.builder,aK.handler).command(yR.command,yR.description,yR.builder,yR.handler).command(xR.command,xR.description,xR.builder,xR.handler).command(wR.command,wR.description,wR.builder,wR.handler).command(OR.command,OR.description,OR.builder,OR.handler).command(GR.command,GR.description,GR.builder,GR.handler).command(JR.command,JR.description,JR.builder,JR.handler).command(rB.command,rB.description,rB.builder,rB.handler).command(EB.command,EB.description,EB.builder,EB.handler).command(aB.command,aB.description,aB.builder,aB.handler).command(sB.command,sB.description,sB.builder,sB.handler).command(_B.command,_B.description,_B.builder,_B.handler).command(AB.command,AB.description,AB.builder,AB.handler).command(QB.command,QB.description,QB.builder,QB.handler).command(nV.command,nV.description,nV.builder,nV.handler).command(aV.command,aV.description,aV.builder,aV.handler).command(iH.command,iH.description,iH.builder,iH.handler).command(HG.command,HG.description,HG.builder,HG.handler).command(XG.command,XG.description,XG.builder,XG.handler).command(dK.command,dK.description,dK.builder,dK.handler).command(hB.command,hB.description,hB.builder,hB.handler).command(mK.command,mK.description,mK.builder,mK.handler).command(QK.command,QK.description,QK.builder,QK.handler).command(Tq.command,Tq.description,Tq.builder,Tq.handler).command(rq.command,rq.description,rq.builder,rq.handler).command(dq.command,dq.description,dq.builder,dq.handler).command(Cq.command,Cq.description,Cq.builder,Cq.handler).command(Oq.command,Oq.description,Oq.builder,Oq.handler).command(Aq.command,Aq.description,Aq.builder,Aq.handler).command(Iq.command,Iq.description,Iq.builder,Iq.handler).command(Hq.command,Hq.description,Hq.builder,Hq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command($q.command,$q.description,$q.builder,$q.handler).command(rJ.command,rJ.description,rJ.builder,rJ.handler).command(tJ.command,tJ.description,tJ.builder,tJ.handler).command(bJ.command,bJ.description,bJ.builder,bJ.handler).command(fJ.command,fJ.description,fJ.builder,fJ.handler).command(mJ.command,mJ.description,mJ.builder,mJ.handler).command(gJ.command,gJ.description,gJ.builder,gJ.handler).command(OJ.command,OJ.description,OJ.builder,OJ.handler).command(AJ.command,AJ.description,AJ.builder,AJ.handler).command(WJ.command,WJ.description,WJ.builder,WJ.handler).command(YJ.command,YJ.description,YJ.builder,YJ.handler).command(QJ.command,QJ.description,QJ.builder,QJ.handler).command(tY.command,tY.description,tY.builder,tY.handler).command(rY.command,rY.description,rY.builder,rY.handler).command(aY.command,aY.description,aY.builder,aY.handler).command(sY.command,sY.description,sY.builder,sY.handler).command(EX.command,EX.description,EX.builder,EX.handler).command(FX.command,FX.description,FX.builder,FX.handler).command(VX.command,VX.description,VX.builder,VX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var GX=__esmMin(()=>{lh(),uh(),Ch(),UX(),Th(),P_(),eB()});GX(),P_(),nB();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),P_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const KX=globalThis.process,qX=Number(KX?.exitCode);Number.isInteger(qX)&&qX!==0&&KX.exit(qX);
|