@gjsify/cli 0.46.0 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.gjs.mjs +28 -27
- package/lib/commands/onboard.js +11 -0
- package/lib/commands/publish.d.ts +41 -0
- package/lib/commands/publish.js +222 -2
- package/lib/utils/publish-readback.d.ts +132 -0
- package/lib/utils/publish-readback.js +273 -0
- package/lib/utils/ship/layout.js +8 -4
- package/package.json +19 -19
package/dist/cli.gjs.mjs
CHANGED
|
@@ -39,7 +39,7 @@ function tokenizeArgString(n){if(Array.isArray(n))return n.map(n=>typeof n==`str
|
|
|
39
39
|
* SPDX-License-Identifier: ISC
|
|
40
40
|
*/
|
|
41
41
|
function combineAliases(n){let S=[],C=Object.create(null),N=!0;for(Object.keys(n).forEach(function(C){S.push([].concat(n[C],C))});N;){N=!1;for(let n=0;n<S.length;n++)for(let C=n+1;C<S.length;C++)if(S[n].filter(function(n){return S[C].indexOf(n)!==-1}).length){S[n]=S[n].concat(S[C]),S.splice(C,1),N=!0;break}}return S.forEach(function(n){n=n.filter(function(n,S,C){return C.indexOf(n)===S});let S=n.pop();S!==void 0&&typeof S==`string`&&(C[S]=n)}),C}function increment$1(n){return n===void 0?1:n+1}function sanitizeKey(n){return n===`__proto__`?`___proto___`:n}function stripQuotes$1(n){return typeof n==`string`&&(n[0]===`'`||n[0]===`"`)&&n[n.length-1]===n[0]?n.substring(1,n.length-1):n}var Fc,YargsParser,Ic=__esmMin(()=>{Mc(),Pc(),jc(),YargsParser=class{constructor(n){Fc=n}parse(n,S){let C=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},S),N=tokenizeArgString(n),F=typeof n==`string`,I=combineAliases(Object.assign(Object.create(null),C.alias)),H=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},C.configuration),W=Object.assign(Object.create(null),C.default),q=C.configObjects||[],Y=C.envPrefix,X=H[`populate--`],Z=X?`--`:`_`,te=Object.create(null),ne=Object.create(null),re=C.__||Fc.format,ie={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},ae=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,oe=RegExp(`^--`+H[`negation-prefix`]+`(.+)`);[].concat(C.array||[]).filter(Boolean).forEach(function(n){let S=typeof n==`object`?n.key:n,C=Object.keys(n).map(function(n){return{boolean:`bools`,string:`strings`,number:`numbers`}[n]}).filter(Boolean).pop();C&&(ie[C][S]=!0),ie.arrays[S]=!0,ie.keys.push(S)}),[].concat(C.boolean||[]).filter(Boolean).forEach(function(n){ie.bools[n]=!0,ie.keys.push(n)}),[].concat(C.string||[]).filter(Boolean).forEach(function(n){ie.strings[n]=!0,ie.keys.push(n)}),[].concat(C.number||[]).filter(Boolean).forEach(function(n){ie.numbers[n]=!0,ie.keys.push(n)}),[].concat(C.count||[]).filter(Boolean).forEach(function(n){ie.counts[n]=!0,ie.keys.push(n)}),[].concat(C.normalize||[]).filter(Boolean).forEach(function(n){ie.normalize[n]=!0,ie.keys.push(n)}),typeof C.narg==`object`&&Object.entries(C.narg).forEach(([n,S])=>{typeof S==`number`&&(ie.nargs[n]=S,ie.keys.push(n))}),typeof C.coerce==`object`&&Object.entries(C.coerce).forEach(([n,S])=>{typeof S==`function`&&(ie.coercions[n]=S,ie.keys.push(n))}),C.config!==void 0&&(Array.isArray(C.config)||typeof C.config==`string`?[].concat(C.config).filter(Boolean).forEach(function(n){ie.configs[n]=!0}):typeof C.config==`object`&&Object.entries(C.config).forEach(([n,S])=>{(typeof S==`boolean`||typeof S==`function`)&&(ie.configs[n]=S)})),extendAliases(C.key,I,C.default,ie.arrays),Object.keys(W).forEach(function(n){(ie.aliases[n]||[]).forEach(function(S){W[S]=W[n]})});let se=null;checkConfiguration();let Q=[],ce=Object.assign(Object.create(null),{_:[]}),le={};for(let n=0;n<N.length;n++){let S=N[n],C=S.replace(/^-{3,}/,`---`),F,I,W,q,Y,X;if(S!==`--`&&/^-/.test(S)&&isUnknownOptionAsArg(S))pushPositional(S);else if(C.match(/^---+(=|$)/)){pushPositional(S);continue}else if(S.match(/^--.+=/)||!H[`short-option-groups`]&&S.match(/^-.+=/))q=S.match(/^--?([^=]+)=([\s\S]*)$/),q!==null&&Array.isArray(q)&&q.length>=3&&(checkAllAliases(q[1],ie.arrays)?n=eatArray(n,q[1],N,q[2]):checkAllAliases(q[1],ie.nargs)===!1?setArg(q[1],q[2],!0):n=eatNargs(n,q[1],N,q[2]));else if(S.match(oe)&&H[`boolean-negation`])q=S.match(oe),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],setArg(I,checkAllAliases(I,ie.arrays)?[!1]:!1));else if(S.match(/^--.+/)||!H[`short-option-groups`]&&S.match(/^-[^-]+/))q=S.match(/^--?(.+)/),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N):checkAllAliases(I,ie.nargs)===!1?(Y=N[n+1],Y!==void 0&&(!Y.match(/^-/)||Y.match(ae))&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)||/^(true|false)$/.test(Y)?(setArg(I,Y),n++):setArg(I,defaultValue(I))):n=eatNargs(n,I,N));else if(S.match(/^-.\..+=/))q=S.match(/^-([^=]+)=([\s\S]*)$/),q!==null&&Array.isArray(q)&&q.length>=3&&setArg(q[1],q[2]);else if(S.match(/^-.\..+/)&&!S.match(ae))Y=N[n+1],q=S.match(/^-(.\..+)/),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],Y!==void 0&&!Y.match(/^-/)&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)?(setArg(I,Y),n++):setArg(I,defaultValue(I)));else if(S.match(/^-[^-]+/)&&!S.match(ae)){W=S.slice(1,-1).split(``),F=!1;for(let C=0;C<W.length;C++){if(Y=S.slice(C+2),W[C+1]&&W[C+1]===`=`){X=S.slice(C+3),I=W[C],checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N,X):checkAllAliases(I,ie.nargs)===!1?setArg(I,X):n=eatNargs(n,I,N,X),F=!0;break}if(Y===`-`){setArg(W[C],Y);continue}if(/[A-Za-z]/.test(W[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(Y)&&checkAllAliases(Y,ie.bools)===!1){setArg(W[C],Y),F=!0;break}if(W[C+1]&&W[C+1].match(/\W/)){setArg(W[C],Y),F=!0;break}else setArg(W[C],defaultValue(W[C]))}I=S.slice(-1)[0],!F&&I!==`-`&&(checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N):checkAllAliases(I,ie.nargs)===!1?(Y=N[n+1],Y!==void 0&&(!/^(-|--)[^-]/.test(Y)||Y.match(ae))&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)||/^(true|false)$/.test(Y)?(setArg(I,Y),n++):setArg(I,defaultValue(I))):n=eatNargs(n,I,N))}else if(S.match(/^-[0-9]$/)&&S.match(ae)&&checkAllAliases(S.slice(1),ie.bools))I=S.slice(1),setArg(I,defaultValue(I));else if(S===`--`){Q=N.slice(n+1);break}else if(H[`halt-at-non-option`]){Q=N.slice(n);break}else pushPositional(S)}applyEnvVars(ce,!0),applyEnvVars(ce,!1),setConfig(ce),setConfigObjects(),applyDefaultsAndAliases(ce,ie.aliases,W,!0),applyCoercions(ce),H[`set-placeholder-key`]&&setPlaceholderKeys(ce),Object.keys(ie.counts).forEach(function(n){hasKey(ce,n.split(`.`))||setArg(n,0)}),X&&Q.length&&(ce[Z]=[]),Q.forEach(function(n){ce[Z].push(n)}),H[`camel-case-expansion`]&&H[`strip-dashed`]&&Object.keys(ce).filter(n=>n!==`--`&&n.includes(`-`)).forEach(n=>{delete ce[n]}),H[`strip-aliased`]&&[].concat(...Object.keys(I).map(n=>I[n])).forEach(n=>{H[`camel-case-expansion`]&&n.includes(`-`)&&delete ce[n.split(`.`).map(n=>camelCase(n)).join(`.`)],delete ce[n]});function pushPositional(n){let S=maybeCoerceNumber(`_`,n);(typeof S==`string`||typeof S==`number`)&&ce._.push(S)}function eatNargs(n,S,C,N){let F,I=checkAllAliases(S,ie.nargs);if(I=typeof I!=`number`||isNaN(I)?1:I,I===0)return isUndefined(N)||(se=Error(re(`Argument unexpected for: %s`,S))),setArg(S,defaultValue(S)),n;let W=+!isUndefined(N);if(H[`nargs-eats-options`])C.length-(n+1)+W<I&&(se=Error(re(`Not enough arguments following: %s`,S))),W=I;else{for(F=n+1;F<C.length&&(!C[F].match(/^-[^0-9]/)||C[F].match(ae)||isUnknownOptionAsArg(C[F]));F++)W++;W<I&&(se=Error(re(`Not enough arguments following: %s`,S)))}let q=Math.min(W,I);for(!isUndefined(N)&&q>0&&(setArg(S,N),q--),F=n+1;F<q+n+1;F++)setArg(S,C[F]);return n+q}function eatArray(n,S,C,N){let I=[],q=N||C[n+1],Y=checkAllAliases(S,ie.nargs);if(checkAllAliases(S,ie.bools)&&!/^(true|false)$/.test(q))I.push(!0);else if(isUndefined(q)||isUndefined(N)&&/^-/.test(q)&&!ae.test(q)&&!isUnknownOptionAsArg(q)){if(W[S]!==void 0){let n=W[S];I=Array.isArray(n)?n:[n]}}else{isUndefined(N)||I.push(processValue(S,N,!0));for(let N=n+1;N<C.length&&!(!H[`greedy-arrays`]&&I.length>0||Y&&typeof Y==`number`&&I.length>=Y||(q=C[N],/^-/.test(q)&&!ae.test(q)&&!isUnknownOptionAsArg(q)));N++)n=N,I.push(processValue(S,q,F))}return typeof Y==`number`&&(Y&&I.length<Y||isNaN(Y)&&I.length===0)&&(se=Error(re(`Not enough arguments following: %s`,S))),setArg(S,I),n}function setArg(n,S,C=F){/-/.test(n)&&H[`camel-case-expansion`]&&addNewAlias(n,n.split(`.`).map(function(n){return camelCase(n)}).join(`.`));let N=processValue(n,S,C),I=n.split(`.`);setKey(ce,I,N),ie.aliases[n]&&ie.aliases[n].forEach(function(n){let S=n.split(`.`);setKey(ce,S,N)}),I.length>1&&H[`dot-notation`]&&(ie.aliases[I[0]]||[]).forEach(function(S){let C=S.split(`.`),F=[].concat(I);F.shift(),C=C.concat(F),(ie.aliases[n]||[]).includes(C.join(`.`))||setKey(ce,C,N)}),checkAllAliases(n,ie.normalize)&&!checkAllAliases(n,ie.arrays)&&[n].concat(ie.aliases[n]||[]).forEach(function(n){Object.defineProperty(le,n,{enumerable:!0,get(){return S},set(n){S=typeof n==`string`?Fc.normalize(n):n}})})}function addNewAlias(n,S){ie.aliases[n]&&ie.aliases[n].length||(ie.aliases[n]=[S],te[S]=!0),ie.aliases[S]&&ie.aliases[S].length||addNewAlias(S,n)}function processValue(n,S,C){C&&(S=stripQuotes$1(S)),(checkAllAliases(n,ie.bools)||checkAllAliases(n,ie.counts))&&typeof S==`string`&&(S=S===`true`);let N=Array.isArray(S)?S.map(function(S){return maybeCoerceNumber(n,S)}):maybeCoerceNumber(n,S);return checkAllAliases(n,ie.counts)&&(isUndefined(N)||typeof N==`boolean`)&&(N=increment$1()),checkAllAliases(n,ie.normalize)&&checkAllAliases(n,ie.arrays)&&(N=Array.isArray(S)?S.map(n=>Fc.normalize(n)):Fc.normalize(S)),N}function maybeCoerceNumber(n,S){return!H[`parse-positional-numbers`]&&n===`_`||!checkAllAliases(n,ie.strings)&&!checkAllAliases(n,ie.bools)&&!Array.isArray(S)&&(looksLikeNumber(S)&&H[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))||!isUndefined(S)&&checkAllAliases(n,ie.numbers))&&(S=Number(S)),S}function setConfig(n){let S=Object.create(null);applyDefaultsAndAliases(S,ie.aliases,W),Object.keys(ie.configs).forEach(function(C){let N=n[C]||S[C];if(N)try{let n=null,S=Fc.resolve(Fc.cwd(),N),F=ie.configs[C];if(typeof F==`function`){try{n=F(S)}catch(S){n=S}if(n instanceof Error){se=n;return}}else n=Fc.require(S);setConfigObject(n)}catch(S){S.name===`PermissionDenied`?se=S:n[C]&&(se=Error(re(`Invalid JSON config file: %s`,N)))}})}function setConfigObject(n,S){Object.keys(n).forEach(function(C){let N=n[C],F=S?S+`.`+C:C;typeof N==`object`&&N&&!Array.isArray(N)&&H[`dot-notation`]?setConfigObject(N,F):(!hasKey(ce,F.split(`.`))||checkAllAliases(F,ie.arrays)&&H[`combine-arrays`])&&setArg(F,N)})}function setConfigObjects(){q!==void 0&&q.forEach(function(n){setConfigObject(n)})}function applyEnvVars(n,S){if(Y===void 0)return;let C=typeof Y==`string`?Y:``,N=Fc.env();Object.keys(N).forEach(function(F){if(C===``||F.lastIndexOf(C,0)===0){let I=F.split(`__`).map(function(n,S){return S===0&&(n=n.substring(C.length)),camelCase(n)});(S&&ie.configs[I.join(`.`)]||!S)&&!hasKey(n,I)&&setArg(I.join(`.`),N[F])}})}function applyCoercions(n){let S,C=new Set;Object.keys(n).forEach(function(N){if(!C.has(N)&&(S=checkAllAliases(N,ie.coercions),typeof S==`function`))try{let F=maybeCoerceNumber(N,S(n[N]));[].concat(ie.aliases[N]||[],N).forEach(S=>{C.add(S),n[S]=F})}catch(n){se=n}})}function setPlaceholderKeys(n){return ie.keys.forEach(S=>{~S.indexOf(`.`)||n[S]===void 0&&(n[S]=void 0)}),n}function applyDefaultsAndAliases(n,S,C,N=!1){Object.keys(C).forEach(function(F){hasKey(n,F.split(`.`))||(setKey(n,F.split(`.`),C[F]),N&&(ne[F]=!0),(S[F]||[]).forEach(function(S){hasKey(n,S.split(`.`))||setKey(n,S.split(`.`),C[F])}))})}function hasKey(n,S){let C=n;H[`dot-notation`]||(S=[S.join(`.`)]),S.slice(0,-1).forEach(function(n){C=C[n]||{}});let N=S[S.length-1];return typeof C==`object`?N in C:!1}function setKey(n,S,C){let N=n;H[`dot-notation`]||(S=[S.join(`.`)]),S.slice(0,-1).forEach(function(n){n=sanitizeKey(n),typeof N==`object`&&N[n]===void 0&&(N[n]={}),typeof N[n]!=`object`||Array.isArray(N[n])?(Array.isArray(N[n])?N[n].push({}):N[n]=[N[n],{}],N=N[n][N[n].length-1]):N=N[n]});let F=sanitizeKey(S[S.length-1]),I=checkAllAliases(S.join(`.`),ie.arrays),W=Array.isArray(C),q=H[`duplicate-arguments-array`];!q&&checkAllAliases(F,ie.nargs)&&(q=!0,(!isUndefined(N[F])&&ie.nargs[F]===1||Array.isArray(N[F])&&N[F].length===ie.nargs[F])&&(N[F]=void 0)),C===increment$1()?N[F]=increment$1(N[F]):Array.isArray(N[F])?q&&I&&W?N[F]=H[`flatten-duplicate-arrays`]?N[F].concat(C):(Array.isArray(N[F][0])?N[F]:[N[F]]).concat([C]):!q&&!!I==!!W?N[F]=C:N[F]=N[F].concat([C]):N[F]===void 0&&I?N[F]=W?C:[C]:q&&!(N[F]===void 0||checkAllAliases(F,ie.counts)||checkAllAliases(F,ie.bools))?N[F]=[N[F],C]:N[F]=C}function extendAliases(...n){n.forEach(function(n){Object.keys(n||{}).forEach(function(n){ie.aliases[n]||(ie.aliases[n]=[].concat(I[n]||[]),ie.aliases[n].concat(n).forEach(function(S){if(/-/.test(S)&&H[`camel-case-expansion`]){let C=camelCase(S);C!==n&&ie.aliases[n].indexOf(C)===-1&&(ie.aliases[n].push(C),te[C]=!0)}}),ie.aliases[n].concat(n).forEach(function(S){if(S.length>1&&/[A-Z]/.test(S)&&H[`camel-case-expansion`]){let C=decamelize(S,`-`);C!==n&&ie.aliases[n].indexOf(C)===-1&&(ie.aliases[n].push(C),te[C]=!0)}}),ie.aliases[n].forEach(function(S){ie.aliases[S]=[n].concat(ie.aliases[n].filter(function(n){return S!==n}))}))})})}function checkAllAliases(n,S){let C=[].concat(ie.aliases[n]||[],n),N=Object.keys(S),F=C.find(n=>N.includes(n));return F?S[F]:!1}function hasAnyFlag(n){let S=Object.keys(ie);return[].concat(S.map(n=>ie[n])).some(function(S){return Array.isArray(S)?S.includes(n):S[n]})}function hasFlagsMatching(n,...S){return[].concat(...S).some(function(S){let C=n.match(S);return C&&hasAnyFlag(C[1])})}function hasAllShortFlags(n){if(n.match(ae)||!n.match(/^-[^-]+/))return!1;let S=!0,C,N=n.slice(1).split(``);for(let F=0;F<N.length;F++){if(C=n.slice(F+2),!hasAnyFlag(N[F])){S=!1;break}if(N[F+1]&&N[F+1]===`=`||C===`-`||/[A-Za-z]/.test(N[F])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(C)||N[F+1]&&N[F+1].match(/\W/))break}return S}function isUnknownOptionAsArg(n){return H[`unknown-options-as-args`]&&isUnknownOption(n)}function isUnknownOption(n){return n=n.replace(/^-{3,}/,`--`),n.match(ae)||hasAllShortFlags(n)?!1:!hasFlagsMatching(n,/^-+([^=]+?)=[\s\S]*$/,oe,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function defaultValue(n){return!checkAllAliases(n,ie.bools)&&!checkAllAliases(n,ie.counts)&&`${n}`in W?W[n]:defaultForType(guessType(n))}function defaultForType(n){return{[Nc.BOOLEAN]:!0,[Nc.STRING]:``,[Nc.NUMBER]:void 0,[Nc.ARRAY]:[]}[n]}function guessType(n){let S=Nc.BOOLEAN;return checkAllAliases(n,ie.strings)?S=Nc.STRING:checkAllAliases(n,ie.numbers)?S=Nc.NUMBER:checkAllAliases(n,ie.bools)?S=Nc.BOOLEAN:checkAllAliases(n,ie.arrays)&&(S=Nc.ARRAY),S}function isUndefined(n){return n===void 0}function checkConfiguration(){Object.keys(ie.counts).find(n=>checkAllAliases(n,ie.arrays)?(se=Error(re(`Invalid configuration: %s, opts.count excludes opts.array.`,n)),!0):checkAllAliases(n,ie.nargs)?(se=Error(re(`Invalid configuration: %s, opts.count excludes opts.narg.`,n)),!0):!1)}return{aliases:Object.assign({},ie.aliases),argv:Object.assign(le,ce),configuration:H,defaulted:Object.assign({},ne),error:se,newAliases:Object.assign({},te)}}},__name$1(increment$1,`increment`),__name$1(stripQuotes$1,`stripQuotes`)}),Lc,Rc,zc=__esmMin(()=>{Lc=Object.defineProperty,Rc=__name$1((n,S)=>{let C={};for(var N in n)Lc(C,N,{get:n[N],enumerable:!0});return S||Lc(C,Symbol.toStringTag,{value:`Module`}),C},`__exportAll`)});function normalizePath(n){return n instanceof URL||n instanceof mn?fileURLToPath(n):typeof n==`string`?n:n.toString()}function randomName(){return[...[,,,,,,]].map(()=>`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`[Math.floor(Math.random()*62)]).join(``)}var Bc=__esmMin(()=>{gn()});function createNodeError(n,S,C,N){return typeof n?.code==`string`?n:createNodeError$1(n,S,{path:C.toString(),dest:N?.toString()})}function requireCallback(n,S=`cb`){if(typeof n==`function`)return n;let C=TypeError(`The "${S}" argument must be of type function. Received ${describeReceived(n)}`);throw C.code=`ERR_INVALID_ARG_TYPE`,C}function describeReceived(n){if(n==null)return String(n);if(typeof n==`object`){let S=n.constructor?.name;return`an instance of ${S&&S.length>0?S:`Object`}`}if(typeof n==`string`){let S=n.length>25?`${n.slice(0,25)}...`:n;return S.includes(`'`)?`type string ("${S}")`:`type string ('${S}')`}return typeof n==`bigint`?`type bigint (${n}n)`:typeof n==`symbol`?`type symbol (${n.toString()})`:`type ${typeof n} (${String(n)})`}function invalidState(n){let S=Error(`Invalid state: ${n}`);return S.code=`ERR_INVALID_STATE`,S}var Vc=__esmMin(()=>{Be()});function gioEventToNodeType(n){switch(n){case Lr.FileMonitorEvent.CHANGED:case Lr.FileMonitorEvent.CHANGES_DONE_HINT:return`change`;case Lr.FileMonitorEvent.DELETED:case Lr.FileMonitorEvent.CREATED:case Lr.FileMonitorEvent.RENAMED:case Lr.FileMonitorEvent.MOVED_IN:case Lr.FileMonitorEvent.MOVED_OUT:return`rename`;default:return null}}var WatchTree,Hc=__esmMin(()=>{Vc(),Rr(),Hs(),Be(),WatchTree=class{_monitors=new Map;_fileMonitors=new Map;_closed=!1;_root;_recursive;_fanOut;_budget;_budgetReported=!1;_onEvent;_onError;constructor(n,S,C,N,F){this._recursive=S,this._onEvent=C,this._onError=N,this._fanOut=F?.fanOut??isDarwin(),this._budget=F?.budget??(this._fanOut?4096:1/0);let I=Lr.File.new_for_path(n);this._root=I.get_path()??n,this._open(this._root,I),I.query_file_type(Lr.FileQueryInfoFlags.NONE,null)===Lr.FileType.DIRECTORY&&(S||this._fanOut)&&this._descend(this._root,!1)}get monitorCount(){return this._monitors.size+this._fileMonitors.size}close(){this._closed=!0;for(let n of this._monitors.values())n.cancel();this._monitors.clear();for(let n of this._fileMonitors.values())n.cancel();this._fileMonitors.clear()}_open(n,S){let C=S.monitor(Lr.FileMonitorFlags.NONE,null);C.connect(`changed`,(n,S,C,N)=>{this._dispatch(S,N)}),this._monitors.set(n,C)}_watchFile(n){if(this._closed||this._fileMonitors.has(n)||!this._admit(n))return;let S;try{S=Lr.File.new_for_path(n).monitor(Lr.FileMonitorFlags.NONE,null)}catch(n){isNotFoundError(n)||this._onError(n);return}S.connect(`changed`,(n,S,C,N)=>{if(gioEventToNodeType(N)!==`change`)return;let F=S.get_path();F!==null&&this._emit(`change`,F)}),this._fileMonitors.set(n,S)}_admit(n){if(this.monitorCount<this._budget)return!0;if(this._budgetReported)return!1;this._budgetReported=!0;let S=Error(`fs.watch: this watch holds its whole budget of ${this._budget} monitors and stopped at ${n}. Anything under ${this._root} that is not already attached is NOT being watched, and no further event will arrive for it. The budget is finite because this host needs a monitor per FILE rather than per directory, and unbounded growth of a shared process resource surfaces as an unrelated allocation failing elsewhere, in a trace that never mentions fs.watch. Watch a narrower directory.`);return S.code=`ERR_FS_WATCH_MONITOR_BUDGET`,S.path=n,this._onError(S),!1}_dispatch(n,S){let C=n.get_path();if(C===null)return;let N=gioEventToNodeType(S);if(N!==null&&this._emit(N,C),!(!this._recursive&&!this._fanOut))switch(S){case Lr.FileMonitorEvent.CREATED:case Lr.FileMonitorEvent.MOVED_IN:{let S=n.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);S===Lr.FileType.DIRECTORY?this._recursive&&this._addSubtree(C,!0):this._fanOut&&S===Lr.FileType.REGULAR&&this._watchFile(C);break}case Lr.FileMonitorEvent.DELETED:case Lr.FileMonitorEvent.MOVED_OUT:this._dropSubtree(C);break}}_emit(n,S){let C=Ms(this._root,S);this._onEvent(n,C===``?Fs(S):C)}_addSubtree(n,S){if(!(this._closed||this._monitors.has(n))&&this._admit(n)){try{this._open(n,Lr.File.new_for_path(n))}catch(n){isNotFoundError(n)||this._onError(n);return}this._descend(n,S)}}_descend(n,S){for(let C of this._children(n)){if(this._closed)return;if(C.isDirectory){if(!this._recursive)continue;S&&this._emit(`rename`,C.path),this._addSubtree(C.path,S)}else S&&this._emit(`rename`,C.path),this._fanOut&&C.isFile&&this._watchFile(C.path)}}_dropSubtree(n){this._fileMonitors.get(n)?.cancel(),this._fileMonitors.delete(n);let S=n+zs;for(let[n,C]of this._fileMonitors)n.startsWith(S)&&(C.cancel(),this._fileMonitors.delete(n));for(let[C,N]of this._monitors)C!==n&&!C.startsWith(S)||(N.cancel(),this._monitors.delete(C))}_children(n){let S;try{S=Lr.File.new_for_path(n).enumerate_children(`standard::name,standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){return isNotFoundError(n)||this._onError(n),[]}let C=[];try{let N=S.next_file(null);for(;N!==null;){let F=N.get_file_type();C.push({path:js(n,N.get_name()),isDirectory:F===Lr.FileType.DIRECTORY,isFile:F===Lr.FileType.REGULAR}),N=S.next_file(null)}}catch(n){isNotFoundError(n)||this._onError(n)}finally{try{S.close(null)}catch{}}return C}}});async function*watchAsync(n,S){let C=S?.signal;if(C?.aborted)return;let N=normalizePath(n),F=[],I=[],H=!1,W=null;function enqueue(n){H||(I.length>0?I.shift().resolve({value:n,done:!1}):F.push(n))}function terminate(){if(!H)for(H=!0;I.length>0;)I.shift().resolve({value:void 0,done:!0})}let q;try{q=new WatchTree(N,S?.recursive===!0,(n,S)=>{enqueue({eventType:n,filename:S})},n=>{W=n,terminate()})}catch{return}let abortHandler=()=>terminate();C?.addEventListener(`abort`,abortHandler);try{for(;!H;){if(F.length>0){yield F.shift();continue}let n=await new Promise(n=>{I.push({resolve:n})});if(n.done)break;yield n.value}if(W!==null)throw W}finally{C?.removeEventListener(`abort`,abortHandler),q.close()}}var Uc,FSWatcher,Wc=__esmMin(()=>{Bc(),Hc(),pt(),Kt(),Uc=new WeakMap,FSWatcher=class extends Ft{constructor(n,S,C){super(),(!S||typeof S!=`object`)&&(S={persistent:!0});let N=S.persistent!==!1,F=new WatchTree(normalizePath(n),S.recursive===!0,(n,S)=>{this.emit(`change`,n,S)},n=>{this.emit(`error`,n)}),I=null;N&&(I=ft.timeout_add(ft.PRIORITY_LOW,2147483647,()=>ft.SOURCE_CONTINUE)),Uc.set(this,{persistent:N,closed:!1,sourceId:I,tree:F}),C&&this.on(`change`,C)}close(){let n=Uc.get(this);n.closed||(n.closed=!0,n.tree.close(),n.sourceId!==null&&(ft.source_remove(n.sourceId),n.sourceId=null))}ref(){let n=Uc.get(this);return!n.persistent&&!n.closed&&(n.persistent=!0,n.sourceId=ft.timeout_add(ft.PRIORITY_LOW,2147483647,()=>ft.SOURCE_CONTINUE)),this}unref(){let n=Uc.get(this);return n.persistent&&(n.persistent=!1,n.sourceId!==null&&(ft.source_remove(n.sourceId),n.sourceId=null)),this}}}),Gc=__exportAll$4({lchmod:()=>void 0,lchmodAsync:()=>lchmodAsync,lchmodSync:()=>void 0,lchown:()=>lchown,lchownAsync:()=>lchownAsync,lchownSync:()=>lchownSync,lutimes:()=>lutimes,lutimesAsync:()=>lutimesAsync,lutimesSync:()=>lutimesSync,utimes:()=>utimes,utimesAsync:()=>utimesAsync,utimesSync:()=>utimesSync});function toGLibDateTime(n){let S=n instanceof Date?n.getTime():typeof n==`bigint`?Number(n):typeof n==`string`?Date.parse(n):n*1e3;return ft.DateTime.new_from_unix_utc(Math.floor(S/1e3))}function setTimestamps(n,S,C,N){let F=Lr.File.new_for_path(n),I=new Lr.FileInfo;I.set_modification_date_time(toGLibDateTime(C)),I.set_access_date_time(toGLibDateTime(S)),F.set_attributes_from_info(I,N,null)}function utimesSync(n,S,C){setTimestamps(normalizePath(n),S,C,Lr.FileQueryInfoFlags.NONE)}function utimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>utimesSync(n,S,C)).then(()=>N(null),N)}async function utimesAsync(n,S,C){utimesSync(n,S,C)}function lutimesSync(n,S,C){setTimestamps(normalizePath(n),S,C,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS)}function lutimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>lutimesSync(n,S,C)).then(()=>N(null),N)}async function lutimesAsync(n,S,C){lutimesSync(n,S,C)}function lchownSync(n,S,C){let N=normalizePath(n),F=Lr.File.new_for_path(N),I=new Lr.FileInfo;S!==-1&&I.set_attribute_uint32(`unix::uid`,S),C!==-1&&I.set_attribute_uint32(`unix::gid`,C),F.set_attributes_from_info(I,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}function lchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>lchownSync(n,S,C)).then(()=>N(null),N)}async function lchownAsync(n,S,C){lchownSync(n,S,C)}function lchmodUnsupported(){let n=Error(`The lchmod() method is not implemented`);return n.code=`ERR_METHOD_NOT_IMPLEMENTED`,n}async function lchmodAsync(n,S){throw lchmodUnsupported()}var Kc=__esmMin(()=>{Bc(),Vc(),pt(),Rr()});function isStdFd(n){return n===0||n===1||n===2}function stdinInput(){return qc||=da.InputStream.new(0,!1),qc}function stdOutput(n){return Jc[n]||(Jc[n]=da.OutputStream.new(n,!1)),Jc[n]}function readStdFdAll(n){try{let S=n===0?stdinInput():da.InputStream.new(n,!1),C=[],N=0;for(;;){let n=S.read_bytes(64*1024,null).get_data();if(!n||n.length===0)break;C.push(n),N+=n.length}return concat(C,N)}catch(S){if(n!==0)throw S;let[C,N]=Lr.File.new_for_path(`/dev/stdin`).load_contents(null);if(!C)throw S;return N}}function readStdFdSync(n,S,C,N){let F=(n===0?stdinInput():da.InputStream.new(n,!1)).read_bytes(N,null).get_data();return F&&F.length>0?(new Uint8Array(S.buffer,S.byteOffset+C).set(F),F.length):0}function writeStdFdSync(n,S){return stdOutput(n).write_bytes(ft.Bytes.new(S),null)}function concat(n,S){if(n.length===1)return n[0];let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}var qc,Jc,Yc=__esmMin(()=>{pt(),Rr(),fa(),qc=null,Jc={}});function getEncodingFromOptions(n={encoding:null,flag:`r`},S=`utf8`){return n===null?S:typeof n==`string`?n:typeof n==`object`&&typeof n.encoding==`string`?n.encoding:S}function encodeUint8Array(n,S){return n===`buffer`?$e.from(S):new TextDecoder(n).decode(S)}function decode(n,S){if(S){let C=new TextDecoder(S),N=new TextEncoder;return C.decode(N.encode(n))}else return n}var Xc=__esmMin(()=>{lt()});function createReadStream(n,S){return new ReadStream$1(n,S)}var ReadStream$1,Zc=__esmMin(()=>{Bc(),Fl(),Pl(),pt(),Rr(),lt(),gi(),ReadStream$1=class extends li{static{__name$1(this,`ReadStream`)}bytesRead=0;path;pending=!0;fd=null;_ownFd=null;_autoCloseFd=!0;_positional=!1;_gioFile;_inputStream=null;_cancellable=new Lr.Cancellable;_start;_end;_pos;_reading=!1;_readAgain=!1;_lastSize=64*1024;close(n){this._cancellable.cancel(),this._release(),this.destroy(),n&&n(null)}constructor(n,S){let C=normalizePath(n);super({highWaterMark:S?.highWaterMark??64*1024,encoding:S?.encoding,objectMode:!1}),this.path=C,this._gioFile=Lr.File.new_for_path(C),this._start=S?.start??0,this._end=S?.end??1/0,this._pos=this._start,this._positional=S?.start!==void 0,typeof S?.fd==`number`&&(this._ownFd=S.fd,this.fd=S.fd,this._autoCloseFd=S.autoClose!==!1),this.once(`end`,()=>this._release())}_construct(n){if(this._ownFd!==null){this.pending=!1,n(),this.emit(`open`,this._ownFd),this.emit(`ready`);return}this._gioFile.read_async(ft.PRIORITY_DEFAULT,this._cancellable,(S,C)=>{if(this.destroyed){n();return}try{this._inputStream=this._gioFile.read_finish(C),this.pending=!1,this.emit(`open`,0),this.emit(`ready`),this._start>0&&this._inputStream.can_seek()&&this._inputStream.seek(this._start,ft.SeekType.SET,null),n()}catch(S){this._cancellable.is_cancelled()||n(S)}})}_read(n){if(this._lastSize=n,this._reading){this._readAgain=!0;return}this._doRead(n)}_doRead(n){if(this._ownFd!==null){if(this._reading||this.destroyed)return;this._reading=!0,ft.timeout_add(ft.PRIORITY_DEFAULT,0,()=>(this._reading=!1,this.destroyed||this._readThroughFd(n),ft.SOURCE_REMOVE));return}let S=n;if(this._end!==1/0){let C=this._end-this._pos+1;if(C<=0){this.push(null);return}S=Math.min(n,C)}let C=this._inputStream;!C||this.destroyed||(this._reading=!0,C.read_bytes_async(S,ft.PRIORITY_DEFAULT,this._cancellable,(n,S)=>{this._reading=!1;try{let n=C.read_bytes_finish(S).get_data();if(!n||n.length===0){this._readAgain=!1,this.push(null);return}this.bytesRead+=n.length,this._pos+=n.length,this.push($e.from(n)),this._readAgain&&!this._reading&&(this._readAgain=!1,this._doRead(this._lastSize))}catch(n){this._readAgain=!1,this._cancellable.is_cancelled()||this.destroy(n)}}))}_readThroughFd(n){try{let S=n;if(this._end!==1/0){let C=this._end-this._pos+1;if(C<=0){this._readAgain=!1,this.push(null);return}S=Math.min(n,C)}let C=Nl.getInstance(this._ownFd,`read`),N=$e.alloc(S),F=C._readSync(N,0,S,this._positional?this._pos:null);if(F===0){this._readAgain=!1,this.push(null);return}this.bytesRead+=F,this._pos+=F,this.push(N.subarray(0,F))}catch(n){this._readAgain=!1,this.destroy(n)}}_release(){this._inputStream&&=(this._inputStream.close_async(ft.PRIORITY_DEFAULT,null,()=>{}),null),this._releaseFd()}_releaseFd(){if(this._ownFd===null||!this._autoCloseFd)return;let n=this._ownFd;this._ownFd=null,this.fd=null;try{closeSync(n)}catch{}}_destroy(n,S){this._cancellable.cancel(),this._release(),S(n)}}});function openFlagValues(){return isWin32()?el:isDarwin()?$c:Qc}function stringFlagBits(n,S){switch(n){case`r`:return S.O_RDONLY;case`rs`:case`sr`:return S.O_RDONLY|S.O_SYNC;case`r+`:return S.O_RDWR;case`rs+`:case`sr+`:return S.O_RDWR|S.O_SYNC;case`w`:return S.O_TRUNC|S.O_CREAT|S.O_WRONLY;case`wx`:case`xw`:return S.O_TRUNC|S.O_CREAT|S.O_WRONLY|S.O_EXCL;case`w+`:return S.O_TRUNC|S.O_CREAT|S.O_RDWR;case`wx+`:case`xw+`:return S.O_TRUNC|S.O_CREAT|S.O_RDWR|S.O_EXCL;case`a`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY;case`ax`:case`xa`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY|S.O_EXCL;case`as`:case`sa`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY|S.O_SYNC;case`a+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR;case`ax+`:case`xa+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR|S.O_EXCL;case`as+`:case`sa+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR|S.O_SYNC;default:return}}function parseOpenFlags(n){let S=openFlagValues(),C;if(n==null)C=S.O_RDONLY;else if(typeof n==`number`)C=n;else{let N=stringFlagBits(n,S);if(N===void 0){let S=TypeError(`Unknown file open flag: ${n}`);throw S.code=`ERR_INVALID_ARG_VALUE`,S}C=N}let N=C&(S.O_RDONLY|S.O_WRONLY|S.O_RDWR);return{posix:C,readable:N===S.O_RDONLY||N===S.O_RDWR,writable:N===S.O_WRONLY||N===S.O_RDWR,append:(C&S.O_APPEND)!==0,creat:(C&S.O_CREAT)!==0,excl:(C&S.O_CREAT)!==0&&(C&S.O_EXCL)!==0,trunc:(C&S.O_TRUNC)!==0,nofollow:S.O_NOFOLLOW!==0&&(C&S.O_NOFOLLOW)!==0,directory:S.O_DIRECTORY!==0&&(C&S.O_DIRECTORY)!==0}}function normalizeMode(n,S){let C=n??S,N=C;if(typeof C==`string`){if(!/^[0-7]+$/.test(C))throw invalidMode(C);N=parseInt(C,8)}if(typeof N!=`number`)throw modeNotANumber(N);if(!Number.isInteger(N))throw modeOutOfRange(`an integer`,N);if(N<0||N>4294967295)throw modeOutOfRange(`>= 0 && <= 4294967295`,N);return N}function invalidMode(n){let S=TypeError(`The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received '${n}'`);return S.code=`ERR_INVALID_ARG_VALUE`,S}function modeNotANumber(n){let S=n==null?String(n):`type ${typeof n} (${describeValue(n)})`,C=TypeError(`The "mode" argument must be of type number. Received ${S}`);return C.code=`ERR_INVALID_ARG_TYPE`,C}function describeValue(n){try{return typeof n==`object`?Object.prototype.toString.call(n):String(n)}catch{return`<unprintable>`}}function modeOutOfRange(n,S){let C=RangeError(`The value of "mode" is out of range. It must be ${n}. Received ${S}`);return C.code=`ERR_OUT_OF_RANGE`,C}var Qc,$c,el,tl=__esmMin(()=>{Be(),Qc={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:64,O_EXCL:128,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_NONBLOCK:2048,O_DSYNC:4096,O_SYNC:1052672,O_DIRECTORY:65536,O_NOFOLLOW:131072},$c={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_NONBLOCK:4,O_DSYNC:4194304,O_SYNC:128,O_DIRECTORY:1048576,O_NOFOLLOW:256},el={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:256,O_EXCL:1024,O_NOCTTY:0,O_TRUNC:512,O_APPEND:8,O_NONBLOCK:0,O_DSYNC:0,O_SYNC:0,O_DIRECTORY:0,O_NOFOLLOW:0}}),Dirent,nl=__esmMin(()=>{Rr(),Hs(),Dirent=class{name;parentPath;_isFile=!1;_isDirectory=!1;_isBlockDevice=!1;_isCharacterDevice=!1;_isSymbolicLink=!1;_isFIFO=!1;_isSocket=!1;_file;constructor(n,S,C,N){switch(S||=Fs(n),this.name=S,this.parentPath=Ps(n),this._file=Lr.File.new_for_path(n),C??this._file.query_file_type(Lr.FileQueryInfoFlags.NONE,null)){case Lr.FileType.DIRECTORY:this._isDirectory=!0;break;case Lr.FileType.MOUNTABLE:break;case Lr.FileType.REGULAR:this._isFile=!0;break;case Lr.FileType.SYMBOLIC_LINK:case Lr.FileType.SHORTCUT:this._isSymbolicLink=!0;break;case Lr.FileType.SPECIAL:this._classifySpecialFile(n,N);break}}_classifySpecialFile(n,S){try{let C=S?.has_attribute(`unix::mode`)===!0?S:Lr.File.new_for_path(n).query_info(`unix::mode`,Lr.FileQueryInfoFlags.NONE,null),N=C.has_attribute(`unix::mode`)?C.get_attribute_uint32(`unix::mode`):0;if(N===0)return;switch(N&61440){case 24576:this._isBlockDevice=!0;break;case 8192:this._isCharacterDevice=!0;break;case 49152:this._isSocket=!0;break;case 4096:this._isFIFO=!0;break}}catch{}}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isBlockDevice(){return this._isBlockDevice}isCharacterDevice(){return this._isCharacterDevice}isSymbolicLink(){return this._isSymbolicLink}isFIFO(){return this._isFIFO}isSocket(){return this._isSocket}}});function fsError(n,S,C,N){let F=`${n}: ${describe(n)}, ${S}`;C&&(F+=` '${C}'`),N&&(F+=` -> '${N}'`);let I=Error(F);return I.code=n,I.errno=rl[n]??-1,I.syscall=S,C&&(I.path=C),N&&(I.dest=N),I}function describe(n){switch(n){case`ENOENT`:return`no such file or directory`;case`EEXIST`:return`file already exists`;case`EACCES`:return`permission denied`;case`EISDIR`:return`illegal operation on a directory`;case`ENOTDIR`:return`not a directory`;case`EBADF`:return`bad file descriptor`;case`EPERM`:return`operation not permitted`;case`EINVAL`:return`invalid argument`;case`ELOOP`:return`too many symbolic links encountered`;case`ENAMETOOLONG`:return`name too long`;case`EMFILE`:return`too many open files`;case`ENFILE`:return`file table overflow`;case`EROFS`:return`read-only file system`;case`ESPIPE`:return`invalid seek`;case`ENXIO`:return`no such device or address`;default:return`i/o error`}}function hasProcFd(){return il===null&&(il=ft.file_test(`/proc/self/fd`,ft.FileTest.IS_DIR)),il}function fdPath(n){return hasProcFd()?`/proc/self/fd/${n}`:null}function openFd(n,S,C){let N=ft.open(n,S.posix,C);if(N<0)throw classifyOpenFailure(n,S);return N}function closeFd(n){ft.close(n)}function classifyOpenFailure(n,S){let C=nameTooLong(n,`open`);if(C)return C;let N=Lr.File.new_for_path(n),F=null,I=!1;try{let n=N.query_info(`standard::type,standard::symlink-target,unix::mode,access::can-read,access::can-write`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);answered(n)?F=n:I=!0}catch{F=null}if(I)return refusalNotAboutThePath(n,S,N,null);if(F){if(S.excl)return fsError(`EEXIST`,`open`,n);if(F.get_file_type()===Lr.FileType.SYMBOLIC_LINK&&!S.nofollow){let C=walkSymlinkChain(N);if(C===`loop`)return fsError(`ELOOP`,`open`,n);if(C===`too-long`)return fsError(`ENAMETOOLONG`,`open`,n);if(C===`dangling`&&!S.creat)return fsError(`ENOENT`,`open`,n)}return F.get_file_type()===Lr.FileType.DIRECTORY&&S.writable?fsError(`EISDIR`,`open`,n):S.directory&&F.get_file_type()!==Lr.FileType.DIRECTORY?fsError(`ENOTDIR`,`open`,n):refusalNotAboutThePath(n,S,N,F)}if(ancestorIsNotADirectory(N))return fsError(`ENOTDIR`,`open`,n);if(!S.creat)return fsError(`ENOENT`,`open`,n);let H=N.get_parent();if(!H)return fsError(`ENOENT`,`open`,n);try{H.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null)}catch{return fsError(`ENOENT`,`open`,n)}return refusalNotAboutThePath(n,S,N,null)}function ancestorIsNotADirectory(n){for(let S=n.get_parent();S;S=S.get_parent()){let n;try{n=S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null)}catch{continue}return answered(n)?n.get_file_type()!==Lr.FileType.DIRECTORY:!1}return!1}function answered(n){return n!==null&&n.has_attribute(`standard::type`)}function nameTooLong(n,S){let C=new TextEncoder;if(C.encode(n).length>4096)return fsError(`ENAMETOOLONG`,S,n);for(let N of splitPathComponents(n))if(C.encode(N).length>255)return fsError(`ENAMETOOLONG`,S,n);return null}function walkSymlinkChain(n){let S=new TextEncoder,C=n;for(let n=0;n<40;n++){let n;try{n=C.query_info(`standard::type,standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch{return`dangling`}if(!answered(n)||n.get_file_type()!==Lr.FileType.SYMBOLIC_LINK)return`resolved`;let N=n.get_symlink_target();if(!N)return`dangling`;if(S.encode(N).length>4096)return`too-long`;let F=C.get_parent();C=N.startsWith(`/`)?Lr.File.new_for_path(N):F?.resolve_relative_path(N)??Lr.File.new_for_path(N)}return`loop`}function refusalNotAboutThePath(n,S,C,N){let F=ft.open(`/dev/null`,0,0);if(F<0)return fsError(`EMFILE`,`open`,n);ft.close(F);let I=N!==null&&(N.get_attribute_uint32(`unix::mode`)&146)==0;if((S.writable||S.creat)&&!I)try{if(C.query_filesystem_info(`filesystem::readonly`,null).get_attribute_boolean(`filesystem::readonly`))return fsError(`EROFS`,`open`,n)}catch{}return N&¬hingOnTheOtherEnd(S,N)?fsError(`ENXIO`,`open`,n):fsError(`EACCES`,`open`,n)}function nothingOnTheOtherEnd(n,S){if(!S.has_attribute(`unix::mode`))return!1;let C=S.get_attribute_uint32(`unix::mode`)&61440;if(!(C===8192||C===24576||C===4096))return!1;let permits=n=>S.has_attribute(n)&&S.get_attribute_boolean(n);return!(n.readable&&!permits(`access::can-read`)||n.writable&&!permits(`access::can-write`))}function classifyMkdirFailure(n){let S=nameTooLong(n,`mkdir`);if(S)return S;let C=Lr.File.new_for_path(n);try{return answered(C.query_info(`standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null))?fsError(`EEXIST`,`mkdir`,n):fsError(`EACCES`,`mkdir`,n)}catch{}let N=C.get_parent();if(!N)return fsError(`ENOENT`,`mkdir`,n);try{let S=N.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null);if(answered(S)&&S.get_file_type()!==Lr.FileType.DIRECTORY)return fsError(`ENOTDIR`,`mkdir`,n)}catch{return fsError(`ENOENT`,`mkdir`,n)}return fsError(`EACCES`,`mkdir`,n)}function seekHandle(n){let S=al.get(n);return S||(S=ft.IOChannel.unix_new(n),S.set_encoding(null),S.set_buffered(!1),S.set_close_on_unref(!1),al.set(n,S)),S}function input(n){let S=ol.get(n);return S||(S=da.InputStream.new(n,!1),ol.set(n,S)),S}function output(n){let S=sl.get(n);return S||(S=da.OutputStream.new(n,!1),sl.set(n,S)),S}function isSeekableFd(n,S){let C=cl.get(n);return C===void 0&&(C=probeSeekable(n,S),cl.set(n,C)),C}function probeSeekable(n,S){try{let C=Lr.File.new_for_path(fdPath(n)??S).query_info(`unix::mode`,Lr.FileQueryInfoFlags.NONE,null);if(C.has_attribute(`unix::mode`)){let n=C.get_attribute_uint32(`unix::mode`)&61440;if(n===4096||n===49152)return!1}}catch{}try{return seekHandle(n).seek_position(0,ft.SeekType.CUR),!0}catch{return!1}}function seekFd(n,S){seekHandle(n).seek_position(S,ft.SeekType.SET)}function tellFd(n){if(!hasProcFd())return null;try{let[S,C]=ft.file_get_contents(`/proc/self/fdinfo/${n}`);if(!S)return null;let N=/^pos:\s*(\d+)/m.exec(new TextDecoder().decode(C));return N?Number(N[1]):null}catch{return null}}function readFd(n,S){return S<=0?new Uint8Array:input(n).read_bytes(S,null).get_data()??new Uint8Array}function writeFd(n,S){if(S.length===0)return 0;let[,C]=output(n).write_all(S,null);return C}function fsyncFd(n){output(n).flush(null),ft.fsync(n)}function releaseFd(n){let S=sl.get(n);if(S)try{S.flush(null)}catch{}al.delete(n),ol.delete(n),sl.delete(n),cl.delete(n)}function sizeOfFd(n,S){let C=fdPath(n)??S,N=Lr.File.new_for_path(C).query_info(`standard::size`,Lr.FileQueryInfoFlags.NONE,null);return Number(N.get_size())}function truncateFd(n,S,C){let N=Lr.File.new_for_path(fdPath(n)??C),F;try{let n=N.append_to(Lr.FileCreateFlags.NONE,null);try{n.truncate(S,null)}finally{n.close(null)}return}catch(n){F=n}try{let n=N.open_readwrite(null);try{n.get_output_stream().truncate(S,null)}finally{n.close(null)}return}catch{}throw createNodeError(F,`ftruncate`,C)}var rl,il,al,ol,sl,cl,ll=__esmMin(()=>{Vc(),pt(),Rr(),Be(),fa(),rl={EPERM:-1,ENOENT:-2,EIO:-5,ENXIO:-6,EBADF:-9,EACCES:-13,EEXIST:-17,ENOTDIR:-20,EISDIR:-21,EINVAL:-22,ENFILE:-23,EMFILE:-24,ETXTBSY:-26,ENOSPC:-28,ESPIPE:-29,EROFS:-30,ENAMETOOLONG:-36,ENOTEMPTY:-39,ELOOP:-40},il=null,al=new Map,ol=new Map,sl=new Map,cl=new Map});function populateFromInfo(n){let S=n.get_attribute_uint64(`time::access`),C=n.get_attribute_uint32(`time::access-usec`)||0,N=n.get_attribute_uint64(`time::modified`),F=n.get_attribute_uint32(`time::modified-usec`)||0,I=n.get_attribute_uint64(`time::changed`),H=n.get_attribute_uint32(`time::changed-usec`)||0,W=n.get_attribute_uint64(`time::created`),q=n.get_attribute_uint32(`time::created-usec`)||0,Y=S*1e3+C/1e3,X=N*1e3+F/1e3,Z=I?I*1e3+H/1e3:X,te=W?W*1e3+q/1e3:Z;return{dev:n.get_attribute_uint32(`unix::device`)||0,ino:Number(n.get_attribute_uint64(`unix::inode`)||0),mode:n.get_attribute_uint32(`unix::mode`)||0,nlink:n.get_attribute_uint32(`unix::nlink`)||0,uid:n.get_attribute_uint32(`unix::uid`)||0,gid:n.get_attribute_uint32(`unix::gid`)||0,rdev:n.get_attribute_uint32(`unix::rdev`)||0,size:Number(n.get_size()||0),blksize:n.get_attribute_uint32(`unix::block-size`)||4096,blocks:Number(n.get_attribute_uint64(`unix::blocks`)||0),atimeMs:Y,mtimeMs:X,ctimeMs:Z,birthtimeMs:te,atime:new Date(Y),mtime:new Date(X),ctime:new Date(Z),birthtime:new Date(te)}}function statsFrom(n,S,C,N){if(!answered(n))throw fsError(`EACCES`,C,S);return N?new BigIntStats(n,S):new Stats(n,S)}var ul,Stats,BigIntStats,dl=__esmMin(()=>{nl(),ll(),Rr(),Hs(),ul=`standard::*,time::*,unix::*`,Stats=class extends Dirent{dev;ino;mode;nlink;uid;gid;rdev;size;blksize;blocks;atimeMs;mtimeMs;ctimeMs;birthtimeMs;atime;mtime;ctime;birthtime;_info;constructor(n,S,C){let N,F;n instanceof Lr.FileInfo?(N=n,F=S.toString(),C||=Fs(F)):(F=n.toString(),typeof S==`string`&&(C=S),C||=Fs(F),N=Lr.File.new_for_path(F).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)),super(F,C,N.get_file_type(),N),this._info=N;let I=populateFromInfo(N);this.dev=I.dev,this.ino=I.ino,this.mode=I.mode,this.nlink=I.nlink,this.uid=I.uid,this.gid=I.gid,this.rdev=I.rdev,this.size=I.size,this.blksize=I.blksize,this.blocks=I.blocks,this.atimeMs=I.atimeMs,this.mtimeMs=I.mtimeMs,this.ctimeMs=I.ctimeMs,this.birthtimeMs=I.birthtimeMs,this.atime=I.atime,this.mtime=I.mtime,this.ctime=I.ctime,this.birthtime=I.birthtime}},BigIntStats=class extends Dirent{dev;ino;mode;nlink;uid;gid;rdev;size;blksize;blocks;atimeMs;mtimeMs;ctimeMs;birthtimeMs;atimeNs;mtimeNs;ctimeNs;birthtimeNs;atime;mtime;ctime;birthtime;_info;constructor(n,S,C){let N,F;n instanceof Lr.FileInfo?(N=n,F=S.toString(),C||=Fs(F)):(F=n.toString(),typeof S==`string`&&(C=S),C||=Fs(F),N=Lr.File.new_for_path(F).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)),super(F,C,N.get_file_type(),N),this._info=N;let I=populateFromInfo(N);this.dev=BigInt(I.dev),this.ino=BigInt(I.ino),this.mode=BigInt(I.mode),this.nlink=BigInt(I.nlink),this.uid=BigInt(I.uid),this.gid=BigInt(I.gid),this.rdev=BigInt(I.rdev),this.size=BigInt(I.size),this.blksize=BigInt(I.blksize),this.blocks=BigInt(I.blocks),this.atimeMs=BigInt(Math.trunc(I.atimeMs)),this.mtimeMs=BigInt(Math.trunc(I.mtimeMs)),this.ctimeMs=BigInt(Math.trunc(I.ctimeMs)),this.birthtimeMs=BigInt(Math.trunc(I.birthtimeMs)),this.atimeNs=this.atimeMs*1000000n,this.mtimeNs=this.mtimeMs*1000000n,this.ctimeNs=this.ctimeMs*1000000n,this.birthtimeNs=this.birthtimeMs*1000000n,this.atime=I.atime,this.mtime=I.mtime,this.ctime=I.ctime,this.birthtime=I.birthtime}}});function statSync(n,S){let C=normalizePath(n);try{return statsFrom(Lr.File.new_for_path(C).query_info(ul,Lr.FileQueryInfoFlags.NONE,null),C,`stat`,S?.bigint)}catch(n){if(S?.throwIfNoEntry===!1&&isNotFoundError(n))return;throw createNodeError(n,`stat`,C)}}function lstatSync(n,S){let C=normalizePath(n);try{return statsFrom(Lr.File.new_for_path(C).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null),C,`lstat`,S?.bigint)}catch(n){if(S?.throwIfNoEntry===!1&&isNotFoundError(n))return;throw createNodeError(n,`lstat`,C)}}function readdirSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C).enumerate_children(`standard::name,standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null),F=[];try{let n=N.next_file(null);for(;n!==null;)F.push({name:n.get_name(),type:n.get_file_type()}),n=N.next_file(null)}finally{try{N.close(null)}catch{}}let I=[];for(let n of F){let N=js(C,n.name);if(S?.withFileTypes?I.push(new Dirent(N,n.name,n.type)):I.push(n.name),S?.recursive&&n.type===Lr.FileType.DIRECTORY){let C=readdirSync(N,S);for(let S of C)typeof S==`string`?I.push(js(n.name,S)):I.push(S)}}return I}function realpathSync(n){let S=normalizePath(n);return resolveEveryComponent(Lr.File.new_for_path(S),{left:40},S)}function resolveEveryComponent(n,S,C){let N=n.get_parent();return expandSymlinks(N===null?n:Lr.File.new_for_path(resolveEveryComponent(N,S,C)).get_child(n.get_basename()),S,C)}function expandSymlinks(n,S,C){let N=n;for(;;){let n=N.query_info(`standard::is-symlink,standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);if(!n.get_is_symlink())return N.get_path();if(--S.left<0)throw Error(`ELOOP: too many levels of symbolic links, realpath '${C}'`);let F=n.get_symlink_target(),I=N.get_parent(),H=ft.path_is_absolute(F)?Lr.File.new_for_path(F):(I??N).resolve_relative_path(F);N=Lr.File.new_for_path(resolveEveryComponent(H,S,C))}}function symlinkSync(n,S,C){let N=normalizePath(S),F=normalizePath(n);Lr.File.new_for_path(N).make_symbolic_link(F,null)}function readFileSync(n,S={encoding:null,flag:`r`}){if(n instanceof Nl&&(n=n.fd),typeof n==`number`&&isStdFd(n))return encodeUint8Array(getEncodingFromOptions(S,`buffer`),readStdFdAll(n));if(typeof n==`number`)return encodeUint8Array(getEncodingFromOptions(S,`buffer`),Nl.getInstance(n,`read`)._readToEndSync());let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let[n,F]=N.load_contents(null);if(!n)throw createNodeError(Error(`failed to read file`),`read`,C);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),F)}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`read`,C)}}function mkdirSync(n,S){let C=!1,N;S!=null&&(typeof S==`object`?(S.recursive&&(C=S.recursive),S.mode!==void 0&&(N=S.mode)):N=S),n=normalizePath(n);let F=normalizeMode(N,511);if(C)return mkdirSyncRecursive(n,F);mkdirWithMode(n,F)}function mkdirWithMode(n,S){if(ft.mkdir(n,S)!==0)throw classifyMkdirFailure(n)}function mkdirSyncRecursive(n,S){if(ft.mkdir(n,S)===0)return n;let C=classifyMkdirFailure(n);if(C.code===`EEXIST`){if(ft.file_test(n,ft.FileTest.IS_DIR))return;throw C}if(C.code!==`ENOENT`)throw C;let N=js(n,`..`),F=Lr.File.new_for_path(N).get_path();if(F===n)throw C;let I=mkdirSyncRecursive(F,S);return mkdirWithMode(n,S),I??n}function rmdirSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{if(N.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()!==Lr.FileType.DIRECTORY)throw createNodeError(Object.assign(Error(),{code:4}),`rmdir`,C);if(N.enumerate_children(`standard::name`,Lr.FileQueryInfoFlags.NONE,null).next_file(null)!==null)throw createNodeError(Object.assign(Error(),{code:5}),`rmdir`,C);N.delete(null)}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`rmdir`,C)}}function unlinkSync(n){let S=normalizePath(n),C=Lr.File.new_for_path(S);try{C.delete(null)}catch(n){throw createNodeError(n,`unlink`,S)}}function writeWholeFile(n,S,C,N){let F=getEncodingFromOptions(C,`utf8`),I=typeof C==`object`&&C?C:{},H=typeof S==`string`?$e.from(S,F||`utf8`):S;if(typeof n==`number`||n instanceof Nl){if(typeof n==`number`&&isStdFd(n)){writeStdFdSync(n,H);return}Nl.getInstance(n,`write`)._writeSync(H,null);return}let W=new Nl({path:normalizePath(n),flags:I.flag??N,mode:I.mode??438});try{W._writeSync(H,null)}finally{W._closeSync()}}function writeFileSync(n,S,C){writeWholeFile(n,S,C??null,`w`)}function renameSync(n,S){let C=normalizePath(n),N=normalizePath(S),F=Lr.File.new_for_path(C),I=Lr.File.new_for_path(N);try{F.move(I,Lr.FileCopyFlags.OVERWRITE,null,null)}catch(n){throw createNodeError(n,`rename`,C,N)}}function copyFileSync(n,S,C){let N=normalizePath(n),F=normalizePath(S),I=Lr.File.new_for_path(N),H=Lr.File.new_for_path(F),W=Lr.FileCopyFlags.NONE;C&&!(C&1)?W=Lr.FileCopyFlags.OVERWRITE:C||(W=Lr.FileCopyFlags.OVERWRITE);try{I.copy(H,W,null,null)}catch(n){throw createNodeError(n,`copyfile`,N,F)}stripPrivilegeBitsAfterCopy(H,N,F)}function stripPrivilegeBitsAfterCopy(n,S,C){try{let S=n.query_info(`unix::mode,standard::size`,Lr.FileQueryInfoFlags.NONE,null);if(S.get_size()===0)return;let C=S.get_attribute_uint32(`unix::mode`),N=C&-2049;if((isDarwin()||C&8)&&(N&=-1025),N===C)return;n.set_attribute_uint32(`unix::mode`,N,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`copyfile`,S,C)}}function accessSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.query_info(`access::*`,Lr.FileQueryInfoFlags.NONE,null);if(S!==void 0&&S!==0){let N={code:14,message:`permission denied, access '${C}'`};if(S&4&&!n.get_attribute_boolean(`access::can-read`)||S&2&&!n.get_attribute_boolean(`access::can-write`)||S&1&&!n.get_attribute_boolean(`access::can-execute`))throw createNodeError(N,`access`,C)}}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`access`,C)}}function appendFileSync(n,S,C){writeWholeFile(n,S,C??null,`a`)}function readlinkSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.query_info(`standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null).get_symlink_target();if(!n)throw Object.assign(Error(`EINVAL: invalid argument, readlink '${C}'`),{code:`EINVAL`,errno:-22,syscall:`readlink`,path:C});return(typeof S==`string`?S:S?.encoding)===`buffer`?$e.from(n):n}catch(n){throw typeof n.code==`string`?n:createNodeError(n,`readlink`,C)}}function linkSync(n,S){let C=normalizePath(n),N=normalizePath(S);if(Lr.File.new_for_path(C).query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)===Lr.FileType.UNKNOWN)throw Object.assign(Error(`ENOENT: no such file or directory, link '${C}' -> '${N}'`),{code:`ENOENT`,errno:-2,syscall:`link`,path:C,dest:N});if(Lr.File.new_for_path(N).query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)!==Lr.FileType.UNKNOWN)throw Object.assign(Error(`EEXIST: file already exists, link '${C}' -> '${N}'`),{code:`EEXIST`,errno:-17,syscall:`link`,path:C,dest:N});let F=``;try{let[,,n,S]=ft.spawn_sync(null,[`ln`,`--`,C,N],null,ft.SpawnFlags.SEARCH_PATH,null);if(F=n?new TextDecoder().decode(n).trim():``,!ft.spawn_check_wait_status(S))throw Error(`ln exited non-zero (${S})`);return}catch(n){throw F===``&&n instanceof Error&&(F=n.message),Object.assign(Error(`EPERM: operation not permitted, link '${C}' -> '${N}'`+(F?` (${F})`:``)),{code:`EPERM`,errno:-1,syscall:`link`,path:C,dest:N})}}function truncateSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.open_readwrite(null);try{n.get_output_stream().truncate(Math.max(0,S??0),null)}finally{n.close(null)}}catch(n){throw createNodeError(n,`truncate`,C)}}function chmodSync(n,S){let C=normalizePath(n),N=normalizeMode(S);try{Lr.File.new_for_path(C).set_attribute_uint32(`unix::mode`,N,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`chmod`,C)}}function chownSync(n,S,C){let N=normalizePath(n);try{let n=Lr.File.new_for_path(N),F=new Lr.FileInfo;S!==-1&&F.set_attribute_uint32(`unix::uid`,S),C!==-1&&F.set_attribute_uint32(`unix::gid`,C),n.set_attributes_from_info(F,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`chown`,N)}}function watch(n,S,C){return typeof S==`function`&&(C=S,S=void 0),new FSWatcher(normalizePath(n),S,C)}function openSync(n,S,C){return new Nl({path:n,flags:S,mode:C})}function mkdtempSync(n,S){let C=getEncodingFromOptions(S),N=mkdtempAt(n);return C===`buffer`?$e.from(N):decode(N,C)}function mkdtempAt(n){for(let S=0;S<64;S++){let S=n+randomName();if(ft.mkdir(S,448)===0)return S;let C=classifyMkdirFailure(S);if(C.code!==`EEXIST`)throw C.syscall=`mkdtemp`,C}throw fsError(`EEXIST`,`mkdtemp`,n+`XXXXXX`)}function rmSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C),F=S?.recursive||!1,I=S?.force||!1,H;try{H=N.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}if(H===Lr.FileType.SYMBOLIC_LINK){try{N.delete(null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}return}if(H===Lr.FileType.DIRECTORY){let N=readdirSync(n);if(!F&&N.length)throw createNodeError(Object.assign(Error(),{code:5}),`rm`,n);for(let n of N)rmSync(js(C,n),S)}try{N.delete(null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}}var fl=__esmMin(()=>{Xc(),Bc(),Vc(),Wc(),Yc(),tl(),nl(),ll(),dl(),Pl(),pt(),Rr(),Hs(),lt(),va(),Be(),realpathSync.native=realpathSync});function makeEEXIST(n){let S=Error(`ERR_FS_CP_EEXIST: file already exists, copyfile '${n}'`);return S.code=`ERR_FS_CP_EEXIST`,S.syscall=`copyfile`,S.path=n,S}function makeEISDIR(n){let S=Error(`ERR_FS_EISDIR: illegal operation on a directory, copyfile '${n}'`);return S.code=`ERR_FS_EISDIR`,S.syscall=`copyfile`,S.path=n,S}function makeENOTDIR(n,S){let C=Error(`ENOTDIR: not a directory, copyfile '${n}' -> '${S}'`);return C.code=`ENOTDIR`,C.syscall=`copyfile`,C.path=n,C.dest=S,C}function makeSYMLINKLOOP(n,S){let C=Error(`ELOOP: too many levels of symbolic links, copyfile '${n}' -> '${S}'`);return C.code=`ELOOP`,C.syscall=`copyfile`,C.path=n,C.dest=S,C}function queryCopyFlags(n){let S=n.force??!0,C=Lr.FileCopyFlags.NONE;return S&&(C|=Lr.FileCopyFlags.OVERWRITE),n.preserveTimestamps&&(C|=Lr.FileCopyFlags.TARGET_DEFAULT_MODIFIED_TIME),n.dereference||(C|=Lr.FileCopyFlags.NOFOLLOW_SYMLINKS),C}function copyOneSyncFile(n,S,C,N,F){let I=F.force??!0;try{if(S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()===Lr.FileType.DIRECTORY)throw makeENOTDIR(C,N);if(!I){if(F.errorOnExist)throw makeEEXIST(N);return}}catch(n){if(typeof n.code==`string`)throw n}let H=queryCopyFlags(F);try{n.copy(S,H,null,null)}catch(n){throw createNodeError(n,`copyfile`,C,N)}}function cpOneDirSync(n,S,C,N,F){let I=C.endsWith(`/`)?``:`/`;if(N.startsWith(C+I)&&N!==C)throw makeSYMLINKLOOP(C,N);if(S.query_exists(null))try{if(S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()!==Lr.FileType.DIRECTORY)throw makeENOTDIR(N,C)}catch(n){if(typeof n.code==`string`)throw n}else try{S.make_directory_with_parents(null)}catch(n){throw createNodeError(n,`mkdir`,N)}let H;try{H=n.enumerate_children(`standard::name,standard::type,standard::is-symlink`,F.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){throw createNodeError(n,`scandir`,C)}let W=H.next_file(null);for(;W!==null;){let n=W.get_name(),S=js(C,n),I=js(N,n),q=F.filter;if(q&&!q(S,I)){W=H.next_file(null);continue}cpSyncInternal(S,I,F),W=H.next_file(null)}}function cpSyncInternal(n,S,C){let N=Lr.File.new_for_path(n),F=Lr.File.new_for_path(S),I;try{I=N.query_info(`standard::type,standard::is-symlink`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`stat`,n)}if(I.get_file_type()===Lr.FileType.DIRECTORY){if(!C.recursive)throw makeEISDIR(n);cpOneDirSync(N,F,n,S,C)}else copyOneSyncFile(N,F,n,S,C)}function cpSync(n,S,C){let N=normalizePath(n),F=normalizePath(S),I=C??{},H=Lr.File.new_for_path(N),W=I.filter;if(!(W&&!W(N,F))){try{if(H.query_info(`standard::type`,I.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null).get_file_type()===Lr.FileType.DIRECTORY&&!I.recursive)throw makeEISDIR(N)}catch(n){throw typeof n.code==`string`?n:createNodeError(n,`stat`,N)}cpSyncInternal(N,F,I)}}function cp(n,S,C,N){let F,I;typeof C==`function`?(I=C,F={}):(I=requireCallback(N),F=C);let H=F.filter;if(H){Promise.resolve(H(normalizePath(n),normalizePath(S))).then(C=>{if(!C){I(null);return}try{cpPromises(n,S,F).then(()=>I(null)).catch(I)}catch(n){I(n)}}).catch(I);return}Promise.resolve().then(()=>{try{cpSync(n,S,F),I(null)}catch(n){I(n)}})}async function cpPromisesDir(n,S,C){let N=n.endsWith(`/`)?``:`/`;if(S.startsWith(n+N)&&S!==n)throw makeSYMLINKLOOP(n,S);let F=Lr.File.new_for_path(S);if(!F.query_exists(null))try{F.make_directory_with_parents(null)}catch(n){throw createNodeError(n,`mkdir`,S)}let I=Lr.File.new_for_path(n),H;try{H=I.enumerate_children(`standard::name,standard::type`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`scandir`,n)}let W=H.next_file(null);for(;W!==null;){let N=W.get_name(),F=js(n,N),I=js(S,N),q=C.filter;if(q&&!await Promise.resolve(q(F,I))){W=H.next_file(null);continue}await cpPromises(F,I,C),W=H.next_file(null)}}async function cpPromises(n,S,C={}){let N=normalizePath(n),F=normalizePath(S),I=Lr.File.new_for_path(N),H;try{H=I.query_info(`standard::type`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){throw createNodeError(n,`stat`,N)}if(H.get_file_type()===Lr.FileType.DIRECTORY){if(!C.recursive)throw makeEISDIR(N);await cpPromisesDir(N,F,C)}else copyOneSyncFile(I,Lr.File.new_for_path(F),N,F,C)}var pl=__esmMin(()=>{Bc(),Vc(),Rr(),Hs()});function _openDir(n){let S=Lr.File.new_for_path(n),C;try{C=S.enumerate_children(ml,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`opendir`,n)}return new Dir(n,C)}function opendirSync(n){return _openDir(normalizePath(n))}function opendir(n,S,C){let N;if(N=typeof S==`function`?S:requireCallback(C,`callback`),typeof N!=`function`)throw TypeError(`The "callback" argument must be of type function`);Promise.resolve().then(()=>{try{let S=opendirSync(n);N(null,S)}catch(n){N(n,null)}})}async function opendirAsync(n,S){return new Promise((S,C)=>{let N=normalizePath(n),F=Lr.File.new_for_path(N);F.enumerate_children_async(ml,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,ft.PRIORITY_DEFAULT,null,(n,I)=>{try{let n=F.enumerate_children_finish(I);S(new Dir(N,n))}catch(n){C(createNodeError(n,`opendir`,N))}})})}var ml,Dir,hl=__esmMin(()=>{Bc(),Vc(),nl(),pt(),Rr(),ml=`standard::name,standard::type,standard::is-symlink,standard::size,standard::symlink-target,unix::uid,unix::gid,unix::mode,time::modified,time::access,time::created`,Dir=class{path;_enumerator;_closed=!1;constructor(n,S){this.path=n,this._enumerator=S}_assertOpen(){if(this._closed){let n=Error(`Directory handle was closed`);throw n.code=`ERR_DIR_CLOSED`,n}}readSync(){this._assertOpen();try{let n=this._enumerator.next_file(null);if(n===null)return null;let S=n.get_name(),C=n.get_file_type();return new Dirent(this.path.endsWith(`/`)?this.path+S:this.path+`/`+S,S,C)}catch(n){throw createNodeError(n,`readdir`,this.path)}}read(n){if(n!==void 0){if(typeof n!=`function`)throw TypeError(`The "callback" argument must be of type function`);try{this._assertOpen();let S=this.readSync();Promise.resolve().then(()=>n(null,S))}catch(S){Promise.resolve().then(()=>n(S,null))}return}return new Promise((n,S)=>{try{this._assertOpen(),n(this.readSync())}catch(n){S(n)}})}closeSync(){this._assertOpen(),this._closed=!0;try{this._enumerator.close(null)}catch{}this._enumerator=null}close(n){if(n!==void 0){if(typeof n!=`function`)throw TypeError(`The "callback" argument must be of type function`);try{this.closeSync(),Promise.resolve().then(()=>n(null))}catch(S){Promise.resolve().then(()=>n(S))}return}return new Promise((n,S)=>{try{this.closeSync(),n()}catch(n){S(n)}})}async*[Symbol.asyncIterator](){try{for(;;){let n=await this.read();if(n===null)break;yield n}}finally{this._closed||await this.close()}}}});function segmentToRegexSrc(n){let S=/^([!*+?@])\((.+)\)$/.exec(n);if(S){let[,n,C]=S,N=C.split(`|`).map(n=>segmentToRegexSrc(n)),F=`(?:`+N.join(`|`)+`)`;switch(n){case`!`:return`(?!(?:`+N.join(`|`)+`))[^/]*`;case`*`:return F+`*`;case`+`:return F+`+`;case`?`:return F+`?`;case`@`:return F}}let C=``,N=0;for(;N<n.length;){let S=n[N];if(S===`*`){C+=`[^/]*`,N++;continue}if(S===`?`){C+=`[^/]`,N++;continue}if(S===`[`){let S=n.indexOf(`]`,N+1);if(S===-1){C+=`\\[`,N++;continue}C+=n.slice(N,S+1),N=S+1;continue}if(S===`{`){let S=n.indexOf(`}`,N+1);if(S===-1){C+=`\\{`,N++;continue}let F=n.slice(N+1,S).split(`,`).map(n=>segmentToRegexSrc(n.trim()));C+=`(?:`+F.join(`|`)+`)`,N=S+1;continue}`.+^$|()[]{}`.includes(S)?C+=`\\`+S:C+=S,N++}return C}function globToRegex$2(n){n=n.replace(/\/+/g,`/`).replace(/^\.\//,``);let S=n.split(`/`),C=[];for(let n=0;n<S.length;n++){let N=S[n],F=n===S.length-1;N===`**`?F?C.length>0&&C[C.length-1]===`/`?(C.pop(),C.push(`(?:/.+)?`)):C.push(`(?:.+)?`):C.push(`(?:[^/]+/)*`):(C.push(segmentToRegexSrc(N)),F||C.push(`/`))}return RegExp(`^(?:`+C.join(``)+`)$`)}function buildExcludePredicate(n){if(!n)return null;if(typeof n==`function`)return n;let S=(Array.isArray(n)?n:[n]).map(n=>globToRegex$2(n));return n=>S.some(S=>S.test(n))}function matchAll(n,S,C){let N=globToRegex$2(n),F=buildExcludePredicate(C),I;try{I=readdirSync(S,{recursive:!0})}catch{return[]}let H=[`.`,...I],W=[];for(let n of H){let S=n.replace(/\\/g,`/`);N.test(S)&&(F&&F(S)||W.push(n))}return W}function globSync(n,S){let C=Array.isArray(n)?n:[n],N=S?.cwd?normalizePath(S.cwd):globalThis.process?.cwd?.()??`/`,F=S?.exclude,I=new Set,H=[];for(let n of C)for(let S of matchAll(n,N,F))I.has(S)||(I.add(S),H.push(S));return H}function glob(n,S,C){let N,F;typeof S==`function`?(F=S,N={}):(F=requireCallback(C),N=S||{}),Promise.resolve().then(()=>{try{let S=globSync(n,N);F(null,S)}catch(n){F(n,[])}})}async function*globAsync(n,S){let C=globSync(n,S);for(let n of C)yield n}var gl=__esmMin(()=>{Bc(),Vc(),fl(),__name$1(globToRegex$2,`globToRegex`)});function buildStatFs(n){let S=Number(n.get_attribute_uint64(`filesystem::size`)??0),C=Number(n.get_attribute_uint64(`filesystem::free`)??0),N=Math.floor(S/vl),F=Math.floor(C/vl);return{type:0,bsize:vl,blocks:N,bfree:F,bavail:F,files:0,ffree:0}}function buildBigIntStatFs(n){let S=BigInt(n.get_attribute_uint64(`filesystem::size`)??0),C=BigInt(n.get_attribute_uint64(`filesystem::free`)??0),N=BigInt(vl),F=S/N,I=C/N;return{type:0n,bsize:N,blocks:F,bfree:I,bavail:I,files:0n,ffree:0n}}function statfsSync(n,S){let C=Lr.File.new_for_path(normalizePath(n)).query_filesystem_info(_l,null);return S?.bigint===!0?buildBigIntStatFs(C):buildStatFs(C)}function queryFsInfoAsync(n,S){return new Promise((C,N)=>{let F=Lr.File.new_for_path(normalizePath(n));F.query_filesystem_info_async(_l,ft.PRIORITY_DEFAULT,null,(n,I)=>{try{let n=F.query_filesystem_info_finish(I);C(S?buildBigIntStatFs(n):buildStatFs(n))}catch(n){N(n)}})})}function statfs(n,S,C){let N=typeof S==`function`?S:requireCallback(C);queryFsInfoAsync(n,(typeof S==`function`?{}:S)?.bigint===!0).then(n=>N(null,n),n=>N(n,null))}async function statfsAsync(n,S){return queryFsInfoAsync(n,S?.bigint===!0)}var _l,vl,yl=__esmMin(()=>{Bc(),Vc(),pt(),Rr(),_l=[`filesystem::size`,`filesystem::free`].join(`,`),vl=4096}),bl=__exportAll$4({access:()=>access$1,appendFile:()=>appendFile$1,chmod:()=>chmod$1,chown:()=>chown$1,copyFile:()=>copyFile$1,cp:()=>cpPromises,default:()=>Sl,fchmod:()=>fchmodAsync,fchown:()=>fchownAsync,fdatasync:()=>fdatasyncAsync,fstat:()=>fstatAsync,fsync:()=>fsyncAsync,ftruncate:()=>ftruncateAsync,futimes:()=>futimesAsync,glob:()=>globAsync,lchmod:()=>lchmodAsync,lchown:()=>lchownAsync,link:()=>link$1,lstat:()=>lstat$1,lutimes:()=>lutimesAsync,mkdir:()=>mkdir$1,mkdtemp:()=>mkdtemp$1,open:()=>open$2,openAsBlob:()=>openAsBlob,opendir:()=>opendirAsync,promises_exports:()=>xl,readFile:()=>readFile$1,readdir:()=>readdir$1,readlink:()=>readlink$1,readv:()=>readvAsync,realpath:()=>realpath$1,rename:()=>rename$1,rm:()=>rm$1,rmdir:()=>rmdir$1,stat:()=>stat$1,statfs:()=>statfsAsync,symlink:()=>symlink$1,truncate:()=>truncate$1,unlink:()=>unlink$1,utimes:()=>utimesAsync,watch:()=>watchAsync,write:()=>write$1,writeFile:()=>writeFile$1,writev:()=>writevAsync});async function mkdir$1(n,S){return mkdirSync(normalizePath(n),S)}async function readFile$1(n,S={encoding:null,flag:`r`}){if(n instanceof Nl||typeof n==`number`){let C=Nl.getInstance(n,`read`);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),C._readToEndSync())}let C=normalizePath(n),N=Lr.File.new_for_path(C),F,I;try{[F,I]=await new Promise((n,S)=>{N.load_contents_async(null,(C,F)=>{try{n(N.load_contents_finish(F))}catch(n){S(n)}})})}catch(n){throw createNodeError(n,`open`,C)}if(!F)throw createNodeError(Error(`failed to read file`),`open`,C);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),I)}async function mkdtemp$1(n,S){let C=getEncodingFromOptions(S);return decode(mkdtempAt(n),C)}async function writeFile$1(n,S,C){writeFileSync(n,typeof S==`string`||S instanceof Uint8Array?S:String(S),C??null)}async function rmdir$1(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);if((await new Promise((n,S)=>{N.query_info_async(`standard::type`,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(F,I)=>{try{n(N.query_info_finish(I))}catch(n){S(createNodeError(n,`rmdir`,C))}})})).get_file_type()!==Lr.FileType.DIRECTORY)throw createNodeError(Object.assign(Error(),{code:4}),`rmdir`,C);if((await new Promise((n,S)=>{N.enumerate_children_async(`standard::name`,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(F,I)=>{try{n(N.enumerate_children_finish(I))}catch(n){S(createNodeError(n,`rmdir`,C))}})})).next_file(null)!==null)throw createNodeError(Object.assign(Error(),{code:5}),`rmdir`,C);await new Promise((n,S)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,I)=>{try{N.delete_finish(I),n()}catch(n){S(createNodeError(n,`rmdir`,C))}})})}async function unlink$1(n){let S=normalizePath(n),C=Lr.File.new_for_path(S);await new Promise((n,N)=>{C.delete_async(ft.PRIORITY_DEFAULT,null,(F,I)=>{try{C.delete_finish(I),n()}catch(n){N(createNodeError(n,`unlink`,S))}})})}async function open$2(n,S,C){return new Nl({path:n,flags:S,mode:C})}async function write$1(n,S,C,N,F){return typeof S==`string`?_writeStr(n,S,C,N):_writeBuf(n,S,C,N,F)}async function _writeBuf(n,S,C,N,F){return{bytesWritten:(await Nl.getInstance(n,`write`).write(S,C,N,F)).bytesWritten,buffer:S}}async function _writeStr(n,S,C,N){return{bytesWritten:(await Nl.getInstance(n,`write`).write(S,C,N)).bytesWritten,buffer:S}}function queryInfoAsync(n,S,C,N){let F=normalizePath(n);return new Promise((n,I)=>{let H=Lr.File.new_for_path(F);H.query_info_async(ul,S,ft.PRIORITY_DEFAULT,null,(S,W)=>{try{n(statsFrom(H.query_info_finish(W),F,C,N?.bigint))}catch(n){I(createNodeError(n,C,F))}})})}async function stat$1(n,S){return queryInfoAsync(n,Lr.FileQueryInfoFlags.NONE,`stat`,S)}async function lstat$1(n,S){return queryInfoAsync(n,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,`lstat`,S)}async function readdir$1(n,S){try{return readdirSync(n,S)}catch(S){throw createNodeError(S,`scandir`,n)}}async function realpath$1(n){return realpathSync(n)}async function symlink$1(n,S,C){let N=normalizePath(S),F=normalizePath(n);return new Promise((n,S)=>{let C=Lr.File.new_for_path(N);C.make_symbolic_link_async(F,ft.PRIORITY_DEFAULT,null,(I,H)=>{try{C.make_symbolic_link_finish(H),n()}catch(n){S(createNodeError(n,`symlink`,F,N))}})})}async function rm$1(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C),F=S?.recursive||!1,I=S?.force||!1,H;try{H=N.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){if(I)return;throw createNodeError(S,`rm`,n)}if(H===Lr.FileType.SYMBOLIC_LINK){await new Promise((S,C)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,H)=>{try{N.delete_finish(H),S()}catch(N){if(I){S();return}C(createNodeError(N,`rm`,n))}})});return}if(H===Lr.FileType.DIRECTORY){let N=await readdir$1(n,{withFileTypes:!0});if(!F&&N.length)throw createNodeError(Object.assign(Error(),{code:5}),`rm`,n);for(let n of N)typeof n!=`string`&&await rm$1(js(C,n.name),S)}await new Promise((S,C)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,H)=>{try{N.delete_finish(H),S()}catch(N){if(I){S();return}C(createNodeError(N,`rm`,n))}})})}async function rename$1(n,S){renameSync(n,S)}async function copyFile$1(n,S,C){copyFileSync(n,S,C)}async function access$1(n,S){accessSync(n,S)}async function appendFile$1(n,S,C){appendFileSync(n,S,C)}async function readlink$1(n,S){return readlinkSync(n,S)}async function truncate$1(n,S){truncateSync(n,S)}async function chmod$1(n,S){chmodSync(n,S)}async function chown$1(n,S,C){chownSync(n,S,C)}async function link$1(n,S){linkSync(n,S)}var xl,Sl,Cl=__esmMin(()=>{zc(),Xc(),Bc(),Vc(),Wc(),Kc(),Fl(),dl(),Pl(),fl(),pl(),hl(),gl(),yl(),pt(),Rr(),Hs(),xl=Rc({access:()=>access$1,appendFile:()=>appendFile$1,chmod:()=>chmod$1,chown:()=>chown$1,copyFile:()=>copyFile$1,cp:()=>cpPromises,default:()=>Sl,fchmod:()=>fchmodAsync,fchown:()=>fchownAsync,fdatasync:()=>fdatasyncAsync,fstat:()=>fstatAsync,fsync:()=>fsyncAsync,ftruncate:()=>ftruncateAsync,futimes:()=>futimesAsync,glob:()=>globAsync,lchmod:()=>lchmodAsync,lchown:()=>lchownAsync,link:()=>link$1,lstat:()=>lstat$1,lutimes:()=>lutimesAsync,mkdir:()=>mkdir$1,mkdtemp:()=>mkdtemp$1,open:()=>open$2,openAsBlob:()=>openAsBlob,opendir:()=>opendirAsync,readFile:()=>readFile$1,readdir:()=>readdir$1,readlink:()=>readlink$1,readv:()=>readvAsync,realpath:()=>realpath$1,rename:()=>rename$1,rm:()=>rm$1,rmdir:()=>rmdir$1,stat:()=>stat$1,statfs:()=>statfsAsync,symlink:()=>symlink$1,truncate:()=>truncate$1,unlink:()=>unlink$1,utimes:()=>utimesAsync,watch:()=>watchAsync,write:()=>write$1,writeFile:()=>writeFile$1,writev:()=>writevAsync}),__name$1(mkdir$1,`mkdir`),__name$1(readFile$1,`readFile`),__name$1(mkdtemp$1,`mkdtemp`),__name$1(writeFile$1,`writeFile`),__name$1(rmdir$1,`rmdir`),__name$1(unlink$1,`unlink`),__name$1(open$2,`open`),__name$1(write$1,`write`),__name$1(stat$1,`stat`),__name$1(lstat$1,`lstat`),__name$1(readdir$1,`readdir`),__name$1(realpath$1,`realpath`),__name$1(symlink$1,`symlink`),__name$1(rm$1,`rm`),__name$1(rename$1,`rename`),__name$1(copyFile$1,`copyFile`),__name$1(access$1,`access`),__name$1(appendFile$1,`appendFile`),__name$1(readlink$1,`readlink`),__name$1(truncate$1,`truncate`),__name$1(chmod$1,`chmod`),__name$1(chown$1,`chown`),__name$1(link$1,`link`),Sl={readFile:readFile$1,mkdir:mkdir$1,mkdtemp:mkdtemp$1,realpath:realpath$1,readdir:readdir$1,writeFile:writeFile$1,rmdir:rmdir$1,unlink:unlink$1,open:open$2,write:write$1,rm:rm$1,lstat:lstat$1,symlink:symlink$1,stat:stat$1,rename:rename$1,copyFile:copyFile$1,access:access$1,appendFile:appendFile$1,readlink:readlink$1,truncate:truncate$1,chmod:chmod$1,chown:chown$1,link:link$1,cp:cpPromises,opendir:opendirAsync,glob:globAsync,watch:watchAsync,statfs:statfsAsync,utimes:utimesAsync,lutimes:lutimesAsync,lchown:lchownAsync,lchmod:lchmodAsync,fstat:fstatAsync,ftruncate:ftruncateAsync,fdatasync:fdatasyncAsync,fsync:fsyncAsync,fchmod:fchmodAsync,fchown:fchownAsync,futimes:futimesAsync,readv:readvAsync,writev:writevAsync,openAsBlob}});function withHandle(n,S,C){try{return Nl.getInstance(n,S)}catch(n){return Promise.resolve().then(()=>C(n)),null}}function parseOptsCb(n,S){return typeof n==`function`?{options:{},callback:n}:{options:n??{},callback:requireCallback(S)}}function statImpl(n,S,C,N,F){let I=normalizePath(n),H=Lr.File.new_for_path(I);H.query_info_async(ul,S,ft.PRIORITY_DEFAULT,null,(n,S)=>{try{F(null,statsFrom(H.query_info_finish(S),I,C,N?.bigint))}catch(n){F(createNodeError(n,C,I))}})}function stat(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);statImpl(n,Lr.FileQueryInfoFlags.NONE,`stat`,N,F)}function lstat(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);statImpl(n,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,`lstat`,N,F)}function readdir(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);Promise.resolve().then(()=>{try{F(null,readdirSync(n,N))}catch(S){F(createNodeError(S,`readdir`,n))}})}function realpath(n,S,C){let{callback:N}=parseOptsCb(S,C);Promise.resolve().then(()=>{try{N(null,realpathSync(n))}catch(n){N(n)}})}function symlink(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);if(typeof F!=`function`)throw TypeError(`Callback must be a function. Received `+typeof F);let I=normalizePath(S),H=normalizePath(n),W=Lr.File.new_for_path(I);W.make_symbolic_link_async(H,ft.PRIORITY_DEFAULT,null,(n,S)=>{try{W.make_symbolic_link_finish(S),F(null)}catch(n){F(createNodeError(n,`symlink`,H,I))}})}function open$1(n,...S){let C,N,F;switch(S.length){case 1:F=S[0];break;case 2:C=S[0],F=S[1];break;case 3:C=S[0],N=S[1],F=S[2];break;default:break}let I=requireCallback(F);open$2(n,C,N).then(n=>{I(null,n.fd)}).catch(n=>{I(n,-1)})}function write(n,S,...C){requireCallback(C[C.length-1]);let N=withHandle(n,`write`,n=>{let N=C[C.length-1];typeof S==`string`?N(n,0,``):N(n,0,$e.from([]))});if(!N)return;if(typeof S==`string`){let n=C.pop(),F=C[0],I=C[1];N.write(S,F,I).then(S=>{n(null,S.bytesWritten,S.buffer)}).catch(S=>{n(S,0,``)});return}let F=C[C.length-1],I=C[0],H=C[1],W=C[2];N.write(S,I,H,W).then(n=>{F(null,n.bytesWritten,n.buffer)}).catch(n=>{F(n,0,$e.from([]))})}function read$1(n,...S){let C=requireCallback(S[S.length-1]),N=withHandle(n,`read`,n=>{typeof C==`function`&&C(n,0,$e.from([]))});if(!N)return;let F,I,H,W;if(!(S.length<=1))if(typeof S[0]==`object`&&!ArrayBuffer.isView(S[0])){let n=S[0];F=n.buffer,I=n.offset,H=n.length,W=n.position}else F=S[0],I=S[1],H=S[2],W=S[3];N.read(F,I,H,W).then(n=>{C(null,n.bytesRead,n.buffer)}).catch(n=>{C(n,0,$e.from([]))})}function close$1(n,S){let done=n=>{typeof S==`function`&&S(n)},C=withHandle(n,`close`,done);C&&C.close().then(()=>done(null)).catch(n=>done(n))}function rm(n,...S){let C={},N=S[S.length-1];S.length>=2&&(C=S[0]),rm$1(n,C).then(()=>{N(null)}).catch(n=>{N(n)})}function rename(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{renameSync(n,S),C(null)}catch(n){C(n)}})}function copyFile(n,S,C,N){let F=typeof C==`function`?0:C,I=typeof C==`function`?C:requireCallback(N);Promise.resolve().then(()=>{try{copyFileSync(n,S,F),I(null)}catch(n){I(n)}})}function access(n,S,C){let N=typeof S==`function`?void 0:S,F=typeof S==`function`?S:requireCallback(C);Promise.resolve().then(()=>{try{accessSync(n,N),F(null)}catch(n){F(n)}})}function appendFile(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N),I=typeof C==`function`?void 0:C;Promise.resolve().then(()=>{try{appendFileSync(n,S,I),F(null)}catch(n){F(n)}})}function readlink(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{N(null,readlinkSync(n,F))}catch(n){N(n,``)}})}function truncate(n,S,C){let N=typeof S==`function`?0:S,F=typeof S==`function`?S:requireCallback(C);Promise.resolve().then(()=>{try{truncateSync(n,N),F(null)}catch(n){F(n)}})}function chmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{chmodSync(n,S),C(null)}catch(n){C(n)}})}function chown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>{try{chownSync(n,S,C),N(null)}catch(n){N(n)}})}function mkdir(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{mkdirSync(n,F),N(null)}catch(n){N(n)}})}function mkdtemp(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{let S;try{S=mkdtempSync(n,F)}catch(n){N(n,void 0);return}N(null,S)})}function rmdir(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{rmdirSync(n,F),N(null)}catch(n){N(n)}})}function readFile(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{let S=typeof F==`string`?{encoding:F,flag:`r`}:{encoding:F?.encoding??null,flag:F?.flag??`r`};N(null,readFileSync(n,S))}catch(n){N(n,null)}})}function writeFile(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N),I=typeof C==`function`?void 0:C;Promise.resolve().then(()=>{try{writeFileSync(n,S,I),F(null)}catch(n){F(n)}})}function link(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{linkSync(n,S),C(null)}catch(n){C(n)}})}function unlink(n,S){requireCallback(S);let C=normalizePath(n);Promise.resolve().then(()=>{ft.unlink(C),S(null)})}var wl=__esmMin(()=>{Bc(),Vc(),dl(),Pl(),fl(),Cl(),pt(),Rr(),lt(),__name$1(open$1,`open`),__name$1(read$1,`read`),__name$1(close$1,`close`)});function toPathIfFileURL(n){return normalizePath(n)}function createWriteStream(n,S){return new WriteStream$1(n,S)}var Tl,El,WriteStream$1,Dl=__esmMin(()=>{Bc(),tl(),wl(),gi(),Tl=Symbol(`kIsPerformingIO`),El=Symbol(`kIoDone`),WriteStream$1=class extends di{static{__name$1(this,`WriteStream`)}close(n,S=null){let done=S=>{typeof n==`function`&&n(S)};if(this.fd===null||!this._autoClose)this.fd=null,done(S);else{let n=this._fdFromHandle;close$1(this.fd,C=>{let N=n&&C?.code===`EBADF`?null:C;done(N||S)}),this.fd=null}}bytesWritten=0;path;pending;fd=null;flags=`w`;mode=438;pos=void 0;_autoClose=!0;_fdFromHandle=!1;[Tl]=!1;constructor(n,S={}){super(S),this.path=toPathIfFileURL(n),S.flags!==void 0&&(this.flags=S.flags),S.mode!==void 0&&(this.mode=normalizeMode(S.mode,438)),S.start!==void 0&&(this.pos=S.start),S.encoding&&this.setDefaultEncoding(S.encoding),typeof S.fd==`number`?(this.fd=S.fd,this._autoClose=S.autoClose??!0,this._fdFromHandle=S.fdFromHandle===!0):S.autoClose!==void 0&&(this._autoClose=S.autoClose),this.pending=this.fd===null}_construct(n){if(this.fd!==null){n(),this.emit(`open`,this.fd),this.emit(`ready`);return}open$1(this.path.toString(),this.flags,this.mode,(S,C)=>{if(S){n(S);return}this.fd=C,this.pending=!1,n(),this.emit(`open`,this.fd),this.emit(`ready`)})}_write(n,S,C){this[Tl]=!0,write(this.fd,n,0,n.length,this.pos??null,(n,S)=>{if(this[Tl]=!1,this.destroyed)return C(n),this.emit(El,n);if(n)return C(n);this.bytesWritten+=S,C()}),this.pos!==void 0&&(this.pos+=n.length)}_destroy(n,S){this[Tl]?this.once(El,C=>this.close(S,n||C)):this.close(S,n)}}});function createInterface$1(n,S,C,N){return typeof n==`object`&&n&&!(`read`in n&&typeof n.read==`function`)?new Interface$1(n):new Interface$1({input:n,output:S,completer:C,terminal:N})}function*emitKeys(n){for(;;){let S=yield,C=S,N=!1,F={sequence:``,name:void 0,ctrl:!1,meta:!1,shift:!1};if(S===`\x1B`&&(N=!0,C+=S=yield,S===`\x1B`&&(C+=S=yield)),N&&(S===`O`||S===`[`)){let n=S,N=0;if(S===`O`)C+=S=yield,S>=`0`&&S<=`9`&&(N=S.charCodeAt(0)-1,C+=S=yield),n+=S;else if(S===`[`){C+=S=yield,S===`[`&&(n+=S,C+=S=yield);let F=C.length-1;S>=`0`&&S<=`9`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=S=yield))),S===`;`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=yield));let I=C.slice(F),H;(H=/^(?:(\d\d?)(?:;(\d))?([~^$])|(\d{3}~))$/.exec(I))?H[4]?n+=H[4]:(n+=H[1]+H[3],N=(parseInt(H[2]??`1`,10)||1)-1):(H=/^((\d;)?(\d))?([A-Za-z])$/.exec(I))?(n+=H[4],N=(parseInt(H[3]??`1`,10)||1)-1):n+=I}switch(F.ctrl=!!(N&4),F.meta=!!(N&10),F.shift=!!(N&1),F.code=n,n){case`[P`:case`OP`:case`[11~`:case`[[A`:F.name=`f1`;break;case`[Q`:case`OQ`:case`[12~`:case`[[B`:F.name=`f2`;break;case`[R`:case`OR`:case`[13~`:case`[[C`:F.name=`f3`;break;case`[S`:case`OS`:case`[14~`:case`[[D`:F.name=`f4`;break;case`[15~`:case`[[E`:F.name=`f5`;break;case`[17~`:F.name=`f6`;break;case`[18~`:F.name=`f7`;break;case`[19~`:F.name=`f8`;break;case`[20~`:F.name=`f9`;break;case`[21~`:F.name=`f10`;break;case`[23~`:F.name=`f11`;break;case`[24~`:F.name=`f12`;break;case`[200~`:F.name=`paste-start`;break;case`[201~`:F.name=`paste-end`;break;case`[A`:case`OA`:F.name=`up`;break;case`[B`:case`OB`:F.name=`down`;break;case`[C`:case`OC`:F.name=`right`;break;case`[D`:case`OD`:F.name=`left`;break;case`[E`:case`OE`:F.name=`clear`;break;case`[F`:case`OF`:F.name=`end`;break;case`[H`:case`OH`:F.name=`home`;break;case`[1~`:F.name=`home`;break;case`[2~`:F.name=`insert`;break;case`[3~`:F.name=`delete`;break;case`[4~`:F.name=`end`;break;case`[5~`:case`[[5~`:F.name=`pageup`;break;case`[6~`:case`[[6~`:F.name=`pagedown`;break;case`[7~`:F.name=`home`;break;case`[8~`:F.name=`end`;break;case`[a`:F.name=`up`,F.shift=!0;break;case`[b`:F.name=`down`,F.shift=!0;break;case`[c`:F.name=`right`,F.shift=!0;break;case`[d`:F.name=`left`,F.shift=!0;break;case`[2$`:F.name=`insert`,F.shift=!0;break;case`[3$`:F.name=`delete`,F.shift=!0;break;case`[5$`:F.name=`pageup`,F.shift=!0;break;case`[6$`:F.name=`pagedown`,F.shift=!0;break;case`[7$`:F.name=`home`,F.shift=!0;break;case`[8$`:F.name=`end`,F.shift=!0;break;case`Oa`:F.name=`up`,F.ctrl=!0;break;case`Ob`:F.name=`down`,F.ctrl=!0;break;case`Oc`:F.name=`right`,F.ctrl=!0;break;case`Od`:F.name=`left`,F.ctrl=!0;break;case`[2^`:F.name=`insert`,F.ctrl=!0;break;case`[3^`:F.name=`delete`,F.ctrl=!0;break;case`[5^`:F.name=`pageup`,F.ctrl=!0;break;case`[6^`:F.name=`pagedown`,F.ctrl=!0;break;case`[7^`:F.name=`home`,F.ctrl=!0;break;case`[8^`:F.name=`end`,F.ctrl=!0;break;case`[Z`:F.name=`tab`,F.shift=!0;break;default:F.name=`undefined`;break}}else S===`\r`?(F.name=`return`,F.meta=N):S===`
|
|
42
|
-
`?(F.name=`enter`,F.meta=N):S===` `?(F.name=`tab`,F.meta=N):S===`\b`||S===``?(F.name=`backspace`,F.meta=N):S===`\x1B`?(F.name=`escape`,F.meta=N):S===` `?(F.name=`space`,F.meta=N):!N&&S<=``?(F.name=String.fromCharCode(S.charCodeAt(0)+97-1),F.ctrl=!0):/^[0-9A-Za-z]$/.test(S)?(F.name=S.toLowerCase(),F.shift=/^[A-Z]$/.test(S),F.meta=N):N&&(F.name=S.length?void 0:`escape`,F.meta=!0);F.sequence=C,C.length!==0&&(F.name!==void 0||N)?n.emit(`keypress`,N?void 0:C,F):C.length===1&&n.emit(`keypress`,C,F)}}function emitKeypressEvents(n,S={}){let C=n;if(C[Al])return;C[Al]=new qt(`utf8`),C[jl]=emitKeys(n),C[jl].next();let N=S.escapeCodeTimeout??500,F,triggerEscape=()=>C[jl].next(``);function onData(S){if(n.listenerCount(`keypress`)>0){let I=C[Al].write(typeof S==`string`?Buffer.from(S):S);if(I){clearTimeout(F);for(let S of I)try{C[jl].next(S),S===`\x1B`&&(F=setTimeout(triggerEscape,N))}catch{C[jl]=emitKeys(n),C[jl].next()}}}else n.removeListener(`data`,onData),delete C[Al],delete C[jl]}n.on(`data`,onData)}var Ol,Interface$1,kl,Al,jl,Ml=__esmMin(()=>{Kt(),Jt(),Ol=/\r\n|\r|\n/,Interface$1=class extends Ft{static{__name$1(this,`Interface`)}terminal;line=``;cursor=0;escapeCodeTimeout;_input;_output;get input(){return this._input}get output(){return this._output}_prompt;_closed=!1;_paused=!1;history;_historySize;_crlfDelay;_lineBuffer=``;_questionCallback=null;_boundOnData=null;_boundOnEnd=null;_boundOnError=null;_boundOnKeypress=null;constructor(n,S){super();let C;if(C=n&&typeof n==`object`&&!(`read`in n&&typeof n.read==`function`)?n:{input:n,output:S},this._input=C.input||null,this._output=C.output||null,this._prompt=C.prompt||`> `,this.terminal=C.terminal??this._output!==null,this._historySize=C.historySize??30,this.history=[],this._crlfDelay=C.crlfDelay??100,this.escapeCodeTimeout=C.escapeCodeTimeout,this._input&&(this._boundOnData=n=>this._onData(n),this._boundOnEnd=()=>this._onEnd(),this._boundOnError=n=>this.emit(`error`,n),this._input.on(`data`,this._boundOnData),this._input.on(`end`,this._boundOnEnd),this._input.on(`error`,this._boundOnError),`setEncoding`in this._input&&typeof this._input.setEncoding==`function`&&this._input.setEncoding(`utf8`),this.terminal)){emitKeypressEvents(this._input,this);let n=this._input;typeof n.setRawMode==`function`&&(n.isRaw||n.setRawMode(!0)),typeof this._input.resume==`function`&&this._input.resume(),this._boundOnKeypress=(n,S)=>{S&&(S.name===`backspace`||S.name===`delete`?this.cursor>0&&(this.line=this.line.slice(0,this.cursor-1)+this.line.slice(this.cursor),this.cursor--):n&&n.length===1&&!S.ctrl&&!S.meta&&S.name!==`return`&&S.name!==`enter`&&S.name!==`escape`&&(this.line=this.line.slice(0,this.cursor)+n+this.line.slice(this.cursor),this.cursor++))},this._input.on(`keypress`,this._boundOnKeypress)}}_onData(n){if(this._closed||this._paused)return;let S=typeof n==`string`?n:n.toString(`utf8`);this._lineBuffer+=S;let C;for(;(C=Ol.exec(this._lineBuffer))!==null;){let n=this._lineBuffer.substring(0,C.index);this._lineBuffer=this._lineBuffer.substring(C.index+C[0].length),this._onLine(n)}}_onLine(n){if(n.length>0&&this._historySize>0&&(this.history.length===0||this.history[0]!==n)&&(this.history.unshift(n),this.history.length>this._historySize&&this.history.pop()),this._questionCallback){let S=this._questionCallback;this._questionCallback=null,S(n)}this.emit(`line`,n)}_onEnd(){this._lineBuffer.length>0&&(this._onLine(this._lineBuffer),this._lineBuffer=``),this.close()}setPrompt(n){this._prompt=n}getPrompt(){return this._prompt}prompt(n){if(this._closed)throw Error(`readline was closed`);this._output?.write(this._prompt)}question(n,S,C){if(this._closed)throw Error(`readline was closed`);let N=typeof S==`function`?S:C;this._questionCallback=N,this._output?.write(n)}clearLine(n,S){return this.line=``,this.cursor=0,S&&S(),!0}write(n,S){if(!this._closed){if(S){this._input&&this._input.emit(`keypress`,n??``,S);return}if(n!=null){let S=typeof n==`string`?n:n.toString(`utf8`);S&&(this.line=this.line.slice(0,this.cursor)+S+this.line.slice(this.cursor),this.cursor+=S.length),this._output?.write(n)}}}close(){if(!this._closed){if(this._closed=!0,this._input){this._boundOnData&&this._input.removeListener(`data`,this._boundOnData),this._boundOnEnd&&this._input.removeListener(`end`,this._boundOnEnd),this._boundOnError&&this._input.removeListener(`error`,this._boundOnError),this._boundOnKeypress&&this._input.removeListener(`keypress`,this._boundOnKeypress),this._boundOnData=null,this._boundOnEnd=null,this._boundOnError=null,this._boundOnKeypress=null;let n=this._input;this.terminal&&n.isRaw&&typeof n.setRawMode==`function`&&n.setRawMode(!1),typeof this._input.pause==`function`&&this._input.pause()}this.emit(`close`)}}pause(){return this._closed?this:(this._paused=!0,this._input&&`pause`in this._input&&typeof this._input.pause==`function`&&this._input.pause(),this.emit(`pause`),this)}resume(){return this._closed?this:(this._paused=!1,this._input&&`resume`in this._input&&typeof this._input.resume==`function`&&this._input.resume(),this.emit(`resume`),this)}getCursorPos(){let n=this._output?.columns??80,S=this._prompt.length+this.cursor;return{rows:Math.floor(S/n),cols:S%n}}[Symbol.asyncIterator](){let n=[],S=null,C=!1,onLine=C=>{if(S){let n=S;S=null,n({value:C,done:!1})}else n.push(C)},onClose=()=>{if(C=!0,S){let n=S;S=null,n({value:void 0,done:!0})}};return this.on(`line`,onLine),this.on(`close`,onClose),{next:()=>n.length>0?Promise.resolve({value:n.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{S=n}),return:()=>(C=!0,this.removeListener(`line`,onLine),this.removeListener(`close`,onClose),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this}}}},kl=Symbol.dispose??Symbol.for(`Symbol.dispose`),Interface$1.prototype[kl]=function(){this.close()},__name$1(createInterface$1,`createInterface`),Al=Symbol(`keypress-decoder`),jl=Symbol(`escape-decoder`)}),Nl,Pl=__esmMin(()=>{Xc(),Bc(),Vc(),Zc(),tl(),Dl(),ll(),dl(),fl(),pt(),Rr(),lt(),Ml(),Nl=class FileHandle{options;_gFile;_pathStr;_spec;_pos=0;_closed=!1;_webStreamLocked=!1;static instances={};constructor(n){this.options=n,this.options.flags??=`r`;let S=normalizePath(n.path);this._spec=parseOpenFlags(this.options.flags),this.options.mode??=438;let C=normalizeMode(this.options.mode,438);return this.fd=openFd(S,this._spec,C),this._pathStr=S,this._gFile=Lr.File.new_for_path(S),FileHandle.instances[this.fd]=this,FileHandle.getInstance(this.fd)}_readCore(n,S,C,N){if(this._assertOpen(`read`),!this._spec.readable)throw fsError(`EBADF`,`read`,this._pathStr);if(C>n.byteLength-S){let N=RangeError(`The value of "length" is out of range. It must be <= ${n.byteLength-S}. Received ${C}`);throw N.code=`ERR_OUT_OF_RANGE`,N}let F=N!=null&&N>=0,I=isSeekableFd(this.fd,this._pathStr);if(F&&!I)throw fsError(`ESPIPE`,`read`,this._pathStr);let H=F?N:this._pos;I&&seekFd(this.fd,H);let W=readFd(this.fd,C);return W.length>0&&new Uint8Array(n.buffer,n.byteOffset+S,W.length).set(W),!F&&I&&(this._pos=H+W.length),W.length}_writeCore(n,S){if(this._assertOpen(`write`),!this._spec.writable)throw fsError(`EBADF`,`write`,this._pathStr);if(this._spec.append){let S=writeFd(this.fd,n);return this._pos=tellFd(this.fd)??sizeOfFd(this.fd,this._pathStr),S}let C=S!=null&&S>=0,N=isSeekableFd(this.fd,this._pathStr);if(C&&!N)throw fsError(`ESPIPE`,`write`,this._pathStr);let F=C?S:this._pos;N&&seekFd(this.fd,F);let I=writeFd(this.fd,n);return!C&&N&&(this._pos=F+I),I}_assertOpen(n){if(this._closed)throw fsError(`EBADF`,n,this._pathStr)}_truncateCore(n){if(this._assertOpen(`ftruncate`),!this._spec.writable)throw fsError(`EINVAL`,`ftruncate`,this._pathStr);truncateFd(this.fd,Math.max(0,n),this._pathStr)}_readToEnd(){let n=[],S=0;for(;;){let C=new Uint8Array(64*1024),N=this._readCore(C,0,C.length,null);if(N===0)break;n.push(C.subarray(0,N)),S+=N}let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}_fdTarget(){return fdPath(this.fd)??this._pathStr}fd;static getInstance(n,S=`read`){let C=n instanceof FileHandle?n.fd:n,N=FileHandle.instances[C];if(!N)throw fsError(`EBADF`,S);return N}async appendFile(n,S){await this.writeFile(n,S)}async chown(n,S){this._assertOpen(`fchown`),chownSync(normalizePath(this.options.path),n,S)}async chmod(n){this._assertOpen(`fchmod`),chmodSync(this._fdTarget(),n)}createReadStream(n){return new ReadStream$1(this.options.path,{...n,fd:this.fd})}createWriteStream(n){return new WriteStream$1(this.options.path,{...n,fd:this.fd,fdFromHandle:!0})}async datasync(){this._assertOpen(`fdatasync`),fsyncFd(this.fd)}async sync(){this._assertOpen(`fsync`),fsyncFd(this.fd)}async read(...n){let S,C,N,F;if(typeof n[0]==`object`&&!(n[0]instanceof Uint8Array)&&!(n[0]instanceof $e)){let I=n[0];S=I.buffer,C=I.offset,N=I.length,F=I.position}else S=n[0],C=n[1],N=n[2],F=n[3];let I=S,H=C??0,W=N??(I?I.byteLength-H:65536);return{bytesRead:this._readCore(S,H,W,F??null),buffer:S}}readableWebStream(){if(this._closed)throw invalidState(`The FileHandle is closed`);if(this._webStreamLocked)throw invalidState(`The FileHandle is locked`);let n=globalThis.ReadableStream;if(typeof n!=`function`)throw Error(`readableWebStream() requires a global ReadableStream. Import "node:stream/web" or "@gjsify/web-streams/register" before calling this method.`);return this._webStreamLocked=!0,new n({type:`bytes`,pull:n=>{if(this._closed){n.close(),n.byobRequest?.respond(0);return}let S=n.byobRequest?.view,C=S?new Uint8Array(S.buffer,S.byteOffset,S.byteLength):new Uint8Array(64*1024),N;try{N=this._readCore(C,0,C.length,null)}catch(S){n.error(S);return}if(N===0){n.close(),n.byobRequest?.respond(0);return}if(n.byobRequest){n.byobRequest.respond(N);return}n.enqueue(C.subarray(0,N))}})}async readFile(n){return encodeUint8Array(getEncodingFromOptions(n,`buffer`),this._readToEnd())}readLines(n){return createInterface$1({input:this.createReadStream(n),crlfDelay:1/0})}async stat(n){this._assertOpen(`fstat`);let S=Lr.File.new_for_path(this._fdTarget());return statsFrom(await new Promise((n,C)=>{S.query_info_async(ul,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(N,F)=>{try{n(S.query_info_finish(F))}catch(n){C(n)}})}),this._pathStr,`fstat`,n?.bigint)}async truncate(n=0){this._truncateCore(n)}async utimes(n,S){this._assertOpen(`futimes`);let{utimesSync:C}=await Promise.resolve().then(()=>(Kc(),Gc));C(normalizePath(this.options.path),n,S)}async writeFile(n,S){let C=getEncodingFromOptions(S),N;N=typeof n==`string`?$e.from(n,C||`utf8`):n,this._writeCore(N,null)}async write(n,...S){let C=null,N=null,F=null,I=null;typeof n==`string`?(C=S[0],N=S[1]):(F=S[0],I=S[1],C=S[2]),N=getEncodingFromOptions(N,typeof n==`string`?`utf8`:null);let H;H=typeof n==`string`?new TextEncoder().encode(n):n;let W=F??0,q=I??H.byteLength-W,Y=H.subarray(W,W+q);return{bytesWritten:this._writeCore(Y,C??null),buffer:n}}async writev(n,S){let C=0;for(let N of n){let n=$e.from(N.buffer,N.byteOffset,N.byteLength),F=await this.write(n,0,n.byteLength,S==null?null:S+C);C+=F.bytesWritten}return{bytesWritten:C,buffers:n}}async readv(n,S){let C=0;for(let N of n){let n=await this.read({buffer:$e.from(N.buffer,N.byteOffset,N.byteLength),position:S==null?null:S+C});if(C+=n.bytesRead,n.bytesRead<N.byteLength)break}return{bytesRead:C,buffers:n}}_flushSync(){fsyncFd(this.fd)}_closeSync(){this._teardown()}_readSync(n,S,C,N){return this._readCore(n,S,C,N)}_writeSync(n,S){return this._writeCore(n,S)}_readToEndSync(){return this._readToEnd()}_truncateSync(n){this._truncateCore(n)}_fdStatTarget(){return this._fdTarget()}_teardown(){if(this._closed)return;this._closed=!0,releaseFd(this.fd),closeFd(this.fd);let n=FileHandle;delete n.instances[this.fd]}async close(){this._teardown()}async[Symbol.asyncDispose](){await this.close()}pull(...n){throw Error('FileHandle.pull() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}writer(n){throw Error('FileHandle.writer() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}}});function getFH(n,S){return Nl.getInstance(n,S)}function fstatSync(n,S){return statSync(getFH(n,`fstat`)._fdStatTarget(),S)}function fstat(n,S,C){let N=typeof S==`function`?S:requireCallback(C);fstatAsync(n,typeof S==`function`?{}:S).then(n=>N(null,n),n=>N(n,void 0))}async function fstatAsync(n,S){return S?.bigint,fstatSync(n,S)}function ftruncateSync(n,S=0){getFH(n,`ftruncate`)._truncateSync(S)}function ftruncate(n,S,C){let N=typeof S==`function`?S:requireCallback(C);ftruncateAsync(n,typeof S==`function`?0:S).then(()=>N(null),N)}async function ftruncateAsync(n,S=0){ftruncateSync(n,S)}function fdatasyncSync(n){getFH(n,`fdatasync`)._flushSync()}function fdatasync(n,S){requireCallback(S),Promise.resolve().then(()=>fdatasyncSync(n)).then(()=>S(null),S)}async function fdatasyncAsync(n){fdatasyncSync(n)}function fsyncSync(n){getFH(n,`fsync`)._flushSync()}function fsync(n,S){requireCallback(S),Promise.resolve().then(()=>fsyncSync(n)).then(()=>S(null),S)}async function fsyncAsync(n){fsyncSync(n)}function fchmodSync(n,S){chmodSync(getFH(n,`fchmod`)._fdStatTarget(),S)}function fchmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>fchmodSync(n,S)).then(()=>C(null),C)}async function fchmodAsync(n,S){fchmodSync(n,S)}function fchownSync(n,S,C){chownSync(normalizePath(getFH(n,`fchown`).options.path),S,C)}function fchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>fchownSync(n,S,C)).then(()=>N(null),N)}async function fchownAsync(n,S,C){fchownSync(n,S,C)}function futimesSync(n,S,C){utimesSync(normalizePath(getFH(n,`futimes`).options.path),S,C)}function futimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>futimesSync(n,S,C)).then(()=>N(null),N)}async function futimesAsync(n,S,C){futimesSync(n,S,C)}function closeSync(n){isStdFd(n)||getFH(n,`close`)._closeSync()}function readSync(n,S,C,N,F){let I=0;return typeof C==`object`&&C?(I=C.offset??0,N=C.length??S.byteLength-I,F=C.position??null):(I=C??0,N??=S.byteLength-I),isStdFd(n)?readStdFdSync(n,S,I,N):getFH(n,`read`)._readSync(S,I,N,F??null)}function writeSync(n,S,C,N,F){let I;if(typeof S==`string`)I=new TextEncoder().encode(S),typeof C==`number`&&(F=C);else{let n=typeof C==`number`?C:0,F=typeof N==`number`?N:S.byteLength-n;I=new Uint8Array(S.buffer,S.byteOffset+n,F)}return isStdFd(n)?writeStdFdSync(n,I):getFH(n,`write`)._writeSync(I,F??null)}function readvSync(n,S,C){let N=0;for(let F of S){let S=readSync(n,F,0,F.byteLength,C==null?null:C+N);if(N+=S,S<F.byteLength)break}return N}function readv(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);readvAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesRead,n.buffers),n=>F(n,0,S))}async function readvAsync(n,S,C){return{bytesRead:readvSync(n,S,C),buffers:S}}function writevSync(n,S,C){let N=0;for(let F of S){let S=writeSync(n,F,0,F.byteLength,C==null?null:C+N);N+=S}return N}function writev(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);writevAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesWritten,n.buffers),n=>F(n,0,S))}async function writevAsync(n,S,C){return{bytesWritten:writevSync(n,S,C),buffers:S}}function exists(n,S){requireCallback(S);try{statSync(normalizePath(n)),S(!0)}catch{S(!1)}}async function openAsBlob(n,S){let C=readFileSync(normalizePath(n));return new Blob([C],{type:S?.type??``})}var Fl=__esmMin(()=>{Bc(),Vc(),Kc(),Yc(),Pl(),fl()});function zeroedStat(){return{dev:0,ino:0,mode:0,nlink:0,uid:0,gid:0,rdev:0,size:0,blksize:0,blocks:0,atimeMs:0,mtimeMs:0,ctimeMs:0,birthtimeMs:0,atime:new Date(0),mtime:new Date(0),ctime:new Date(0),birthtime:new Date(0),isFile:()=>!1,isDirectory:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isSymbolicLink:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}function watchFile(n,S,C){typeof S==`function`&&(C=S,S={}),requireCallback(C,`listener`);let N=S.interval??5007,F=n.toString(),I=Il.get(F);return I||(I=new StatWatcher(F,N),I.start(),Il.set(F,I)),C&&I.addChangeListener(C),I}function unwatchFile(n,S){let C=n.toString(),N=Il.get(C);N&&(S?N.removeChangeListener(S):N.removeAllChangeListeners(),N.changeListenerCount===0&&(N.stop(),Il.delete(C)))}var StatWatcher,Il,Ll=__esmMin(()=>{Vc(),fl(),Kt(),StatWatcher=class extends Ft{_path;_interval;_timerId=null;_prev;_changeCount=0;constructor(n,S){super(),this._path=n,this._interval=S,this._prev=zeroedStat()}start(){try{this._prev=statSync(this._path)}catch{}this._timerId=setInterval(()=>{let n;try{n=statSync(this._path)}catch{n=zeroedStat()}let S=this._prev;(n.mtimeMs!==S.mtimeMs||n.size!==S.size||n.ino!==S.ino)&&(this._prev=n,this.emit(`change`,n,S))},this._interval)}stop(){this._timerId!==null&&(clearInterval(this._timerId),this._timerId=null),this.emit(`stop`)}addChangeListener(n){this._changeCount++,this.on(`change`,n)}removeChangeListener(n){this._changeCount--,this.removeListener(`change`,n)}removeAllChangeListeners(){this._changeCount=0,this.removeAllListeners(`change`)}get changeListenerCount(){return this._changeCount}},Il=new Map}),Rl=__exportAll$4({BigIntStats:()=>BigIntStats,Dir:()=>Dir,Dirent:()=>Dirent,FSWatcher:()=>FSWatcher,ReadStream:()=>ReadStream$1,StatWatcher:()=>StatWatcher,Stats:()=>Stats,WriteStream:()=>WriteStream$1,access:()=>access,accessSync:()=>accessSync,appendFile:()=>appendFile,appendFileSync:()=>appendFileSync,chmod:()=>chmod,chmodSync:()=>chmodSync,chown:()=>chown,chownSync:()=>chownSync,close:()=>close$1,closeSync:()=>closeSync,constants:()=>zl,copyFile:()=>copyFile,copyFileSync:()=>copyFileSync,cp:()=>cp,cpSync:()=>cpSync,createReadStream:()=>createReadStream,createWriteStream:()=>createWriteStream,default:()=>Bl,exists:()=>exists,existsSync:()=>existsSync,fchmod:()=>fchmod,fchmodSync:()=>fchmodSync,fchown:()=>fchown,fchownSync:()=>fchownSync,fdatasync:()=>fdatasync,fdatasyncSync:()=>fdatasyncSync,fstat:()=>fstat,fstatSync:()=>fstatSync,fsync:()=>fsync,fsyncSync:()=>fsyncSync,ftruncate:()=>ftruncate,ftruncateSync:()=>ftruncateSync,futimes:()=>futimes,futimesSync:()=>futimesSync,glob:()=>glob,globSync:()=>globSync,lchmod:()=>void 0,lchmodSync:()=>void 0,lchown:()=>lchown,lchownSync:()=>lchownSync,link:()=>link,linkSync:()=>linkSync,lstat:()=>lstat,lstatSync:()=>lstatSync,lutimes:()=>lutimes,lutimesSync:()=>lutimesSync,mkdir:()=>mkdir,mkdirSync:()=>mkdirSync,mkdtemp:()=>mkdtemp,mkdtempSync:()=>mkdtempSync,open:()=>open$1,openAsBlob:()=>openAsBlob,openSync:()=>openSync,opendir:()=>opendir,opendirSync:()=>opendirSync,promises:()=>xl,read:()=>read$1,readFile:()=>readFile,readFileSync:()=>readFileSync,readSync:()=>readSync,readdir:()=>readdir,readdirSync:()=>readdirSync,readlink:()=>readlink,readlinkSync:()=>readlinkSync,readv:()=>readv,readvSync:()=>readvSync,realpath:()=>realpath,realpathSync:()=>realpathSync,rename:()=>rename,renameSync:()=>renameSync,rm:()=>rm,rmSync:()=>rmSync,rmdir:()=>rmdir,rmdirSync:()=>rmdirSync,stat:()=>stat,statSync:()=>statSync,statfs:()=>statfs,statfsSync:()=>statfsSync,symlink:()=>symlink,symlinkSync:()=>symlinkSync,truncate:()=>truncate,truncateSync:()=>truncateSync,unlink:()=>unlink,unlinkSync:()=>unlinkSync,unwatchFile:()=>unwatchFile,utimes:()=>utimes,utimesSync:()=>utimesSync,watch:()=>watch,watchFile:()=>watchFile,write:()=>write,writeFile:()=>writeFile,writeFileSync:()=>writeFileSync,writeSync:()=>writeSync,writev:()=>writev,writevSync:()=>writevSync});function openFlagDescriptors(){let n={};for(let S of Object.keys(openFlagValues()))n[S]={enumerable:!0,configurable:!0,get:()=>openFlagValues()[S]};return n}var zl,Bl,Vl=__esmMin(()=>{Wc(),Kc(),Fl(),Zc(),tl(),Dl(),nl(),dl(),fl(),pl(),hl(),gl(),yl(),Cl(),wl(),Ll(),zl=Object.defineProperties({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1},openFlagDescriptors()),Bl={FSWatcher,StatWatcher,Stats,BigIntStats,Dirent,Dir,constants:zl,existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,rmdirSync,unlinkSync,mkdtemp,mkdtempSync,rmSync,statSync,openSync,realpathSync,symlinkSync,lstatSync,renameSync,copyFileSync,accessSync,appendFileSync,readlinkSync,linkSync,truncateSync,chmodSync,chownSync,cpSync,opendirSync,globSync,glob,watch,watchFile,unwatchFile,statfsSync,statfs,utimesSync,utimes,lutimesSync,lutimes,lchownSync,lchown,lchmodSync:void 0,lchmod:void 0,fstatSync,fstat,ftruncateSync,ftruncate,fdatasyncSync,fdatasync,fsyncSync,fsync,fchmodSync,fchmod,fchownSync,fchown,futimesSync,futimes,closeSync,readSync,writeSync,readvSync,readv,writevSync,writev,exists,openAsBlob,createReadStream,ReadStream:ReadStream$1,createWriteStream,WriteStream:WriteStream$1,promises:xl,open:open$1,close:close$1,read:read$1,write,rm,realpath,readdir,symlink,lstat,stat,rename,copyFile,cp,access,appendFile,readlink,truncate,chmod,chown,mkdir,rmdir,readFile,writeFile,unlink,link,opendir}}),Hl,Ul,Wl,Gl,Kl,ql,Jl=__esmMin(()=>{
|
|
42
|
+
`?(F.name=`enter`,F.meta=N):S===` `?(F.name=`tab`,F.meta=N):S===`\b`||S===``?(F.name=`backspace`,F.meta=N):S===`\x1B`?(F.name=`escape`,F.meta=N):S===` `?(F.name=`space`,F.meta=N):!N&&S<=``?(F.name=String.fromCharCode(S.charCodeAt(0)+97-1),F.ctrl=!0):/^[0-9A-Za-z]$/.test(S)?(F.name=S.toLowerCase(),F.shift=/^[A-Z]$/.test(S),F.meta=N):N&&(F.name=S.length?void 0:`escape`,F.meta=!0);F.sequence=C,C.length!==0&&(F.name!==void 0||N)?n.emit(`keypress`,N?void 0:C,F):C.length===1&&n.emit(`keypress`,C,F)}}function emitKeypressEvents(n,S={}){let C=n;if(C[Al])return;C[Al]=new qt(`utf8`),C[jl]=emitKeys(n),C[jl].next();let N=S.escapeCodeTimeout??500,F,triggerEscape=()=>C[jl].next(``);function onData(S){if(n.listenerCount(`keypress`)>0){let I=C[Al].write(typeof S==`string`?Buffer.from(S):S);if(I){clearTimeout(F);for(let S of I)try{C[jl].next(S),S===`\x1B`&&(F=setTimeout(triggerEscape,N))}catch{C[jl]=emitKeys(n),C[jl].next()}}}else n.removeListener(`data`,onData),delete C[Al],delete C[jl]}n.on(`data`,onData)}var Ol,Interface$1,kl,Al,jl,Ml=__esmMin(()=>{Kt(),Jt(),Ol=/\r\n|\r|\n/,Interface$1=class extends Ft{static{__name$1(this,`Interface`)}terminal;line=``;cursor=0;escapeCodeTimeout;_input;_output;get input(){return this._input}get output(){return this._output}_prompt;_closed=!1;_paused=!1;history;_historySize;_crlfDelay;_lineBuffer=``;_questionCallback=null;_boundOnData=null;_boundOnEnd=null;_boundOnError=null;_boundOnKeypress=null;constructor(n,S){super();let C;if(C=n&&typeof n==`object`&&!(`read`in n&&typeof n.read==`function`)?n:{input:n,output:S},this._input=C.input||null,this._output=C.output||null,this._prompt=C.prompt||`> `,this.terminal=C.terminal??this._output!==null,this._historySize=C.historySize??30,this.history=[],this._crlfDelay=C.crlfDelay??100,this.escapeCodeTimeout=C.escapeCodeTimeout,this._input&&(this._boundOnData=n=>this._onData(n),this._boundOnEnd=()=>this._onEnd(),this._boundOnError=n=>this.emit(`error`,n),this._input.on(`data`,this._boundOnData),this._input.on(`end`,this._boundOnEnd),this._input.on(`error`,this._boundOnError),`setEncoding`in this._input&&typeof this._input.setEncoding==`function`&&this._input.setEncoding(`utf8`),this.terminal)){emitKeypressEvents(this._input,this);let n=this._input;typeof n.setRawMode==`function`&&(n.isRaw||n.setRawMode(!0)),typeof this._input.resume==`function`&&this._input.resume(),this._boundOnKeypress=(n,S)=>{S&&(S.name===`backspace`||S.name===`delete`?this.cursor>0&&(this.line=this.line.slice(0,this.cursor-1)+this.line.slice(this.cursor),this.cursor--):n&&n.length===1&&!S.ctrl&&!S.meta&&S.name!==`return`&&S.name!==`enter`&&S.name!==`escape`&&(this.line=this.line.slice(0,this.cursor)+n+this.line.slice(this.cursor),this.cursor++))},this._input.on(`keypress`,this._boundOnKeypress)}}_onData(n){if(this._closed||this._paused)return;let S=typeof n==`string`?n:n.toString(`utf8`);this._lineBuffer+=S;let C;for(;(C=Ol.exec(this._lineBuffer))!==null;){let n=this._lineBuffer.substring(0,C.index);this._lineBuffer=this._lineBuffer.substring(C.index+C[0].length),this._onLine(n)}}_onLine(n){if(n.length>0&&this._historySize>0&&(this.history.length===0||this.history[0]!==n)&&(this.history.unshift(n),this.history.length>this._historySize&&this.history.pop()),this._questionCallback){let S=this._questionCallback;this._questionCallback=null,S(n)}this.emit(`line`,n)}_onEnd(){this._lineBuffer.length>0&&(this._onLine(this._lineBuffer),this._lineBuffer=``),this.close()}setPrompt(n){this._prompt=n}getPrompt(){return this._prompt}prompt(n){if(this._closed)throw Error(`readline was closed`);this._output?.write(this._prompt)}question(n,S,C){if(this._closed)throw Error(`readline was closed`);let N=typeof S==`function`?S:C;this._questionCallback=N,this._output?.write(n)}clearLine(n,S){return this.line=``,this.cursor=0,S&&S(),!0}write(n,S){if(!this._closed){if(S){this._input&&this._input.emit(`keypress`,n??``,S);return}if(n!=null){let S=typeof n==`string`?n:n.toString(`utf8`);S&&(this.line=this.line.slice(0,this.cursor)+S+this.line.slice(this.cursor),this.cursor+=S.length),this._output?.write(n)}}}close(){if(!this._closed){if(this._closed=!0,this._input){this._boundOnData&&this._input.removeListener(`data`,this._boundOnData),this._boundOnEnd&&this._input.removeListener(`end`,this._boundOnEnd),this._boundOnError&&this._input.removeListener(`error`,this._boundOnError),this._boundOnKeypress&&this._input.removeListener(`keypress`,this._boundOnKeypress),this._boundOnData=null,this._boundOnEnd=null,this._boundOnError=null,this._boundOnKeypress=null;let n=this._input;this.terminal&&n.isRaw&&typeof n.setRawMode==`function`&&n.setRawMode(!1),typeof this._input.pause==`function`&&this._input.pause()}this.emit(`close`)}}pause(){return this._closed?this:(this._paused=!0,this._input&&`pause`in this._input&&typeof this._input.pause==`function`&&this._input.pause(),this.emit(`pause`),this)}resume(){return this._closed?this:(this._paused=!1,this._input&&`resume`in this._input&&typeof this._input.resume==`function`&&this._input.resume(),this.emit(`resume`),this)}getCursorPos(){let n=this._output?.columns??80,S=this._prompt.length+this.cursor;return{rows:Math.floor(S/n),cols:S%n}}[Symbol.asyncIterator](){let n=[],S=null,C=!1,onLine=C=>{if(S){let n=S;S=null,n({value:C,done:!1})}else n.push(C)},onClose=()=>{if(C=!0,S){let n=S;S=null,n({value:void 0,done:!0})}};return this.on(`line`,onLine),this.on(`close`,onClose),{next:()=>n.length>0?Promise.resolve({value:n.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{S=n}),return:()=>(C=!0,this.removeListener(`line`,onLine),this.removeListener(`close`,onClose),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this}}}},kl=Symbol.dispose??Symbol.for(`Symbol.dispose`),Interface$1.prototype[kl]=function(){this.close()},__name$1(createInterface$1,`createInterface`),Al=Symbol(`keypress-decoder`),jl=Symbol(`escape-decoder`)}),Nl,Pl=__esmMin(()=>{Xc(),Bc(),Vc(),Zc(),tl(),Dl(),ll(),dl(),fl(),pt(),Rr(),lt(),Ml(),Nl=class FileHandle{options;_gFile;_pathStr;_spec;_pos=0;_closed=!1;_webStreamLocked=!1;static instances={};constructor(n){this.options=n,this.options.flags??=`r`;let S=normalizePath(n.path);this._spec=parseOpenFlags(this.options.flags),this.options.mode??=438;let C=normalizeMode(this.options.mode,438);return this.fd=openFd(S,this._spec,C),this._pathStr=S,this._gFile=Lr.File.new_for_path(S),FileHandle.instances[this.fd]=this,FileHandle.getInstance(this.fd)}_readCore(n,S,C,N){if(this._assertOpen(`read`),!this._spec.readable)throw fsError(`EBADF`,`read`,this._pathStr);if(C>n.byteLength-S){let N=RangeError(`The value of "length" is out of range. It must be <= ${n.byteLength-S}. Received ${C}`);throw N.code=`ERR_OUT_OF_RANGE`,N}let F=N!=null&&N>=0,I=isSeekableFd(this.fd,this._pathStr);if(F&&!I)throw fsError(`ESPIPE`,`read`,this._pathStr);let H=F?N:this._pos;I&&seekFd(this.fd,H);let W=readFd(this.fd,C);return W.length>0&&new Uint8Array(n.buffer,n.byteOffset+S,W.length).set(W),!F&&I&&(this._pos=H+W.length),W.length}_writeCore(n,S){if(this._assertOpen(`write`),!this._spec.writable)throw fsError(`EBADF`,`write`,this._pathStr);if(this._spec.append){let S=writeFd(this.fd,n);return this._pos=tellFd(this.fd)??sizeOfFd(this.fd,this._pathStr),S}let C=S!=null&&S>=0,N=isSeekableFd(this.fd,this._pathStr);if(C&&!N)throw fsError(`ESPIPE`,`write`,this._pathStr);let F=C?S:this._pos;N&&seekFd(this.fd,F);let I=writeFd(this.fd,n);return!C&&N&&(this._pos=F+I),I}_assertOpen(n){if(this._closed)throw fsError(`EBADF`,n,this._pathStr)}_truncateCore(n){if(this._assertOpen(`ftruncate`),!this._spec.writable)throw fsError(`EINVAL`,`ftruncate`,this._pathStr);truncateFd(this.fd,Math.max(0,n),this._pathStr)}_readToEnd(){let n=[],S=0;for(;;){let C=new Uint8Array(64*1024),N=this._readCore(C,0,C.length,null);if(N===0)break;n.push(C.subarray(0,N)),S+=N}let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}_fdTarget(){return fdPath(this.fd)??this._pathStr}fd;static getInstance(n,S=`read`){let C=n instanceof FileHandle?n.fd:n,N=FileHandle.instances[C];if(!N)throw fsError(`EBADF`,S);return N}async appendFile(n,S){await this.writeFile(n,S)}async chown(n,S){this._assertOpen(`fchown`),chownSync(normalizePath(this.options.path),n,S)}async chmod(n){this._assertOpen(`fchmod`),chmodSync(this._fdTarget(),n)}createReadStream(n){return new ReadStream$1(this.options.path,{...n,fd:this.fd})}createWriteStream(n){return new WriteStream$1(this.options.path,{...n,fd:this.fd,fdFromHandle:!0})}async datasync(){this._assertOpen(`fdatasync`),fsyncFd(this.fd)}async sync(){this._assertOpen(`fsync`),fsyncFd(this.fd)}async read(...n){let S,C,N,F;if(typeof n[0]==`object`&&!(n[0]instanceof Uint8Array)&&!(n[0]instanceof $e)){let I=n[0];S=I.buffer,C=I.offset,N=I.length,F=I.position}else S=n[0],C=n[1],N=n[2],F=n[3];let I=S,H=C??0,W=N??(I?I.byteLength-H:65536);return{bytesRead:this._readCore(S,H,W,F??null),buffer:S}}readableWebStream(){if(this._closed)throw invalidState(`The FileHandle is closed`);if(this._webStreamLocked)throw invalidState(`The FileHandle is locked`);let n=globalThis.ReadableStream;if(typeof n!=`function`)throw Error(`readableWebStream() requires a global ReadableStream. Import "node:stream/web" or "@gjsify/web-streams/register" before calling this method.`);return this._webStreamLocked=!0,new n({type:`bytes`,pull:n=>{if(this._closed){n.close(),n.byobRequest?.respond(0);return}let S=n.byobRequest?.view,C=S?new Uint8Array(S.buffer,S.byteOffset,S.byteLength):new Uint8Array(64*1024),N;try{N=this._readCore(C,0,C.length,null)}catch(S){n.error(S);return}if(N===0){n.close(),n.byobRequest?.respond(0);return}if(n.byobRequest){n.byobRequest.respond(N);return}n.enqueue(C.subarray(0,N))}})}async readFile(n){return encodeUint8Array(getEncodingFromOptions(n,`buffer`),this._readToEnd())}readLines(n){return createInterface$1({input:this.createReadStream(n),crlfDelay:1/0})}async stat(n){this._assertOpen(`fstat`);let S=Lr.File.new_for_path(this._fdTarget());return statsFrom(await new Promise((n,C)=>{S.query_info_async(ul,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(N,F)=>{try{n(S.query_info_finish(F))}catch(n){C(n)}})}),this._pathStr,`fstat`,n?.bigint)}async truncate(n=0){this._truncateCore(n)}async utimes(n,S){this._assertOpen(`futimes`);let{utimesSync:C}=await Promise.resolve().then(()=>(Kc(),Gc));C(normalizePath(this.options.path),n,S)}async writeFile(n,S){let C=getEncodingFromOptions(S),N;N=typeof n==`string`?$e.from(n,C||`utf8`):n,this._writeCore(N,null)}async write(n,...S){let C=null,N=null,F=null,I=null;typeof n==`string`?(C=S[0],N=S[1]):(F=S[0],I=S[1],C=S[2]),N=getEncodingFromOptions(N,typeof n==`string`?`utf8`:null);let H;H=typeof n==`string`?new TextEncoder().encode(n):n;let W=F??0,q=I??H.byteLength-W,Y=H.subarray(W,W+q);return{bytesWritten:this._writeCore(Y,C??null),buffer:n}}async writev(n,S){let C=0;for(let N of n){let n=$e.from(N.buffer,N.byteOffset,N.byteLength),F=await this.write(n,0,n.byteLength,S==null?null:S+C);C+=F.bytesWritten}return{bytesWritten:C,buffers:n}}async readv(n,S){let C=0;for(let N of n){let n=await this.read({buffer:$e.from(N.buffer,N.byteOffset,N.byteLength),position:S==null?null:S+C});if(C+=n.bytesRead,n.bytesRead<N.byteLength)break}return{bytesRead:C,buffers:n}}_flushSync(){fsyncFd(this.fd)}_closeSync(){this._teardown()}_readSync(n,S,C,N){return this._readCore(n,S,C,N)}_writeSync(n,S){return this._writeCore(n,S)}_readToEndSync(){return this._readToEnd()}_truncateSync(n){this._truncateCore(n)}_fdStatTarget(){return this._fdTarget()}_teardown(){if(this._closed)return;this._closed=!0,releaseFd(this.fd),closeFd(this.fd);let n=FileHandle;delete n.instances[this.fd]}async close(){this._teardown()}async[Symbol.asyncDispose](){await this.close()}pull(...n){throw Error('FileHandle.pull() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}writer(n){throw Error('FileHandle.writer() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}}});function getFH(n,S){return Nl.getInstance(n,S)}function fstatSync(n,S){return statSync(getFH(n,`fstat`)._fdStatTarget(),S)}function fstat(n,S,C){let N=typeof S==`function`?S:requireCallback(C);fstatAsync(n,typeof S==`function`?{}:S).then(n=>N(null,n),n=>N(n,void 0))}async function fstatAsync(n,S){return S?.bigint,fstatSync(n,S)}function ftruncateSync(n,S=0){getFH(n,`ftruncate`)._truncateSync(S)}function ftruncate(n,S,C){let N=typeof S==`function`?S:requireCallback(C);ftruncateAsync(n,typeof S==`function`?0:S).then(()=>N(null),N)}async function ftruncateAsync(n,S=0){ftruncateSync(n,S)}function fdatasyncSync(n){getFH(n,`fdatasync`)._flushSync()}function fdatasync(n,S){requireCallback(S),Promise.resolve().then(()=>fdatasyncSync(n)).then(()=>S(null),S)}async function fdatasyncAsync(n){fdatasyncSync(n)}function fsyncSync(n){getFH(n,`fsync`)._flushSync()}function fsync(n,S){requireCallback(S),Promise.resolve().then(()=>fsyncSync(n)).then(()=>S(null),S)}async function fsyncAsync(n){fsyncSync(n)}function fchmodSync(n,S){chmodSync(getFH(n,`fchmod`)._fdStatTarget(),S)}function fchmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>fchmodSync(n,S)).then(()=>C(null),C)}async function fchmodAsync(n,S){fchmodSync(n,S)}function fchownSync(n,S,C){chownSync(normalizePath(getFH(n,`fchown`).options.path),S,C)}function fchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>fchownSync(n,S,C)).then(()=>N(null),N)}async function fchownAsync(n,S,C){fchownSync(n,S,C)}function futimesSync(n,S,C){utimesSync(normalizePath(getFH(n,`futimes`).options.path),S,C)}function futimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>futimesSync(n,S,C)).then(()=>N(null),N)}async function futimesAsync(n,S,C){futimesSync(n,S,C)}function closeSync(n){isStdFd(n)||getFH(n,`close`)._closeSync()}function readSync(n,S,C,N,F){let I=0;return typeof C==`object`&&C?(I=C.offset??0,N=C.length??S.byteLength-I,F=C.position??null):(I=C??0,N??=S.byteLength-I),isStdFd(n)?readStdFdSync(n,S,I,N):getFH(n,`read`)._readSync(S,I,N,F??null)}function writeSync(n,S,C,N,F){let I;if(typeof S==`string`)I=new TextEncoder().encode(S),typeof C==`number`&&(F=C);else{let n=typeof C==`number`?C:0,F=typeof N==`number`?N:S.byteLength-n;I=new Uint8Array(S.buffer,S.byteOffset+n,F)}return isStdFd(n)?writeStdFdSync(n,I):getFH(n,`write`)._writeSync(I,F??null)}function readvSync(n,S,C){let N=0;for(let F of S){let S=readSync(n,F,0,F.byteLength,C==null?null:C+N);if(N+=S,S<F.byteLength)break}return N}function readv(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);readvAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesRead,n.buffers),n=>F(n,0,S))}async function readvAsync(n,S,C){return{bytesRead:readvSync(n,S,C),buffers:S}}function writevSync(n,S,C){let N=0;for(let F of S){let S=writeSync(n,F,0,F.byteLength,C==null?null:C+N);N+=S}return N}function writev(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);writevAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesWritten,n.buffers),n=>F(n,0,S))}async function writevAsync(n,S,C){return{bytesWritten:writevSync(n,S,C),buffers:S}}function exists(n,S){requireCallback(S);let C;try{statSync(normalizePath(n)),C=!0}catch{C=!1}Promise.resolve().then(()=>S(C))}async function openAsBlob(n,S){let C=readFileSync(normalizePath(n));return new Blob([C],{type:S?.type??``})}var Fl=__esmMin(()=>{Bc(),Vc(),Kc(),Yc(),Pl(),fl(),Object.defineProperty(exists,Symbol.for(`nodejs.util.promisify.custom`),{value:n=>new Promise(S=>exists(n,S))})});function zeroedStat(){return{dev:0,ino:0,mode:0,nlink:0,uid:0,gid:0,rdev:0,size:0,blksize:0,blocks:0,atimeMs:0,mtimeMs:0,ctimeMs:0,birthtimeMs:0,atime:new Date(0),mtime:new Date(0),ctime:new Date(0),birthtime:new Date(0),isFile:()=>!1,isDirectory:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isSymbolicLink:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}function watchFile(n,S,C){typeof S==`function`&&(C=S,S={}),requireCallback(C,`listener`);let N=S.interval??5007,F=n.toString(),I=Il.get(F);return I||(I=new StatWatcher(F,N),I.start(),Il.set(F,I)),C&&I.addChangeListener(C),I}function unwatchFile(n,S){let C=n.toString(),N=Il.get(C);N&&(S?N.removeChangeListener(S):N.removeAllChangeListeners(),N.changeListenerCount===0&&(N.stop(),Il.delete(C)))}var StatWatcher,Il,Ll=__esmMin(()=>{Vc(),fl(),Kt(),StatWatcher=class extends Ft{_path;_interval;_timerId=null;_prev;_changeCount=0;constructor(n,S){super(),this._path=n,this._interval=S,this._prev=zeroedStat()}start(){try{this._prev=statSync(this._path)}catch{}this._timerId=setInterval(()=>{let n;try{n=statSync(this._path)}catch{n=zeroedStat()}let S=this._prev;(n.mtimeMs!==S.mtimeMs||n.size!==S.size||n.ino!==S.ino)&&(this._prev=n,this.emit(`change`,n,S))},this._interval)}stop(){this._timerId!==null&&(clearInterval(this._timerId),this._timerId=null),this.emit(`stop`)}addChangeListener(n){this._changeCount++,this.on(`change`,n)}removeChangeListener(n){this._changeCount--,this.removeListener(`change`,n)}removeAllChangeListeners(){this._changeCount=0,this.removeAllListeners(`change`)}get changeListenerCount(){return this._changeCount}},Il=new Map}),Rl=__exportAll$4({BigIntStats:()=>BigIntStats,Dir:()=>Dir,Dirent:()=>Dirent,FSWatcher:()=>FSWatcher,ReadStream:()=>ReadStream$1,StatWatcher:()=>StatWatcher,Stats:()=>Stats,WriteStream:()=>WriteStream$1,access:()=>access,accessSync:()=>accessSync,appendFile:()=>appendFile,appendFileSync:()=>appendFileSync,chmod:()=>chmod,chmodSync:()=>chmodSync,chown:()=>chown,chownSync:()=>chownSync,close:()=>close$1,closeSync:()=>closeSync,constants:()=>zl,copyFile:()=>copyFile,copyFileSync:()=>copyFileSync,cp:()=>cp,cpSync:()=>cpSync,createReadStream:()=>createReadStream,createWriteStream:()=>createWriteStream,default:()=>Bl,exists:()=>exists,existsSync:()=>existsSync,fchmod:()=>fchmod,fchmodSync:()=>fchmodSync,fchown:()=>fchown,fchownSync:()=>fchownSync,fdatasync:()=>fdatasync,fdatasyncSync:()=>fdatasyncSync,fstat:()=>fstat,fstatSync:()=>fstatSync,fsync:()=>fsync,fsyncSync:()=>fsyncSync,ftruncate:()=>ftruncate,ftruncateSync:()=>ftruncateSync,futimes:()=>futimes,futimesSync:()=>futimesSync,glob:()=>glob,globSync:()=>globSync,lchmod:()=>void 0,lchmodSync:()=>void 0,lchown:()=>lchown,lchownSync:()=>lchownSync,link:()=>link,linkSync:()=>linkSync,lstat:()=>lstat,lstatSync:()=>lstatSync,lutimes:()=>lutimes,lutimesSync:()=>lutimesSync,mkdir:()=>mkdir,mkdirSync:()=>mkdirSync,mkdtemp:()=>mkdtemp,mkdtempSync:()=>mkdtempSync,open:()=>open$1,openAsBlob:()=>openAsBlob,openSync:()=>openSync,opendir:()=>opendir,opendirSync:()=>opendirSync,promises:()=>xl,read:()=>read$1,readFile:()=>readFile,readFileSync:()=>readFileSync,readSync:()=>readSync,readdir:()=>readdir,readdirSync:()=>readdirSync,readlink:()=>readlink,readlinkSync:()=>readlinkSync,readv:()=>readv,readvSync:()=>readvSync,realpath:()=>realpath,realpathSync:()=>realpathSync,rename:()=>rename,renameSync:()=>renameSync,rm:()=>rm,rmSync:()=>rmSync,rmdir:()=>rmdir,rmdirSync:()=>rmdirSync,stat:()=>stat,statSync:()=>statSync,statfs:()=>statfs,statfsSync:()=>statfsSync,symlink:()=>symlink,symlinkSync:()=>symlinkSync,truncate:()=>truncate,truncateSync:()=>truncateSync,unlink:()=>unlink,unlinkSync:()=>unlinkSync,unwatchFile:()=>unwatchFile,utimes:()=>utimes,utimesSync:()=>utimesSync,watch:()=>watch,watchFile:()=>watchFile,write:()=>write,writeFile:()=>writeFile,writeFileSync:()=>writeFileSync,writeSync:()=>writeSync,writev:()=>writev,writevSync:()=>writevSync});function openFlagDescriptors(){let n={};for(let S of Object.keys(openFlagValues()))n[S]={enumerable:!0,configurable:!0,get:()=>openFlagValues()[S]};return n}var zl,Bl,Vl=__esmMin(()=>{Wc(),Kc(),Fl(),Zc(),tl(),Dl(),nl(),dl(),fl(),pl(),hl(),gl(),yl(),Cl(),wl(),Ll(),zl=Object.defineProperties({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1},openFlagDescriptors()),Bl={FSWatcher,StatWatcher,Stats,BigIntStats,Dirent,Dir,constants:zl,existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,rmdirSync,unlinkSync,mkdtemp,mkdtempSync,rmSync,statSync,openSync,realpathSync,symlinkSync,lstatSync,renameSync,copyFileSync,accessSync,appendFileSync,readlinkSync,linkSync,truncateSync,chmodSync,chownSync,cpSync,opendirSync,globSync,glob,watch,watchFile,unwatchFile,statfsSync,statfs,utimesSync,utimes,lutimesSync,lutimes,lchownSync,lchown,lchmodSync:void 0,lchmod:void 0,fstatSync,fstat,ftruncateSync,ftruncate,fdatasyncSync,fdatasync,fsyncSync,fsync,fchmodSync,fchmod,fchownSync,fchown,futimesSync,futimes,closeSync,readSync,writeSync,readvSync,readv,writevSync,writev,exists,openAsBlob,createReadStream,ReadStream:ReadStream$1,createWriteStream,WriteStream:WriteStream$1,promises:xl,open:open$1,close:close$1,read:read$1,write,rm,realpath,readdir,symlink,lstat,stat,rename,copyFile,cp,access,appendFile,readlink,truncate,chmod,chown,mkdir,rmdir,readFile,writeFile,unlink,link,opendir}}),Hl,Ul,Wl,Gl,Kl,ql,Jl=__esmMin(()=>{
|
|
43
43
|
/**
|
|
44
44
|
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
|
45
45
|
*
|
|
@@ -119,7 +119,7 @@ fi
|
|
|
119
119
|
`)}`:``;S.fail(F(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(N).length,Object.keys(N).join(`, `)+C))}},I.unknownArguments=function unknownArguments(C,N,H,W,q=!0){let Y=n.getInternalMethods().getCommandInstance().getCommands(),X=[],Z=n.getInternalMethods().getContext();if(Object.keys(C).forEach(S=>{!bd.includes(S)&&!Object.prototype.hasOwnProperty.call(H,S)&&!Object.prototype.hasOwnProperty.call(n.getInternalMethods().getParseContext(),S)&&!I.isValidAndSomeAliasIsNotNew(S,N)&&X.push(S)}),q&&(Z.commands.length>0||Y.length>0||W)&&C._.slice(Z.commands.length).forEach(n=>{Y.includes(``+n)||X.push(``+n)}),q){let S=n.getDemandedCommands()._?.max||0,N=Z.commands.length+S;N<C._.length&&C._.slice(N).forEach(n=>{n=String(n),!Z.commands.includes(n)&&!X.includes(n)&&X.push(n)})}X.length&&S.fail(F(`Unknown argument: %s`,`Unknown arguments: %s`,X.length,X.map(n=>n.trim()?n:`"${n}"`).join(`, `)))},I.unknownCommands=function unknownCommands(C){let N=n.getInternalMethods().getCommandInstance().getCommands(),I=[],H=n.getInternalMethods().getContext();return(H.commands.length>0||N.length>0)&&C._.slice(H.commands.length).forEach(n=>{N.includes(``+n)||I.push(``+n)}),I.length>0?(S.fail(F(`Unknown command: %s`,`Unknown commands: %s`,I.length,I.join(`, `))),!0):!1},I.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(S,C){if(!Object.prototype.hasOwnProperty.call(C,S))return!1;let N=n.parsed.newAliases;return[S,...C[S]].some(n=>!Object.prototype.hasOwnProperty.call(N,n)||!N[S])},I.limitedChoices=function limitedChoices(C){let F=n.getOptions(),I={};if(!Object.keys(F.choices).length)return;Object.keys(C).forEach(n=>{bd.indexOf(n)===-1&&Object.prototype.hasOwnProperty.call(F.choices,n)&&[].concat(C[n]).forEach(S=>{F.choices[n].indexOf(S)===-1&&S!==void 0&&(I[n]=(I[n]||[]).concat(S))})});let H=Object.keys(I);if(!H.length)return;let W=N(`Invalid values:`);H.forEach(n=>{W+=`\n ${N(`Argument: %s, Given: %s, Choices: %s`,n,S.stringifiedValues(I[n]),S.stringifiedValues(F.choices[n]))}`}),S.fail(W)};let H={};I.implies=function implies(S,N){argsert(`<string|object> [array|number|string]`,[S,N],arguments.length),typeof S==`object`?Object.keys(S).forEach(n=>{I.implies(n,S[n])}):(n.global(S),H[S]||(H[S]=[]),Array.isArray(N)?N.forEach(n=>I.implies(S,n)):(assertNotStrictEqual(N,void 0,C),H[S].push(N)))},I.getImplied=function getImplied(){return H};function keyExists(n,S){let C=Number(S);return S=isNaN(C)?S:C,typeof S==`number`?S=n._.length>=S:S.match(/^--no-.+/)?(S=S.match(/^--no-(.+)/)[1],S=!Object.prototype.hasOwnProperty.call(n,S)):S=Object.prototype.hasOwnProperty.call(n,S),S}I.implications=function implications(n){let C=[];if(Object.keys(H).forEach(S=>{let N=S;(H[S]||[]).forEach(S=>{let F=N,I=S;F=keyExists(n,F),S=keyExists(n,S),F&&!S&&C.push(` ${N} -> ${I}`)})}),C.length){let n=`${N(`Implications failed:`)}\n`;C.forEach(S=>{n+=S}),S.fail(n)}};let W={};I.conflicts=function conflicts(S,C){argsert(`<string|object> [array|string]`,[S,C],arguments.length),typeof S==`object`?Object.keys(S).forEach(n=>{I.conflicts(n,S[n])}):(n.global(S),W[S]||(W[S]=[]),Array.isArray(C)?C.forEach(n=>I.conflicts(S,n)):W[S].push(C))},I.getConflicting=()=>W,I.conflicting=function conflictingFn(F){Object.keys(F).forEach(n=>{W[n]&&W[n].forEach(C=>{C&&F[n]!==void 0&&F[C]!==void 0&&S.fail(N(`Arguments %s and %s are mutually exclusive`,n,C))})}),n.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(W).forEach(n=>{W[n].forEach(I=>{I&&F[C.Parser.camelCase(n)]!==void 0&&F[C.Parser.camelCase(I)]!==void 0&&S.fail(N(`Arguments %s and %s are mutually exclusive`,n,I))})})},I.recommendCommands=function recommendCommands(n,C){C=C.sort((n,S)=>S.length-n.length);let F=null,I=1/0;for(let S=0,N;(N=C[S])!==void 0;S++){let S=levenshtein(n,N);S<=3&&S<I&&(I=S,F=N)}F&&S.fail(N(`Did you mean %s?`,F))},I.reset=function reset(n){return H=objFilter(H,S=>!n[S]),W=objFilter(W,S=>!n[S]),I};let q=[];return I.freeze=function freeze(){q.push({implied:H,conflicting:W})},I.unfreeze=function unfreeze(){let n=q.pop();assertNotStrictEqual(n,void 0,C),{implied:H,conflicting:W}=n},I}var bd,xd=__esmMin(()=>{sd(),rd(),yd(),fd(),bd=[`$0`,`--`,`_`]});function YargsFactory(n){return(S=[],C=n.process.cwd(),N)=>{let F=new YargsInstance(S,C,N,n);return Object.defineProperty(F,"argv",{get:()=>F.parse(),enumerable:!0}),F.help(),F.version(),F}}function isYargsInstance(n){return!!n&&typeof n.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld,Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,YargsInstance,Vf=__esmMin(()=>{ye(),dd(),rd(),rs(),md(),sd(),vd(),xd(),fd(),os(),cd(),id(),ld(),pd(),__classPrivateFieldSet=function(n,S,C,N,F){if(N===`m`)throw TypeError(`Private method is not writable`);if(N===`a`&&!F)throw TypeError(`Private accessor was defined without a setter`);if(typeof S==`function`?n!==S||!F:!S.has(n))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return N===`a`?F.call(n,C):F?F.value=C:S.set(n,C),C},__classPrivateFieldGet=function(n,S,C,N){if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a getter`);if(typeof S==`function`?n!==S||!N:!S.has(n))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return C===`m`?N:C===`a`?N.call(n):N?N.value:S.get(n)},rf=Symbol(`copyDoubleDash`),af=Symbol(`copyDoubleDash`),of=Symbol(`deleteFromParserHintObject`),sf=Symbol(`emitWarning`),cf=Symbol(`freeze`),lf=Symbol(`getDollarZero`),uf=Symbol(`getParserConfiguration`),df=Symbol(`getUsageConfiguration`),ff=Symbol(`guessLocale`),pf=Symbol(`guessVersion`),mf=Symbol(`parsePositionalNumbers`),hf=Symbol(`pkgUp`),gf=Symbol(`populateParserHintArray`),_f=Symbol(`populateParserHintSingleValueDictionary`),vf=Symbol(`populateParserHintArrayDictionary`),yf=Symbol(`populateParserHintDictionary`),bf=Symbol(`sanitizeKey`),xf=Symbol(`setKey`),Sf=Symbol(`unfreeze`),Cf=Symbol(`validateAsync`),wf=Symbol(`getCommandInstance`),Tf=Symbol(`getContext`),Ef=Symbol(`getHasOutput`),Df=Symbol(`getLoggerInstance`),Of=Symbol(`getParseContext`),kf=Symbol(`getUsageInstance`),Af=Symbol(`getValidationInstance`),jf=Symbol(`hasParseCallback`),Mf=Symbol(`isGlobalContext`),Nf=Symbol(`postProcess`),Pf=Symbol(`rebase`),Ff=Symbol(`reset`),If=Symbol(`runYargsParserAndExecuteCommands`),Lf=Symbol(`runValidation`),Rf=Symbol(`setHasOutput`),zf=Symbol(`kTrackManuallySetKeys`),Bf=`en_US`,YargsInstance=class{constructor(n=[],S,C,N){this.customScriptName=!1,this.parsed=!1,Sd.set(this,void 0),Cd.set(this,void 0),wd.set(this,{commands:[],fullCommands:[]}),Td.set(this,null),Ed.set(this,null),Dd.set(this,`show-hidden`),Od.set(this,null),kd.set(this,!0),Ad.set(this,{}),jd.set(this,!0),Md.set(this,[]),Nd.set(this,void 0),Pd.set(this,{}),Fd.set(this,!1),Id.set(this,null),Ld.set(this,!0),Rd.set(this,void 0),zd.set(this,``),Bd.set(this,void 0),Vd.set(this,void 0),Hd.set(this,{}),Ud.set(this,null),Wd.set(this,null),Gd.set(this,{}),Kd.set(this,{}),qd.set(this,void 0),Jd.set(this,!1),Yd.set(this,void 0),Xd.set(this,!1),Zd.set(this,!1),Qd.set(this,!1),$d.set(this,void 0),ef.set(this,{}),tf.set(this,null),nf.set(this,void 0),__classPrivateFieldSet(this,Yd,N,`f`),__classPrivateFieldSet(this,qd,n,`f`),__classPrivateFieldSet(this,Cd,S,`f`),__classPrivateFieldSet(this,Vd,C,`f`),__classPrivateFieldSet(this,Nd,new GlobalMiddleware(this),`f`),this.$0=this[lf](),this[Ff](),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`),`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`),`f`),__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`),`f`),__classPrivateFieldGet(this,Bd,`f`).showHiddenOpt=__classPrivateFieldGet(this,Dd,`f`),__classPrivateFieldSet(this,Rd,this[af](),`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.setLocale(Bf)}addHelpOpt(n,S){return argsert(`[string|boolean] [string]`,[n,S],arguments.length),__classPrivateFieldGet(this,Id,`f`)&&(this[of](__classPrivateFieldGet(this,Id,`f`)),__classPrivateFieldSet(this,Id,null,`f`)),n===!1&&S===void 0?this:(__classPrivateFieldSet(this,Id,typeof n==`string`?n:`help`,`f`),this.boolean(__classPrivateFieldGet(this,Id,`f`)),this.describe(__classPrivateFieldGet(this,Id,`f`),S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show help`)),this)}help(n,S){return this.addHelpOpt(n,S)}addShowHiddenOpt(n,S){if(argsert(`[string|boolean] [string]`,[n,S],arguments.length),n===!1&&S===void 0)return this;let C=typeof n==`string`?n:__classPrivateFieldGet(this,Dd,`f`);return this.boolean(C),this.describe(C,S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,Bd,`f`).showHiddenOpt=C,this}showHidden(n,S){return this.addShowHiddenOpt(n,S)}alias(n,S){return argsert(`<object|string|array> [string|array]`,[n,S],arguments.length),this[vf](this.alias.bind(this),`alias`,n,S),this}array(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`array`,n),this[zf](n),this}boolean(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`boolean`,n),this[zf](n),this}check(n,S){return argsert(`<function> [boolean]`,[n,S],arguments.length),this.middleware((S,C)=>maybeAsyncResult(()=>n(S,C.getOptions()),C=>(C?(typeof C==`string`||C instanceof Error)&&__classPrivateFieldGet(this,$d,`f`).fail(C.toString(),C):__classPrivateFieldGet(this,$d,`f`).fail(__classPrivateFieldGet(this,Yd,`f`).y18n.__(`Argument check failed: %s`,n.toString())),S),n=>(__classPrivateFieldGet(this,$d,`f`).fail(n.message?n.message:n.toString(),n),S)),!1,S),this}choices(n,S){return argsert(`<object|string|array> [string|array]`,[n,S],arguments.length),this[vf](this.choices.bind(this),`choices`,n,S),this}coerce(n,S){if(argsert(`<object|string|array> [function]`,[n,S],arguments.length),Array.isArray(n)){if(!S)throw new ns(`coerce callback must be provided`);for(let C of n)this.coerce(C,S);return this}else if(typeof n==`object`){for(let S of Object.keys(n))this.coerce(S,n[S]);return this}if(!S)throw new ns(`coerce callback must be provided`);let C=n;return __classPrivateFieldGet(this,Bd,`f`).key[C]=!0,__classPrivateFieldGet(this,Nd,`f`).addCoerceMiddleware((n,N)=>{let F=N.getAliases()[C]??[],I=[C,...F].filter(S=>Object.prototype.hasOwnProperty.call(n,S));return I.length===0?n:maybeAsyncResult(()=>S(n[I[0]]),S=>(I.forEach(C=>{n[C]=S}),n),n=>{throw new ns(n.message)})},C),this}conflicts(n,S){return argsert(`<string|object> [string|array]`,[n,S],arguments.length),__classPrivateFieldGet(this,nf,`f`).conflicts(n,S),this}config(n=`config`,S,C){return argsert(`[object|string] [string|function] [function]`,[n,S,C],arguments.length),typeof n==`object`&&!Array.isArray(n)?(n=applyExtends(n,__classPrivateFieldGet(this,Cd,`f`),this[uf]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).configObjects=(__classPrivateFieldGet(this,Bd,`f`).configObjects||[]).concat(n),this):(typeof S==`function`&&(C=S,S=void 0),this.describe(n,S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(n)?n:[n]).forEach(n=>{__classPrivateFieldGet(this,Bd,`f`).config[n]=C||!0}),this)}completion(n,S,C){return argsert(`[string] [string|boolean|function] [function]`,[n,S,C],arguments.length),typeof S==`function`&&(C=S,S=void 0),__classPrivateFieldSet(this,Ed,n||__classPrivateFieldGet(this,Ed,`f`)||`completion`,`f`),!S&&S!==!1&&(S=`generate completion script`),this.command(__classPrivateFieldGet(this,Ed,`f`),S),C&&__classPrivateFieldGet(this,Td,`f`).registerFunction(C),this}command(n,S,C,N,F,I){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[n,S,C,N,F,I],arguments.length),__classPrivateFieldGet(this,Sd,`f`).addHandler(n,S,C,N,F,I),this}commands(n,S,C,N,F,I){return this.command(n,S,C,N,F,I)}commandDir(n,S){argsert(`<string> [object]`,[n,S],arguments.length);let C=__classPrivateFieldGet(this,Vd,`f`)||__classPrivateFieldGet(this,Yd,`f`).require;return __classPrivateFieldGet(this,Sd,`f`).addDirectory(n,C,__classPrivateFieldGet(this,Yd,`f`).getCallerFile(),S),this}count(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`count`,n),this[zf](n),this}default(n,S,C){return argsert(`<object|string|array> [*] [string]`,[n,S,C],arguments.length),C&&(assertSingleKey(n,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=C),typeof S==`function`&&(assertSingleKey(n,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]||(__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=__classPrivateFieldGet(this,$d,`f`).functionDescription(S)),S=S.call()),this[_f](this.default.bind(this),`default`,n,S),this}defaults(n,S,C){return this.default(n,S,C)}demandCommand(n=1,S,C,N){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[n,S,C,N],arguments.length),typeof S!=`number`&&(C=S,S=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,Bd,`f`).demandedCommands._={min:n,max:S,minMsg:C,maxMsg:N},this}demand(n,S,C){return Array.isArray(S)?(S.forEach(n=>{assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandOption(n,C)}),S=1/0):typeof S!=`number`&&(C=S,S=1/0),typeof n==`number`?(assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandCommand(n,S,C,C)):Array.isArray(n)?n.forEach(n=>{assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandOption(n,C)}):typeof C==`string`?this.demandOption(n,C):(C===!0||C===void 0)&&this.demandOption(n),this}demandOption(n,S){return argsert(`<object|string|array> [string]`,[n,S],arguments.length),this[_f](this.demandOption.bind(this),`demandedOptions`,n,S),this}deprecateOption(n,S){return argsert(`<string> [string|boolean]`,[n,S],arguments.length),__classPrivateFieldGet(this,Bd,`f`).deprecatedOptions[n]=S,this}describe(n,S){return argsert(`<object|string|array> [string]`,[n,S],arguments.length),this[xf](n,!0),__classPrivateFieldGet(this,$d,`f`).describe(n,S),this}detectLocale(n){return argsert(`<boolean>`,[n],arguments.length),__classPrivateFieldSet(this,kd,n,`f`),this}env(n){return argsert(`[string|boolean]`,[n],arguments.length),n===!1?delete __classPrivateFieldGet(this,Bd,`f`).envPrefix:__classPrivateFieldGet(this,Bd,`f`).envPrefix=n||``,this}epilogue(n){return argsert(`<string>`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).epilog(n),this}epilog(n){return this.epilogue(n)}example(n,S){return argsert(`<string|array> [string]`,[n,S],arguments.length),Array.isArray(n)?n.forEach(n=>this.example(...n)):__classPrivateFieldGet(this,$d,`f`).example(n,S),this}exit(n,S){__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldSet(this,Od,S,`f`),__classPrivateFieldGet(this,jd,`f`)&&__classPrivateFieldGet(this,Yd,`f`).process.exit(n)}exitProcess(n=!0){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,jd,n,`f`),this}fail(n){if(argsert(`<function|boolean>`,[n],arguments.length),typeof n==`boolean`&&n!==!1)throw new ns(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,$d,`f`).failFn(n),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(n,S){return argsert(`<array> [function]`,[n,S],arguments.length),S?__classPrivateFieldGet(this,Td,`f`).getCompletion(n,S):new Promise((S,C)=>{__classPrivateFieldGet(this,Td,`f`).getCompletion(n,(n,N)=>{n?C(n):S(N)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,kd,`f`)}getExitProcess(){return __classPrivateFieldGet(this,jd,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,Pd,`f`),__classPrivateFieldGet(this,Kd,`f`))}getHelp(){if(__classPrivateFieldSet(this,Fd,!0,`f`),!__classPrivateFieldGet(this,$d,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[If](__classPrivateFieldGet(this,qd,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>__classPrivateFieldGet(this,$d,`f`).help())}let n=__classPrivateFieldGet(this,Sd,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>__classPrivateFieldGet(this,$d,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,$d,`f`).help())}getOptions(){return __classPrivateFieldGet(this,Bd,`f`)}getStrict(){return __classPrivateFieldGet(this,Xd,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,Zd,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,Qd,`f`)}global(n,S){return argsert(`<string|array> [boolean]`,[n,S],arguments.length),n=[].concat(n),S===!1?n.forEach(n=>{__classPrivateFieldGet(this,Bd,`f`).local.includes(n)||__classPrivateFieldGet(this,Bd,`f`).local.push(n)}):__classPrivateFieldGet(this,Bd,`f`).local=__classPrivateFieldGet(this,Bd,`f`).local.filter(S=>n.indexOf(S)===-1),this}group(n,S){argsert(`<string|array> <string>`,[n,S],arguments.length);let C=__classPrivateFieldGet(this,Kd,`f`)[S]||__classPrivateFieldGet(this,Pd,`f`)[S];__classPrivateFieldGet(this,Kd,`f`)[S]&&delete __classPrivateFieldGet(this,Kd,`f`)[S];let N={};return __classPrivateFieldGet(this,Pd,`f`)[S]=(C||[]).concat(n).filter(n=>N[n]?!1:N[n]=!0),this}hide(n){return argsert(`<string>`,[n],arguments.length),__classPrivateFieldGet(this,Bd,`f`).hiddenOptions.push(n),this}implies(n,S){return argsert(`<string|object> [number|string|array]`,[n,S],arguments.length),__classPrivateFieldGet(this,nf,`f`).implies(n,S),this}locale(n){return argsert(`[string]`,[n],arguments.length),n===void 0?(this[ff](),__classPrivateFieldGet(this,Yd,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,kd,!1,`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.setLocale(n),this)}middleware(n,S,C){return __classPrivateFieldGet(this,Nd,`f`).addMiddleware(n,!!S,C)}nargs(n,S){return argsert(`<string|object|array> [number]`,[n,S],arguments.length),this[_f](this.nargs.bind(this),`narg`,n,S),this}normalize(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`normalize`,n),this}number(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`number`,n),this[zf](n),this}option(n,S){if(argsert(`<string|object> [object]`,[n,S],arguments.length),typeof n==`object`)Object.keys(n).forEach(S=>{this.options(S,n[S])});else{typeof S!=`object`&&(S={}),this[zf](n),__classPrivateFieldGet(this,tf,`f`)&&(n===`version`||S?.alias===`version`)&&this[sf]([`"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(`
|
|
120
120
|
`),void 0,`versionWarning`),__classPrivateFieldGet(this,Bd,`f`).key[n]=!0,S.alias&&this.alias(n,S.alias);let C=S.deprecate||S.deprecated;C&&this.deprecateOption(n,C);let N=S.demand||S.required||S.require;N&&this.demand(n,N),S.demandOption&&this.demandOption(n,typeof S.demandOption==`string`?S.demandOption:void 0),S.conflicts&&this.conflicts(n,S.conflicts),`default`in S&&this.default(n,S.default),S.implies!==void 0&&this.implies(n,S.implies),S.nargs!==void 0&&this.nargs(n,S.nargs),S.config&&this.config(n,S.configParser),S.normalize&&this.normalize(n),S.choices&&this.choices(n,S.choices),S.coerce&&this.coerce(n,S.coerce),S.group&&this.group(n,S.group),(S.boolean||S.type===`boolean`)&&(this.boolean(n),S.alias&&this.boolean(S.alias)),(S.array||S.type===`array`)&&(this.array(n),S.alias&&this.array(S.alias)),(S.number||S.type===`number`)&&(this.number(n),S.alias&&this.number(S.alias)),(S.string||S.type===`string`)&&(this.string(n),S.alias&&this.string(S.alias)),(S.count||S.type===`count`)&&this.count(n),typeof S.global==`boolean`&&this.global(n,S.global),S.defaultDescription&&(__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=S.defaultDescription),S.skipValidation&&this.skipValidation(n);let F=S.describe||S.description||S.desc,I=__classPrivateFieldGet(this,$d,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(I,n)||typeof F==`string`)&&this.describe(n,F),S.hidden&&this.hide(n),S.requiresArg&&this.requiresArg(n)}return this}options(n,S){return this.option(n,S)}parse(n,S,C){argsert(`[string|array] [function|boolean|object] [function]`,[n,S,C],arguments.length),this[cf](),n===void 0&&(n=__classPrivateFieldGet(this,qd,`f`)),typeof S==`object`&&(__classPrivateFieldSet(this,Wd,S,`f`),S=C),typeof S==`function`&&(__classPrivateFieldSet(this,Ud,S,`f`),S=!1),S||__classPrivateFieldSet(this,qd,n,`f`),__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldSet(this,jd,!1,`f`);let N=this[If](n,!!S),F=this.parsed;return __classPrivateFieldGet(this,Td,`f`).setParsed(this.parsed),isPromise(N)?N.then(n=>(__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`).call(this,__classPrivateFieldGet(this,Od,`f`),n,__classPrivateFieldGet(this,zd,`f`)),n)).catch(n=>{throw __classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`)(n,this.parsed.argv,__classPrivateFieldGet(this,zd,`f`)),n}).finally(()=>{this[Sf](),this.parsed=F}):(__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`).call(this,__classPrivateFieldGet(this,Od,`f`),N,__classPrivateFieldGet(this,zd,`f`)),this[Sf](),this.parsed=F,N)}parseAsync(n,S,C){let N=this.parse(n,S,C);return isPromise(N)?N:Promise.resolve(N)}parseSync(n,S,C){let N=this.parse(n,S,C);if(isPromise(N))throw new ns(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return N}parserConfiguration(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,Hd,n,`f`),this}pkgConf(n,S){argsert(`<string> [string]`,[n,S],arguments.length);let C=null,N=this[hf](S||__classPrivateFieldGet(this,Cd,`f`));return N[n]&&typeof N[n]==`object`&&(C=applyExtends(N[n],S||__classPrivateFieldGet(this,Cd,`f`),this[uf]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).configObjects=(__classPrivateFieldGet(this,Bd,`f`).configObjects||[]).concat(C)),this}positional(n,S){argsert(`<string> <object>`,[n,S],arguments.length);let C=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];S=objFilter(S,(n,S)=>n===`type`&&![`string`,`number`,`boolean`].includes(S)?!1:C.includes(n));let N=__classPrivateFieldGet(this,wd,`f`).fullCommands[__classPrivateFieldGet(this,wd,`f`).fullCommands.length-1],F=N?__classPrivateFieldGet(this,Sd,`f`).cmdToParseOptions(N):{array:[],alias:{},default:{},demand:{}};return objectKeys(F).forEach(C=>{let N=F[C];Array.isArray(N)?N.indexOf(n)!==-1&&(S[C]=!0):N[n]&&!(C in S)&&(S[C]=N[n])}),this.group(n,__classPrivateFieldGet(this,$d,`f`).getPositionalGroupName()),this.option(n,S)}recommendCommands(n=!0){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Jd,n,`f`),this}required(n,S,C){return this.demand(n,S,C)}require(n,S,C){return this.demand(n,S,C)}requiresArg(n){return argsert(`<array|string|object> [number]`,[n],arguments.length),typeof n==`string`&&__classPrivateFieldGet(this,Bd,`f`).narg[n]||this[_f](this.requiresArg.bind(this),`narg`,n,NaN),this}showCompletionScript(n,S){return argsert(`[string] [string]`,[n,S],arguments.length),n||=this.$0,__classPrivateFieldGet(this,Rd,`f`).log(__classPrivateFieldGet(this,Td,`f`).generateCompletionScript(n,S||__classPrivateFieldGet(this,Ed,`f`)||`completion`)),this}showHelp(n){if(argsert(`[string|function]`,[n],arguments.length),__classPrivateFieldSet(this,Fd,!0,`f`),!__classPrivateFieldGet(this,$d,`f`).hasCachedHelpMessage()){if(!this.parsed){let S=this[If](__classPrivateFieldGet(this,qd,`f`),void 0,void 0,0,!0);if(isPromise(S))return S.then(()=>{__classPrivateFieldGet(this,$d,`f`).showHelp(n)}),this}let S=__classPrivateFieldGet(this,Sd,`f`).runDefaultBuilderOn(this);if(isPromise(S))return S.then(()=>{__classPrivateFieldGet(this,$d,`f`).showHelp(n)}),this}return __classPrivateFieldGet(this,$d,`f`).showHelp(n),this}scriptName(n){return this.customScriptName=!0,this.$0=n,this}showHelpOnFail(n,S){return argsert(`[boolean|string] [string]`,[n,S],arguments.length),__classPrivateFieldGet(this,$d,`f`).showHelpOnFail(n,S),this}showVersion(n){return argsert(`[string|function]`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).showVersion(n),this}skipValidation(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`skipValidation`,n),this}strict(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Xd,n!==!1,`f`),this}strictCommands(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Zd,n!==!1,`f`),this}strictOptions(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Qd,n!==!1,`f`),this}string(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`string`,n),this[zf](n),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,Yd,`f`).process.stdColumns}updateLocale(n){return this.updateStrings(n)}updateStrings(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,kd,!1,`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.updateLocale(n),this}usage(n,S,C,N){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[n,S,C,N],arguments.length),S!==void 0){if(assertNotStrictEqual(n,null,__classPrivateFieldGet(this,Yd,`f`)),(n||``).match(/^\$0( |$)/))return this.command(n,S,C,N);throw new ns(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,$d,`f`).usage(n),this}usageConfiguration(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,ef,n,`f`),this}version(n,S,C){let N=`version`;if(argsert(`[boolean|string] [string] [string]`,[n,S,C],arguments.length),__classPrivateFieldGet(this,tf,`f`)&&(this[of](__classPrivateFieldGet(this,tf,`f`)),__classPrivateFieldGet(this,$d,`f`).version(void 0),__classPrivateFieldSet(this,tf,null,`f`)),arguments.length===0)C=this[pf](),n=N;else if(arguments.length===1){if(n===!1)return this;C=n,n=N}else arguments.length===2&&(C=S,S=void 0);return __classPrivateFieldSet(this,tf,typeof n==`string`?n:N,`f`),S||=__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,$d,`f`).version(C||void 0),this.boolean(__classPrivateFieldGet(this,tf,`f`)),this.describe(__classPrivateFieldGet(this,tf,`f`),S),this}wrap(n){return argsert(`<number|null|undefined>`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).wrap(n),this}[(Sd=new WeakMap,Cd=new WeakMap,wd=new WeakMap,Td=new WeakMap,Ed=new WeakMap,Dd=new WeakMap,Od=new WeakMap,kd=new WeakMap,Ad=new WeakMap,jd=new WeakMap,Md=new WeakMap,Nd=new WeakMap,Pd=new WeakMap,Fd=new WeakMap,Id=new WeakMap,Ld=new WeakMap,Rd=new WeakMap,zd=new WeakMap,Bd=new WeakMap,Vd=new WeakMap,Hd=new WeakMap,Ud=new WeakMap,Wd=new WeakMap,Gd=new WeakMap,Kd=new WeakMap,qd=new WeakMap,Jd=new WeakMap,Yd=new WeakMap,Xd=new WeakMap,Zd=new WeakMap,Qd=new WeakMap,$d=new WeakMap,ef=new WeakMap,tf=new WeakMap,nf=new WeakMap,rf)](n){if(!n._||!n[`--`])return n;n._.push.apply(n._,n[`--`]);try{delete n[`--`]}catch{}return n}[af](){return{log:(...n)=>{this[jf]()||ve.log(...n),__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldGet(this,zd,`f`).length&&__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+`
|
|
121
121
|
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)},error:(...n)=>{this[jf]()||ve.error(...n),__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldGet(this,zd,`f`).length&&__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+`
|
|
122
|
-
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)}}}[of](n){objectKeys(__classPrivateFieldGet(this,Bd,`f`)).forEach(S=>{if((n=>n===`configObjects`)(S))return;let C=__classPrivateFieldGet(this,Bd,`f`)[S];Array.isArray(C)?C.includes(n)&&C.splice(C.indexOf(n),1):typeof C==`object`&&delete C[n]}),delete __classPrivateFieldGet(this,$d,`f`).getDescriptions()[n]}[sf](n,S,C){__classPrivateFieldGet(this,Ad,`f`)[C]||(__classPrivateFieldGet(this,Yd,`f`).process.emitWarning(n,S),__classPrivateFieldGet(this,Ad,`f`)[C]=!0)}[cf](){__classPrivateFieldGet(this,Md,`f`).push({options:__classPrivateFieldGet(this,Bd,`f`),configObjects:__classPrivateFieldGet(this,Bd,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,jd,`f`),groups:__classPrivateFieldGet(this,Pd,`f`),strict:__classPrivateFieldGet(this,Xd,`f`),strictCommands:__classPrivateFieldGet(this,Zd,`f`),strictOptions:__classPrivateFieldGet(this,Qd,`f`),completionCommand:__classPrivateFieldGet(this,Ed,`f`),output:__classPrivateFieldGet(this,zd,`f`),exitError:__classPrivateFieldGet(this,Od,`f`),hasOutput:__classPrivateFieldGet(this,Fd,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Ud,`f`),parseContext:__classPrivateFieldGet(this,Wd,`f`)}),__classPrivateFieldGet(this,$d,`f`).freeze(),__classPrivateFieldGet(this,nf,`f`).freeze(),__classPrivateFieldGet(this,Sd,`f`).freeze(),__classPrivateFieldGet(this,Nd,`f`).freeze()}[lf](){let n=``,S;return S=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Yd,`f`).process.argv()[0])?__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(0,1),n=S.map(n=>{let S=this[Pf](__classPrivateFieldGet(this,Cd,`f`),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&S.length<n.length?S:n}).join(` `).trim(),__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Yd,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&(n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Yd,`f`).path.dirname(__classPrivateFieldGet(this,Yd,`f`).process.execPath())}/`,``)),n}[uf](){return __classPrivateFieldGet(this,Hd,`f`)}[df](){return __classPrivateFieldGet(this,ef,`f`)}[ff](){if(!__classPrivateFieldGet(this,kd,`f`))return;let n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(n.replace(/[.:].*/,``))}[pf](){return this[hf]().version||`unknown`}[mf](n){let S=n[`--`]?n[`--`]:n._;for(let n=0,C;(C=S[n])!==void 0;n++)__classPrivateFieldGet(this,Yd,`f`).Parser.looksLikeNumber(C)&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))&&(S[n]=Number(C));return n}[hf](n){let S=n||`*`;if(__classPrivateFieldGet(this,Gd,`f`)[S])return __classPrivateFieldGet(this,Gd,`f`)[S];let C={};try{let S=n||__classPrivateFieldGet(this,Yd,`f`).mainFilename;__classPrivateFieldGet(this,Yd,`f`).path.extname(S)&&(S=__classPrivateFieldGet(this,Yd,`f`).path.dirname(S));let N=__classPrivateFieldGet(this,Yd,`f`).findUp(S,(n,S)=>{if(S.includes(`package.json`))return`package.json`});assertNotStrictEqual(N,void 0,__classPrivateFieldGet(this,Yd,`f`)),C=JSON.parse(__classPrivateFieldGet(this,Yd,`f`).readFileSync(N,`utf8`))}catch{}return __classPrivateFieldGet(this,Gd,`f`)[S]=C||{},__classPrivateFieldGet(this,Gd,`f`)[S]}[gf](n,S){S=[].concat(S),S.forEach(S=>{S=this[bf](S),__classPrivateFieldGet(this,Bd,`f`)[n].push(S)})}[_f](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=C})}[vf](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=(__classPrivateFieldGet(this,Bd,`f`)[n][S]||[]).concat(C)})}[yf](n,S,C,N,F){if(Array.isArray(C))C.forEach(S=>{n(S,N)});else if((n=>typeof n==`object`)(C))for(let S of objectKeys(C))n(S,C[S]);else F(S,this[bf](C),N)}[bf](n){return n===`__proto__`?`___proto___`:n}[xf](n,S){return this[_f](this[xf].bind(this),`key`,n,S),this}[Sf](){var n,S,C,N,F,I,H,W,q,Y,X,Z;let te=__classPrivateFieldGet(this,Md,`f`).pop();assertNotStrictEqual(te,void 0,__classPrivateFieldGet(this,Yd,`f`));let ne;n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,Z=this,{options:{set value(S){__classPrivateFieldSet(n,Bd,S,`f`)}}.value,configObjects:ne,exitProcess:{set value(n){__classPrivateFieldSet(S,jd,n,`f`)}}.value,groups:{set value(n){__classPrivateFieldSet(C,Pd,n,`f`)}}.value,output:{set value(n){__classPrivateFieldSet(N,zd,n,`f`)}}.value,exitError:{set value(n){__classPrivateFieldSet(F,Od,n,`f`)}}.value,hasOutput:{set value(n){__classPrivateFieldSet(I,Fd,n,`f`)}}.value,parsed:this.parsed,strict:{set value(n){__classPrivateFieldSet(H,Xd,n,`f`)}}.value,strictCommands:{set value(n){__classPrivateFieldSet(W,Zd,n,`f`)}}.value,strictOptions:{set value(n){__classPrivateFieldSet(q,Qd,n,`f`)}}.value,completionCommand:{set value(n){__classPrivateFieldSet(Y,Ed,n,`f`)}}.value,parseFn:{set value(n){__classPrivateFieldSet(X,Ud,n,`f`)}}.value,parseContext:{set value(n){__classPrivateFieldSet(Z,Wd,n,`f`)}}.value}=te,__classPrivateFieldGet(this,Bd,`f`).configObjects=ne,__classPrivateFieldGet(this,$d,`f`).unfreeze(),__classPrivateFieldGet(this,nf,`f`).unfreeze(),__classPrivateFieldGet(this,Sd,`f`).unfreeze(),__classPrivateFieldGet(this,Nd,`f`).unfreeze()}[Cf](n,S){return maybeAsyncResult(S,S=>(n(S),S))}getInternalMethods(){return{getCommandInstance:this[wf].bind(this),getContext:this[Tf].bind(this),getHasOutput:this[Ef].bind(this),getLoggerInstance:this[Df].bind(this),getParseContext:this[Of].bind(this),getParserConfiguration:this[uf].bind(this),getUsageConfiguration:this[df].bind(this),getUsageInstance:this[kf].bind(this),getValidationInstance:this[Af].bind(this),hasParseCallback:this[jf].bind(this),isGlobalContext:this[Mf].bind(this),postProcess:this[Nf].bind(this),reset:this[Ff].bind(this),runValidation:this[Lf].bind(this),runYargsParserAndExecuteCommands:this[If].bind(this),setHasOutput:this[Rf].bind(this)}}[wf](){return __classPrivateFieldGet(this,Sd,`f`)}[Tf](){return __classPrivateFieldGet(this,wd,`f`)}[Ef](){return __classPrivateFieldGet(this,Fd,`f`)}[Df](){return __classPrivateFieldGet(this,Rd,`f`)}[Of](){return __classPrivateFieldGet(this,Wd,`f`)||{}}[kf](){return __classPrivateFieldGet(this,$d,`f`)}[Af](){return __classPrivateFieldGet(this,nf,`f`)}[jf](){return!!__classPrivateFieldGet(this,Ud,`f`)}[Mf](){return __classPrivateFieldGet(this,Ld,`f`)}[Nf](n,S,C,N){return C||isPromise(n)?n:(S||(n=this[rf](n)),(this[uf]()[`parse-positional-numbers`]||this[uf]()[`parse-positional-numbers`]===void 0)&&(n=this[mf](n)),N&&(n=applyMiddleware(n,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)),n)}[Ff](n={}){__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`)||{},`f`);let S={};S.local=__classPrivateFieldGet(this,Bd,`f`).local||[],S.configObjects=__classPrivateFieldGet(this,Bd,`f`).configObjects||[];let C={};return S.local.forEach(S=>{C[S]=!0,(n[S]||[]).forEach(n=>{C[n]=!0})}),Object.assign(__classPrivateFieldGet(this,Kd,`f`),Object.keys(__classPrivateFieldGet(this,Pd,`f`)).reduce((n,S)=>{let N=__classPrivateFieldGet(this,Pd,`f`)[S].filter(n=>!(n in C));return N.length>0&&(n[S]=N),n},{})),__classPrivateFieldSet(this,Pd,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(n=>{S[n]=(__classPrivateFieldGet(this,Bd,`f`)[n]||[]).filter(n=>!C[n])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(n=>{S[n]=objFilter(__classPrivateFieldGet(this,Bd,`f`)[n],n=>!C[n])}),S.envPrefix=__classPrivateFieldGet(this,Bd,`f`).envPrefix,__classPrivateFieldSet(this,Bd,S,`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`)?__classPrivateFieldGet(this,$d,`f`).reset(C):usage(this,__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`)?__classPrivateFieldGet(this,nf,`f`).reset(C):validation(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`)?__classPrivateFieldGet(this,Sd,`f`).reset():command(__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,nf,`f`),__classPrivateFieldGet(this,Nd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Td,`f`)||__classPrivateFieldSet(this,Td,completion(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Sd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Nd,`f`).reset(),__classPrivateFieldSet(this,Ed,null,`f`),__classPrivateFieldSet(this,zd,``,`f`),__classPrivateFieldSet(this,Od,null,`f`),__classPrivateFieldSet(this,Fd,!1,`f`),this.parsed=!1,this}[Pf](n,S){return __classPrivateFieldGet(this,Yd,`f`).path.relative(n,S)}[If](n,S,C,N=0,F=!1){let I=!!C||F;n||=__classPrivateFieldGet(this,qd,`f`),__classPrivateFieldGet(this,Bd,`f`).__=__classPrivateFieldGet(this,Yd,`f`).y18n.__,__classPrivateFieldGet(this,Bd,`f`).configuration=this[uf]();let H=!!__classPrivateFieldGet(this,Bd,`f`).configuration[`populate--`],W=Object.assign({},__classPrivateFieldGet(this,Bd,`f`).configuration,{"populate--":!0}),q=__classPrivateFieldGet(this,Yd,`f`).Parser.detailed(n,Object.assign({},__classPrivateFieldGet(this,Bd,`f`),{configuration:{"parse-positional-numbers":!1,...W}})),Y=Object.assign(q.argv,__classPrivateFieldGet(this,Wd,`f`)),X,Z=q.aliases,te=!1,ne=!1;Object.keys(Y).forEach(n=>{n===__classPrivateFieldGet(this,Id,`f`)&&Y[n]?te=!0:n===__classPrivateFieldGet(this,tf,`f`)&&Y[n]&&(ne=!0)}),Y.$0=this.$0,this.parsed=q,N===0&&__classPrivateFieldGet(this,$d,`f`).clearCachedHelpMessage();try{if(this[ff](),S)return this[Nf](Y,H,!!C,!1);__classPrivateFieldGet(this,Id,`f`)&&[__classPrivateFieldGet(this,Id,`f`)].concat(Z[__classPrivateFieldGet(this,Id,`f`)]||[]).filter(n=>n.length>1).includes(``+Y._[Y._.length-1])&&(Y._.pop(),te=!0),__classPrivateFieldSet(this,Ld,!1,`f`);let W=__classPrivateFieldGet(this,Sd,`f`).getCommands(),re=__classPrivateFieldGet(this,Td,`f`)?.completionKey?[__classPrivateFieldGet(this,Td,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Td,`f`)?.completionKey]??[]].some(n=>Object.prototype.hasOwnProperty.call(Y,n)):!1,ie=te||re||F;if(Y._.length){if(W.length){let n;for(let S=N||0,I;Y._[S]!==void 0;S++)if(I=String(Y._[S]),W.includes(I)&&I!==__classPrivateFieldGet(this,Ed,`f`)){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(I,this,q,S+1,F,te||ne||F);return this[Nf](n,H,!!C,!1)}else if(!n&&I!==__classPrivateFieldGet(this,Ed,`f`)){n=I;break}!__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Jd,`f`)&&n&&!ie&&__classPrivateFieldGet(this,nf,`f`).recommendCommands(n,W)}__classPrivateFieldGet(this,Ed,`f`)&&Y._.includes(__classPrivateFieldGet(this,Ed,`f`))&&!re&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&!ie){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(null,this,q,0,F,te||ne||F);return this[Nf](n,H,!!C,!1)}if(re){__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),n=[].concat(n);let S=n.slice(n.indexOf(`--${__classPrivateFieldGet(this,Td,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Td,`f`).getCompletion(S,(n,S)=>{if(n)throw new ns(n.message);(S||[]).forEach(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n)}),this.exit(0)}),this[Nf](Y,!H,!!C,!1)}if(__classPrivateFieldGet(this,Fd,`f`)||(te?(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,this.showHelp(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n),this.exit(0)})):ne&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,__classPrivateFieldGet(this,$d,`f`).showVersion(`log`),this.exit(0))),!I&&__classPrivateFieldGet(this,Bd,`f`).skipValidation.length>0&&(I=Object.keys(Y).some(n=>__classPrivateFieldGet(this,Bd,`f`).skipValidation.indexOf(n)>=0&&Y[n]===!0)),!I){if(q.error)throw new ns(q.error.message);if(!re){let n=this[Lf](Z,{},q.error);C||(X=applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!0)),X=this[Cf](n,X??Y),isPromise(X)&&!C&&(X=X.then(()=>applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)))}}}catch(n){if(n instanceof ns)__classPrivateFieldGet(this,$d,`f`).fail(n.message,n);else throw n}return this[Nf](X??Y,H,!!C,!0)}[Lf](n,S,C,N){let F={...this.getDemandedOptions()};return I=>{if(C)throw new ns(C.message);__classPrivateFieldGet(this,nf,`f`).nonOptionCount(I),__classPrivateFieldGet(this,nf,`f`).requiredArguments(I,F);let H=!1;__classPrivateFieldGet(this,Zd,`f`)&&(H=__classPrivateFieldGet(this,nf,`f`).unknownCommands(I)),__classPrivateFieldGet(this,Xd,`f`)&&!H?__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,S,!!N):__classPrivateFieldGet(this,Qd,`f`)&&__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,{},!1,!1),__classPrivateFieldGet(this,nf,`f`).limitedChoices(I),__classPrivateFieldGet(this,nf,`f`).implications(I),__classPrivateFieldGet(this,nf,`f`).conflicting(I)}}[Rf](){__classPrivateFieldSet(this,Fd,!0,`f`)}[zf](n){if(typeof n==`string`)__classPrivateFieldGet(this,Bd,`f`).key[n]=!0;else for(let S of n)__classPrivateFieldGet(this,Bd,`f`).key[S]=!0}}}),Hf,Uf=__esmMin(()=>{nd(),Vf(),Hf=YargsFactory(td)});function classifyCliFailure(n,S){return typeof n==`string`&&n.length>0?{kind:`usage`,message:n}:{kind:`runtime`}}var Wf=__esmMin(()=>{});function buildHeaders(n,S){let C={"user-agent":`gjsify-install/0.46.0`,"accept-encoding":S.acceptEncoding??`identity`};if(S.npmrc){let N=resolveAuthForUrl(n,S.npmrc);N&&(C.authorization=N)}if(S.headers)for(let[n,N]of Object.entries(S.headers))C[n.toLowerCase()]=N;return C}function resolveAuthForUrl(n,S){let C=pathPrefixes(new URL(n));for(let n of C){let C=S.authTokens[n];if(C)return`Bearer ${C}`;let N=S.basicAuth[n];if(N)return`Basic ${btoa(`${N.username}:${N.password}`)}`}return null}function pathPrefixes(n){let S=n.pathname.split(`/`).filter(Boolean),C=[];for(let N=S.length;N>=0;N--){let F=S.slice(0,N).join(`/`);C.push(F?`//${n.host}/${F}`:`//${n.host}`)}return C}var Gf=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,Kf=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(n,S){super(`Package not found in registry: ${n} (${S})`),this.name=n,this.url=S,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(n,S){super(`Tarball integrity mismatch for ${n} (expected ${S})`),this.url=n,this.integrity=S,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(n,S,C){let N=Math.round(S/100)/10,F=Math.round(S*C/100)/10;super(`@gjsify/npm-registry: GET ${n} timed out after ${N}s × ${C} attempt(s) (total ~${F}s). This usually means the registry CDN is slow or unreachable.`),this.url=n,this.timeoutMs=S,this.attempts=C,this.name=`RegistryTimeoutError`}}});function registryFor(n,S){if(S&&n.startsWith(`@`)){let C=n.slice(0,n.indexOf(`/`)),N=S.scopes[C];if(N)return ensureTrailingSlash$1(N)}return S?.registry?ensureTrailingSlash$1(S.registry):qf}function parseNpmrc(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}},C=n.split(/\r?\n/),N={};for(let n of C){let C=n.replace(/^\s+|\s+$/g,``);if(!C||C.startsWith(`#`)||C.startsWith(`;`))continue;let F=C.indexOf(`=`);if(F<0)continue;let I=C.slice(0,F).trim(),H=expandEnv(stripQuotes(C.slice(F+1).trim()));if(I===`registry`){S.registry=ensureTrailingSlash$1(H);continue}let W=I.match(/^(@[^:]+):registry$/);if(W){S.scopes[W[1]]=ensureTrailingSlash$1(H);continue}let q=I.match(/^\/\/(.+):_authToken$/);if(q){S.authTokens[normalizeAuthHost(q[1])]=H;continue}let Y=I.match(/^\/\/(.+):username$/);if(Y){(N[normalizeAuthHost(Y[1])]??={}).user=H;continue}let X=I.match(/^\/\/(.+):_password$/);if(X){let n=base64Decode(H);(N[normalizeAuthHost(X[1])]??={}).pass=n;continue}}for(let[n,C]of Object.entries(N))C.user&&C.pass!==void 0&&(S.basicAuth[n]={username:C.user,password:C.pass});return S}function normalizeAuthHost(n){return`//${n.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(n){return n.endsWith(`/`)?n:n+`/`}function stripQuotes(n){return n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`)?n.slice(1,-1):n}function expandEnv(n){return n.replace(/\$\{([A-Z0-9_]+)\}/gi,(n,S)=>globalThis.process?.env?.[S]??``)}function base64Decode(n){return atob(n)}var qf,Jf=__esmMin(()=>{qf=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`)});async function fetchWithRetry(n,S,C){let N=C.fetch??globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=Math.max(0,C.retries??3),I=Math.max(0,C.retryDelayMs??250),H=Math.max(0,C.timeoutMs??3e4),W=C.retryNotFound??!1,q=0,Y,X=0;for(;;){if(S.signal?.aborted)throw signalAbortError(S.signal);let Z=H>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${H}ms`)),H),ne=composeSignals(S.signal,Z?.signal);try{let C=await N(n,{...S,signal:ne}),I=isRetryableStatus(C.status)||W&&C.status===404;if(C.ok||!I||q>=F)return C;try{await C.arrayBuffer()}catch{}Y=Error(`HTTP ${C.status} ${C.statusText}`)}catch(C){let N=Z!==null&&Z.signal.aborted,I=S.signal?.aborted===!0;if(N&&!I){if(X++,q>=F)throw new RegistryTimeoutError(n,H,X);Y=C}else if(I)throw signalAbortError(S.signal);else{if(!isRetryableError(C)||q>=F)throw C;Y=C}}finally{te!==null&&clearTimeout(te)}let re=Math.min(I*2**q,8e3);C.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,S.signal),q++}}function composeSignals(n,S){return n?S?AbortSignal.any([n,S]):n:S}function isRetryableStatus(n){return n===408||n===425||n===429||n===500||n===502||n===503||n===504||n===521||n===522||n===524||n===525}function isRetryableError(n){if(n&&typeof n==`object`&&`name`in n&&n.name===`AbortError`)return!1;if(n instanceof TypeError)return!0;if(n&&typeof n==`object`&&`name`in n){let S=n.name;if(S===`FetchError`)return!0;if(S===`AbortError`)return!1}let S=n?.cause;if(S&&typeof S==`object`&&`code`in S){let n=S.code;if(typeof n==`string`)return n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ENETUNREACH`||n===`ENOTFOUND`||n===`ETIMEDOUT`||n===`EAI_AGAIN`||n===`UND_ERR_SOCKET`||n===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n),onAbort=()=>{clearTimeout(F),N(signalAbortError(S))};if(S?.aborted){clearTimeout(F),N(signalAbortError(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}var Yf=__esmMin(()=>{Kf(),__name$1(delay$1,`delay`)});async function verifyIntegrity(n,S){let C=S.trim().split(/\s+/);for(let S of C){let C=S.indexOf(`-`);if(C<0)continue;let N=S.slice(0,C).toLowerCase(),F=S.slice(C+1),I=globalThis.crypto?.subtle;if(!I)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let H=subriToWebCryptoAlgo(N);if(!H)continue;let W=await I.digest(H,dataAsArrayBuffer(n));if(bytesToBase64(new Uint8Array(W))===F)return!0}return!1}function subriToWebCryptoAlgo(n){switch(n){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(n){if(n.byteOffset===0&&n.byteLength===n.buffer.byteLength)return n.buffer;let S=new Uint8Array(n.byteLength);return S.set(n),S.buffer}function bytesToBase64(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return btoa(S)}var Xf=__esmMin(()=>{});function assertPackument(n,S){if(!S||typeof S!=`object`)throw TypeError(`registry: ${n} packument is not an object`);let C=S;if(typeof C.name!=`string`)throw TypeError(`registry: ${n} packument missing string name`);if(!C.versions||typeof C.versions!=`object`)throw TypeError(`registry: ${n} packument missing versions map`)}function packumentUrl(n,S){let C=ensureTrailingSlash$1(S);if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw TypeError(`Invalid scoped package name: ${n}`);let N=n.slice(0,S),F=n.slice(S+1);return`${C}${encodeURIComponent(N)}/${encodeURIComponent(F)}`}return`${C}${encodeURIComponent(n)}`}async function fetchPackumentConditional(n,S={}){let C=packumentUrl(n,S.registry??registryFor(n,S.npmrc)),N=buildHeaders(C,{...S,acceptEncoding:`gzip`});N.accept??=S.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,S.ifNoneMatch&&(N[`if-none-match`]=S.ifNoneMatch);let F=await fetchWithRetry(C,{headers:N,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry});if(F.status===304){try{await F.arrayBuffer()}catch{}return{status:`not-modified`,etag:S.ifNoneMatch}}if(!F.ok)throw F.status===404||F.status===406?new PackageNotFoundError(n,C):Error(`registry GET ${C} -> ${F.status} ${F.statusText}`);let I=F.headers.get(`etag`)??void 0,H=await decodeJsonBody(F);return assertPackument(n,H),{status:`fresh`,packument:H,etag:I}}async function decodeJsonBody(n){return n.json()}async function fetchPackument(n,S={}){let C=await fetchPackumentConditional(n,S);if(!C.packument)throw Error(`registry: ${n} returned 304 Not Modified to an unconditional request`);return C.packument}var Zf=__esmMin(()=>{Gf(),Kf(),Jf(),Yf()});async function fetchTarball(n,S={}){let C=buildHeaders(n,{...S,acceptEncoding:`identity`});C.accept??=`application/octet-stream`;let N=await fetchWithRetry(n,{headers:C,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry,retryNotFound:S.retryNotFound??!0});if(!N.ok)throw Error(`tarball GET ${n} -> ${N.status} ${N.statusText}`);let F=new Uint8Array(await N.arrayBuffer());if(S.integrity&&!await verifyIntegrity(F,S.integrity))throw new IntegrityError(n,S.integrity);return F}var Qf=__esmMin(()=>{Gf(),Kf(),Yf(),Xf()});async function whoami(n,S){let C=`${ensureTrailingSlash$1(n)}-/whoami`,N=buildHeaders(C,{npmrc:S});N.accept=`application/json`;let F=globalThis.fetch;if(!F)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let I=await F(C,{method:`GET`,headers:N});if(!I.ok)throw Error(`whoami GET ${C} -> ${I.status} ${I.statusText}`);let H=await I.json();if(H&&typeof H==`object`&&`username`in H){let n=H.username;if(typeof n==`string`&&n.length>0)return{username:n}}return{}}var $f=__esmMin(()=>{Gf(),Jf()}),ep=__esmMin(()=>{Gf(),Jf(),Zf(),Qf(),$f()});function escapePackageName(n){return n.replace(`/`,`%2f`)}function buildPublishHeaders(n,S){let C=buildHeaders(n,{npmrc:S.npmrc});return C[`content-type`]=`application/json`,C[`npm-command`]=`publish`,C[`npm-auth-type`]=S.otp?`legacy`:`web`,C[`user-agent`]=S.userAgent??defaultUserAgent(),S.otp&&(C[`npm-otp`]=S.otp),S.authorization&&(C.authorization=S.authorization),C}function cliVersion(){return tp===void 0&&(tp=`0.46.0`),tp}function cliPackageDir(){let n=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,S;try{S=Ps(n||fileURLToPath(import.meta.url))}catch{return null}for(let n=0;n<12;n++){try{if(JSON.parse(readFileSync(`${S}/package.json`,`utf8`)).name===`@gjsify/cli`)return S}catch{}let n=Ps(S);if(n===S)break;S=n}return null}function defaultUserAgent(){let n=globalThis.process,S=n?.arch??`x64`,C=n?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${C} ${S})`}var tp,np=__esmMin(()=>{Vl(),Hs(),gn(),ep()}),rp,ip=__esmMin(()=>{rp=`gjsify`}),ap=__commonJSMin(((n,S)=>{let C=(Hs(),__toCommonJS(Es)),N=(gs(),__toCommonJS(fs)),F=(Vl(),__toCommonJS(Rl)),resolveFrom=(n,S,I)=>{if(typeof n!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof n}\``);if(typeof S!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof S}\``);try{n=F.realpathSync(n)}catch(S){if(S.code===`ENOENT`)n=C.resolve(n);else if(I)return null;else throw S}let H=C.join(n,`noop.js`),resolveFileName=()=>N._resolveFilename(S,{id:H,filename:H,paths:N._nodeModulePaths(n)});if(I)try{return resolveFileName()}catch{return null}return resolveFileName()};S.exports=(n,S)=>resolveFrom(n,S),S.exports.silent=(n,S)=>resolveFrom(n,S,!0)})),op=__commonJSMin(((n,S)=>{let callsites=()=>{let n=Error.prepareStackTrace;Error.prepareStackTrace=(n,S)=>S;let S=Error().stack.slice(1);return Error.prepareStackTrace=n,S};S.exports=callsites,S.exports.default=callsites})),sp=__commonJSMin(((n,S)=>{let C=op();S.exports=n=>{let S=C();if(!n)return S[2].getFileName();let N=!1;S.shift();for(let C of S){let S=C.getFileName();if(typeof S==`string`){if(S===n){N=!0;continue}if(S!==`module.js`&&N&&S!==n)return S}}}})),lp=__commonJSMin(((n,S)=>{var{__gjsifyModuleDir:C,__gjsifyModuleFile:N}=(Ks(),__toCommonJS(Us)),F=C(`import-fresh/index.js`),I=N(`import-fresh/index.js`);let H=(Hs(),__toCommonJS(Es)),W=ap(),q=sp();S.exports=n=>{if(typeof n!=`string`)throw TypeError(`Expected a string`);let S=q(I),C=S?H.dirname(S):F,N=W(C,n),Y=X.cache[N];if(Y&&Y.parent){let n=Y.parent.children.length;for(;n--;)Y.parent.children[n].id===N&&Y.parent.children.splice(n,1)}delete X.cache[N];let Z=X.cache[S];return Z===void 0||Z.require===void 0?X(N):Z.require(N)}})),up=__commonJSMin(((n,S)=>{S.exports=function isArrayish(n){return n?n instanceof Array||Array.isArray(n)||n.length>=0&&n.splice instanceof Function:!1}})),dp=__commonJSMin(((n,S)=>{var C=(Ac(),__toCommonJS(Ec)),N=up(),F=function errorEx(n,S){(!n||n.constructor!==String)&&(S=n||{},n=Error.name);var F=function ErrorEXError(C){if(!this)return new ErrorEXError(C);C=C instanceof Error?C.message:C||this.message,Error.call(this,C),Error.captureStackTrace(this,F),this.name=n,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var n=C.split(/\r?\n/g);for(var F in S)if(S.hasOwnProperty(F)){var I=S[F];`message`in I&&(n=I.message(this[F],n)||n,N(n)||(n=[n]))}return n.join(`
|
|
122
|
+
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)}}}[of](n){objectKeys(__classPrivateFieldGet(this,Bd,`f`)).forEach(S=>{if((n=>n===`configObjects`)(S))return;let C=__classPrivateFieldGet(this,Bd,`f`)[S];Array.isArray(C)?C.includes(n)&&C.splice(C.indexOf(n),1):typeof C==`object`&&delete C[n]}),delete __classPrivateFieldGet(this,$d,`f`).getDescriptions()[n]}[sf](n,S,C){__classPrivateFieldGet(this,Ad,`f`)[C]||(__classPrivateFieldGet(this,Yd,`f`).process.emitWarning(n,S),__classPrivateFieldGet(this,Ad,`f`)[C]=!0)}[cf](){__classPrivateFieldGet(this,Md,`f`).push({options:__classPrivateFieldGet(this,Bd,`f`),configObjects:__classPrivateFieldGet(this,Bd,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,jd,`f`),groups:__classPrivateFieldGet(this,Pd,`f`),strict:__classPrivateFieldGet(this,Xd,`f`),strictCommands:__classPrivateFieldGet(this,Zd,`f`),strictOptions:__classPrivateFieldGet(this,Qd,`f`),completionCommand:__classPrivateFieldGet(this,Ed,`f`),output:__classPrivateFieldGet(this,zd,`f`),exitError:__classPrivateFieldGet(this,Od,`f`),hasOutput:__classPrivateFieldGet(this,Fd,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Ud,`f`),parseContext:__classPrivateFieldGet(this,Wd,`f`)}),__classPrivateFieldGet(this,$d,`f`).freeze(),__classPrivateFieldGet(this,nf,`f`).freeze(),__classPrivateFieldGet(this,Sd,`f`).freeze(),__classPrivateFieldGet(this,Nd,`f`).freeze()}[lf](){let n=``,S;return S=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Yd,`f`).process.argv()[0])?__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(0,1),n=S.map(n=>{let S=this[Pf](__classPrivateFieldGet(this,Cd,`f`),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&S.length<n.length?S:n}).join(` `).trim(),__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Yd,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&(n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Yd,`f`).path.dirname(__classPrivateFieldGet(this,Yd,`f`).process.execPath())}/`,``)),n}[uf](){return __classPrivateFieldGet(this,Hd,`f`)}[df](){return __classPrivateFieldGet(this,ef,`f`)}[ff](){if(!__classPrivateFieldGet(this,kd,`f`))return;let n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(n.replace(/[.:].*/,``))}[pf](){return this[hf]().version||`unknown`}[mf](n){let S=n[`--`]?n[`--`]:n._;for(let n=0,C;(C=S[n])!==void 0;n++)__classPrivateFieldGet(this,Yd,`f`).Parser.looksLikeNumber(C)&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))&&(S[n]=Number(C));return n}[hf](n){let S=n||`*`;if(__classPrivateFieldGet(this,Gd,`f`)[S])return __classPrivateFieldGet(this,Gd,`f`)[S];let C={};try{let S=n||__classPrivateFieldGet(this,Yd,`f`).mainFilename;__classPrivateFieldGet(this,Yd,`f`).path.extname(S)&&(S=__classPrivateFieldGet(this,Yd,`f`).path.dirname(S));let N=__classPrivateFieldGet(this,Yd,`f`).findUp(S,(n,S)=>{if(S.includes(`package.json`))return`package.json`});assertNotStrictEqual(N,void 0,__classPrivateFieldGet(this,Yd,`f`)),C=JSON.parse(__classPrivateFieldGet(this,Yd,`f`).readFileSync(N,`utf8`))}catch{}return __classPrivateFieldGet(this,Gd,`f`)[S]=C||{},__classPrivateFieldGet(this,Gd,`f`)[S]}[gf](n,S){S=[].concat(S),S.forEach(S=>{S=this[bf](S),__classPrivateFieldGet(this,Bd,`f`)[n].push(S)})}[_f](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=C})}[vf](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=(__classPrivateFieldGet(this,Bd,`f`)[n][S]||[]).concat(C)})}[yf](n,S,C,N,F){if(Array.isArray(C))C.forEach(S=>{n(S,N)});else if((n=>typeof n==`object`)(C))for(let S of objectKeys(C))n(S,C[S]);else F(S,this[bf](C),N)}[bf](n){return n===`__proto__`?`___proto___`:n}[xf](n,S){return this[_f](this[xf].bind(this),`key`,n,S),this}[Sf](){var n,S,C,N,F,I,H,W,q,Y,X,Z;let te=__classPrivateFieldGet(this,Md,`f`).pop();assertNotStrictEqual(te,void 0,__classPrivateFieldGet(this,Yd,`f`));let ne;n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,Z=this,{options:{set value(S){__classPrivateFieldSet(n,Bd,S,`f`)}}.value,configObjects:ne,exitProcess:{set value(n){__classPrivateFieldSet(S,jd,n,`f`)}}.value,groups:{set value(n){__classPrivateFieldSet(C,Pd,n,`f`)}}.value,output:{set value(n){__classPrivateFieldSet(N,zd,n,`f`)}}.value,exitError:{set value(n){__classPrivateFieldSet(F,Od,n,`f`)}}.value,hasOutput:{set value(n){__classPrivateFieldSet(I,Fd,n,`f`)}}.value,parsed:this.parsed,strict:{set value(n){__classPrivateFieldSet(H,Xd,n,`f`)}}.value,strictCommands:{set value(n){__classPrivateFieldSet(W,Zd,n,`f`)}}.value,strictOptions:{set value(n){__classPrivateFieldSet(q,Qd,n,`f`)}}.value,completionCommand:{set value(n){__classPrivateFieldSet(Y,Ed,n,`f`)}}.value,parseFn:{set value(n){__classPrivateFieldSet(X,Ud,n,`f`)}}.value,parseContext:{set value(n){__classPrivateFieldSet(Z,Wd,n,`f`)}}.value}=te,__classPrivateFieldGet(this,Bd,`f`).configObjects=ne,__classPrivateFieldGet(this,$d,`f`).unfreeze(),__classPrivateFieldGet(this,nf,`f`).unfreeze(),__classPrivateFieldGet(this,Sd,`f`).unfreeze(),__classPrivateFieldGet(this,Nd,`f`).unfreeze()}[Cf](n,S){return maybeAsyncResult(S,S=>(n(S),S))}getInternalMethods(){return{getCommandInstance:this[wf].bind(this),getContext:this[Tf].bind(this),getHasOutput:this[Ef].bind(this),getLoggerInstance:this[Df].bind(this),getParseContext:this[Of].bind(this),getParserConfiguration:this[uf].bind(this),getUsageConfiguration:this[df].bind(this),getUsageInstance:this[kf].bind(this),getValidationInstance:this[Af].bind(this),hasParseCallback:this[jf].bind(this),isGlobalContext:this[Mf].bind(this),postProcess:this[Nf].bind(this),reset:this[Ff].bind(this),runValidation:this[Lf].bind(this),runYargsParserAndExecuteCommands:this[If].bind(this),setHasOutput:this[Rf].bind(this)}}[wf](){return __classPrivateFieldGet(this,Sd,`f`)}[Tf](){return __classPrivateFieldGet(this,wd,`f`)}[Ef](){return __classPrivateFieldGet(this,Fd,`f`)}[Df](){return __classPrivateFieldGet(this,Rd,`f`)}[Of](){return __classPrivateFieldGet(this,Wd,`f`)||{}}[kf](){return __classPrivateFieldGet(this,$d,`f`)}[Af](){return __classPrivateFieldGet(this,nf,`f`)}[jf](){return!!__classPrivateFieldGet(this,Ud,`f`)}[Mf](){return __classPrivateFieldGet(this,Ld,`f`)}[Nf](n,S,C,N){return C||isPromise(n)?n:(S||(n=this[rf](n)),(this[uf]()[`parse-positional-numbers`]||this[uf]()[`parse-positional-numbers`]===void 0)&&(n=this[mf](n)),N&&(n=applyMiddleware(n,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)),n)}[Ff](n={}){__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`)||{},`f`);let S={};S.local=__classPrivateFieldGet(this,Bd,`f`).local||[],S.configObjects=__classPrivateFieldGet(this,Bd,`f`).configObjects||[];let C={};return S.local.forEach(S=>{C[S]=!0,(n[S]||[]).forEach(n=>{C[n]=!0})}),Object.assign(__classPrivateFieldGet(this,Kd,`f`),Object.keys(__classPrivateFieldGet(this,Pd,`f`)).reduce((n,S)=>{let N=__classPrivateFieldGet(this,Pd,`f`)[S].filter(n=>!(n in C));return N.length>0&&(n[S]=N),n},{})),__classPrivateFieldSet(this,Pd,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(n=>{S[n]=(__classPrivateFieldGet(this,Bd,`f`)[n]||[]).filter(n=>!C[n])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(n=>{S[n]=objFilter(__classPrivateFieldGet(this,Bd,`f`)[n],n=>!C[n])}),S.envPrefix=__classPrivateFieldGet(this,Bd,`f`).envPrefix,__classPrivateFieldSet(this,Bd,S,`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`)?__classPrivateFieldGet(this,$d,`f`).reset(C):usage(this,__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`)?__classPrivateFieldGet(this,nf,`f`).reset(C):validation(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`)?__classPrivateFieldGet(this,Sd,`f`).reset():command(__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,nf,`f`),__classPrivateFieldGet(this,Nd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Td,`f`)||__classPrivateFieldSet(this,Td,completion(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Sd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Nd,`f`).reset(),__classPrivateFieldSet(this,Ed,null,`f`),__classPrivateFieldSet(this,zd,``,`f`),__classPrivateFieldSet(this,Od,null,`f`),__classPrivateFieldSet(this,Fd,!1,`f`),this.parsed=!1,this}[Pf](n,S){return __classPrivateFieldGet(this,Yd,`f`).path.relative(n,S)}[If](n,S,C,N=0,F=!1){let I=!!C||F;n||=__classPrivateFieldGet(this,qd,`f`),__classPrivateFieldGet(this,Bd,`f`).__=__classPrivateFieldGet(this,Yd,`f`).y18n.__,__classPrivateFieldGet(this,Bd,`f`).configuration=this[uf]();let H=!!__classPrivateFieldGet(this,Bd,`f`).configuration[`populate--`],W=Object.assign({},__classPrivateFieldGet(this,Bd,`f`).configuration,{"populate--":!0}),q=__classPrivateFieldGet(this,Yd,`f`).Parser.detailed(n,Object.assign({},__classPrivateFieldGet(this,Bd,`f`),{configuration:{"parse-positional-numbers":!1,...W}})),Y=Object.assign(q.argv,__classPrivateFieldGet(this,Wd,`f`)),X,Z=q.aliases,te=!1,ne=!1;Object.keys(Y).forEach(n=>{n===__classPrivateFieldGet(this,Id,`f`)&&Y[n]?te=!0:n===__classPrivateFieldGet(this,tf,`f`)&&Y[n]&&(ne=!0)}),Y.$0=this.$0,this.parsed=q,N===0&&__classPrivateFieldGet(this,$d,`f`).clearCachedHelpMessage();try{if(this[ff](),S)return this[Nf](Y,H,!!C,!1);__classPrivateFieldGet(this,Id,`f`)&&[__classPrivateFieldGet(this,Id,`f`)].concat(Z[__classPrivateFieldGet(this,Id,`f`)]||[]).filter(n=>n.length>1).includes(``+Y._[Y._.length-1])&&(Y._.pop(),te=!0),__classPrivateFieldSet(this,Ld,!1,`f`);let W=__classPrivateFieldGet(this,Sd,`f`).getCommands(),re=__classPrivateFieldGet(this,Td,`f`)?.completionKey?[__classPrivateFieldGet(this,Td,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Td,`f`)?.completionKey]??[]].some(n=>Object.prototype.hasOwnProperty.call(Y,n)):!1,ie=te||re||F;if(Y._.length){if(W.length){let n;for(let S=N||0,I;Y._[S]!==void 0;S++)if(I=String(Y._[S]),W.includes(I)&&I!==__classPrivateFieldGet(this,Ed,`f`)){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(I,this,q,S+1,F,te||ne||F);return this[Nf](n,H,!!C,!1)}else if(!n&&I!==__classPrivateFieldGet(this,Ed,`f`)){n=I;break}!__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Jd,`f`)&&n&&!ie&&__classPrivateFieldGet(this,nf,`f`).recommendCommands(n,W)}__classPrivateFieldGet(this,Ed,`f`)&&Y._.includes(__classPrivateFieldGet(this,Ed,`f`))&&!re&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&!ie){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(null,this,q,0,F,te||ne||F);return this[Nf](n,H,!!C,!1)}if(re){__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),n=[].concat(n);let S=n.slice(n.indexOf(`--${__classPrivateFieldGet(this,Td,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Td,`f`).getCompletion(S,(n,S)=>{if(n)throw new ns(n.message);(S||[]).forEach(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n)}),this.exit(0)}),this[Nf](Y,!H,!!C,!1)}if(__classPrivateFieldGet(this,Fd,`f`)||(te?(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,this.showHelp(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n),this.exit(0)})):ne&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,__classPrivateFieldGet(this,$d,`f`).showVersion(`log`),this.exit(0))),!I&&__classPrivateFieldGet(this,Bd,`f`).skipValidation.length>0&&(I=Object.keys(Y).some(n=>__classPrivateFieldGet(this,Bd,`f`).skipValidation.indexOf(n)>=0&&Y[n]===!0)),!I){if(q.error)throw new ns(q.error.message);if(!re){let n=this[Lf](Z,{},q.error);C||(X=applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!0)),X=this[Cf](n,X??Y),isPromise(X)&&!C&&(X=X.then(()=>applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)))}}}catch(n){if(n instanceof ns)__classPrivateFieldGet(this,$d,`f`).fail(n.message,n);else throw n}return this[Nf](X??Y,H,!!C,!0)}[Lf](n,S,C,N){let F={...this.getDemandedOptions()};return I=>{if(C)throw new ns(C.message);__classPrivateFieldGet(this,nf,`f`).nonOptionCount(I),__classPrivateFieldGet(this,nf,`f`).requiredArguments(I,F);let H=!1;__classPrivateFieldGet(this,Zd,`f`)&&(H=__classPrivateFieldGet(this,nf,`f`).unknownCommands(I)),__classPrivateFieldGet(this,Xd,`f`)&&!H?__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,S,!!N):__classPrivateFieldGet(this,Qd,`f`)&&__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,{},!1,!1),__classPrivateFieldGet(this,nf,`f`).limitedChoices(I),__classPrivateFieldGet(this,nf,`f`).implications(I),__classPrivateFieldGet(this,nf,`f`).conflicting(I)}}[Rf](){__classPrivateFieldSet(this,Fd,!0,`f`)}[zf](n){if(typeof n==`string`)__classPrivateFieldGet(this,Bd,`f`).key[n]=!0;else for(let S of n)__classPrivateFieldGet(this,Bd,`f`).key[S]=!0}}}),Hf,Uf=__esmMin(()=>{nd(),Vf(),Hf=YargsFactory(td)});function classifyCliFailure(n,S){return typeof n==`string`&&n.length>0?{kind:`usage`,message:n}:{kind:`runtime`}}var Wf=__esmMin(()=>{});function buildHeaders(n,S){let C={"user-agent":`gjsify-install/0.47.0`,"accept-encoding":S.acceptEncoding??`identity`};if(S.npmrc){let N=resolveAuthForUrl(n,S.npmrc);N&&(C.authorization=N)}if(S.headers)for(let[n,N]of Object.entries(S.headers))C[n.toLowerCase()]=N;return C}function resolveAuthForUrl(n,S){let C=pathPrefixes(new URL(n));for(let n of C){let C=S.authTokens[n];if(C)return`Bearer ${C}`;let N=S.basicAuth[n];if(N)return`Basic ${btoa(`${N.username}:${N.password}`)}`}return null}function pathPrefixes(n){let S=n.pathname.split(`/`).filter(Boolean),C=[];for(let N=S.length;N>=0;N--){let F=S.slice(0,N).join(`/`);C.push(F?`//${n.host}/${F}`:`//${n.host}`)}return C}var Gf=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,Kf=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(n,S){super(`Package not found in registry: ${n} (${S})`),this.name=n,this.url=S,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(n,S){super(`Tarball integrity mismatch for ${n} (expected ${S})`),this.url=n,this.integrity=S,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(n,S,C){let N=Math.round(S/100)/10,F=Math.round(S*C/100)/10;super(`@gjsify/npm-registry: GET ${n} timed out after ${N}s × ${C} attempt(s) (total ~${F}s). This usually means the registry CDN is slow or unreachable.`),this.url=n,this.timeoutMs=S,this.attempts=C,this.name=`RegistryTimeoutError`}}});function registryFor(n,S){if(S&&n.startsWith(`@`)){let C=n.slice(0,n.indexOf(`/`)),N=S.scopes[C];if(N)return ensureTrailingSlash$1(N)}return S?.registry?ensureTrailingSlash$1(S.registry):qf}function parseNpmrc(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}},C=n.split(/\r?\n/),N={};for(let n of C){let C=n.replace(/^\s+|\s+$/g,``);if(!C||C.startsWith(`#`)||C.startsWith(`;`))continue;let F=C.indexOf(`=`);if(F<0)continue;let I=C.slice(0,F).trim(),H=expandEnv(stripQuotes(C.slice(F+1).trim()));if(I===`registry`){S.registry=ensureTrailingSlash$1(H);continue}let W=I.match(/^(@[^:]+):registry$/);if(W){S.scopes[W[1]]=ensureTrailingSlash$1(H);continue}let q=I.match(/^\/\/(.+):_authToken$/);if(q){S.authTokens[normalizeAuthHost(q[1])]=H;continue}let Y=I.match(/^\/\/(.+):username$/);if(Y){(N[normalizeAuthHost(Y[1])]??={}).user=H;continue}let X=I.match(/^\/\/(.+):_password$/);if(X){let n=base64Decode(H);(N[normalizeAuthHost(X[1])]??={}).pass=n;continue}}for(let[n,C]of Object.entries(N))C.user&&C.pass!==void 0&&(S.basicAuth[n]={username:C.user,password:C.pass});return S}function normalizeAuthHost(n){return`//${n.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(n){return n.endsWith(`/`)?n:n+`/`}function stripQuotes(n){return n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`)?n.slice(1,-1):n}function expandEnv(n){return n.replace(/\$\{([A-Z0-9_]+)\}/gi,(n,S)=>globalThis.process?.env?.[S]??``)}function base64Decode(n){return atob(n)}var qf,Jf=__esmMin(()=>{qf=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`)});async function fetchWithRetry(n,S,C){let N=C.fetch??globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=Math.max(0,C.retries??3),I=Math.max(0,C.retryDelayMs??250),H=Math.max(0,C.timeoutMs??3e4),W=C.retryNotFound??!1,q=0,Y,X=0;for(;;){if(S.signal?.aborted)throw signalAbortError(S.signal);let Z=H>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${H}ms`)),H),ne=composeSignals(S.signal,Z?.signal);try{let C=await N(n,{...S,signal:ne}),I=isRetryableStatus(C.status)||W&&C.status===404;if(C.ok||!I||q>=F)return C;try{await C.arrayBuffer()}catch{}Y=Error(`HTTP ${C.status} ${C.statusText}`)}catch(C){let N=Z!==null&&Z.signal.aborted,I=S.signal?.aborted===!0;if(N&&!I){if(X++,q>=F)throw new RegistryTimeoutError(n,H,X);Y=C}else if(I)throw signalAbortError(S.signal);else{if(!isRetryableError(C)||q>=F)throw C;Y=C}}finally{te!==null&&clearTimeout(te)}let re=Math.min(I*2**q,8e3);C.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,S.signal),q++}}function composeSignals(n,S){return n?S?AbortSignal.any([n,S]):n:S}function isRetryableStatus(n){return n===408||n===425||n===429||n===500||n===502||n===503||n===504||n===521||n===522||n===524||n===525}function isRetryableError(n){if(n&&typeof n==`object`&&`name`in n&&n.name===`AbortError`)return!1;if(n instanceof TypeError)return!0;if(n&&typeof n==`object`&&`name`in n){let S=n.name;if(S===`FetchError`)return!0;if(S===`AbortError`)return!1}let S=n?.cause;if(S&&typeof S==`object`&&`code`in S){let n=S.code;if(typeof n==`string`)return n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ENETUNREACH`||n===`ENOTFOUND`||n===`ETIMEDOUT`||n===`EAI_AGAIN`||n===`UND_ERR_SOCKET`||n===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n),onAbort=()=>{clearTimeout(F),N(signalAbortError(S))};if(S?.aborted){clearTimeout(F),N(signalAbortError(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}var Yf=__esmMin(()=>{Kf(),__name$1(delay$1,`delay`)});async function verifyIntegrity(n,S){let C=S.trim().split(/\s+/);for(let S of C){let C=S.indexOf(`-`);if(C<0)continue;let N=S.slice(0,C).toLowerCase(),F=S.slice(C+1),I=globalThis.crypto?.subtle;if(!I)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let H=subriToWebCryptoAlgo(N);if(!H)continue;let W=await I.digest(H,dataAsArrayBuffer(n));if(bytesToBase64(new Uint8Array(W))===F)return!0}return!1}function subriToWebCryptoAlgo(n){switch(n){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(n){if(n.byteOffset===0&&n.byteLength===n.buffer.byteLength)return n.buffer;let S=new Uint8Array(n.byteLength);return S.set(n),S.buffer}function bytesToBase64(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return btoa(S)}var Xf=__esmMin(()=>{});function assertPackument(n,S){if(!S||typeof S!=`object`)throw TypeError(`registry: ${n} packument is not an object`);let C=S;if(typeof C.name!=`string`)throw TypeError(`registry: ${n} packument missing string name`);if(!C.versions||typeof C.versions!=`object`)throw TypeError(`registry: ${n} packument missing versions map`)}function packumentUrl(n,S){let C=ensureTrailingSlash$1(S);if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw TypeError(`Invalid scoped package name: ${n}`);let N=n.slice(0,S),F=n.slice(S+1);return`${C}${encodeURIComponent(N)}/${encodeURIComponent(F)}`}return`${C}${encodeURIComponent(n)}`}async function fetchPackumentConditional(n,S={}){let C=packumentUrl(n,S.registry??registryFor(n,S.npmrc)),N=buildHeaders(C,{...S,acceptEncoding:`gzip`});N.accept??=S.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,S.ifNoneMatch&&(N[`if-none-match`]=S.ifNoneMatch);let F=await fetchWithRetry(C,{headers:N,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry});if(F.status===304){try{await F.arrayBuffer()}catch{}return{status:`not-modified`,etag:S.ifNoneMatch}}if(!F.ok)throw F.status===404||F.status===406?new PackageNotFoundError(n,C):Error(`registry GET ${C} -> ${F.status} ${F.statusText}`);let I=F.headers.get(`etag`)??void 0,H=await decodeJsonBody(F);return assertPackument(n,H),{status:`fresh`,packument:H,etag:I}}async function decodeJsonBody(n){return n.json()}async function fetchPackument(n,S={}){let C=await fetchPackumentConditional(n,S);if(!C.packument)throw Error(`registry: ${n} returned 304 Not Modified to an unconditional request`);return C.packument}var Zf=__esmMin(()=>{Gf(),Kf(),Jf(),Yf()});async function fetchTarball(n,S={}){let C=buildHeaders(n,{...S,acceptEncoding:`identity`});C.accept??=`application/octet-stream`;let N=await fetchWithRetry(n,{headers:C,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry,retryNotFound:S.retryNotFound??!0});if(!N.ok)throw Error(`tarball GET ${n} -> ${N.status} ${N.statusText}`);let F=new Uint8Array(await N.arrayBuffer());if(S.integrity&&!await verifyIntegrity(F,S.integrity))throw new IntegrityError(n,S.integrity);return F}var Qf=__esmMin(()=>{Gf(),Kf(),Yf(),Xf()});async function whoami(n,S){let C=`${ensureTrailingSlash$1(n)}-/whoami`,N=buildHeaders(C,{npmrc:S});N.accept=`application/json`;let F=globalThis.fetch;if(!F)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let I=await F(C,{method:`GET`,headers:N});if(!I.ok)throw Error(`whoami GET ${C} -> ${I.status} ${I.statusText}`);let H=await I.json();if(H&&typeof H==`object`&&`username`in H){let n=H.username;if(typeof n==`string`&&n.length>0)return{username:n}}return{}}var $f=__esmMin(()=>{Gf(),Jf()}),ep=__esmMin(()=>{Gf(),Jf(),Zf(),Qf(),$f()});function escapePackageName(n){return n.replace(`/`,`%2f`)}function buildPublishHeaders(n,S){let C=buildHeaders(n,{npmrc:S.npmrc});return C[`content-type`]=`application/json`,C[`npm-command`]=`publish`,C[`npm-auth-type`]=S.otp?`legacy`:`web`,C[`user-agent`]=S.userAgent??defaultUserAgent(),S.otp&&(C[`npm-otp`]=S.otp),S.authorization&&(C.authorization=S.authorization),C}function cliVersion(){return tp===void 0&&(tp=`0.47.0`),tp}function cliPackageDir(){let n=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,S;try{S=Ps(n||fileURLToPath(import.meta.url))}catch{return null}for(let n=0;n<12;n++){try{if(JSON.parse(readFileSync(`${S}/package.json`,`utf8`)).name===`@gjsify/cli`)return S}catch{}let n=Ps(S);if(n===S)break;S=n}return null}function defaultUserAgent(){let n=globalThis.process,S=n?.arch??`x64`,C=n?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${C} ${S})`}var tp,np=__esmMin(()=>{Vl(),Hs(),gn(),ep()}),rp,ip=__esmMin(()=>{rp=`gjsify`}),ap=__commonJSMin(((n,S)=>{let C=(Hs(),__toCommonJS(Es)),N=(gs(),__toCommonJS(fs)),F=(Vl(),__toCommonJS(Rl)),resolveFrom=(n,S,I)=>{if(typeof n!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof n}\``);if(typeof S!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof S}\``);try{n=F.realpathSync(n)}catch(S){if(S.code===`ENOENT`)n=C.resolve(n);else if(I)return null;else throw S}let H=C.join(n,`noop.js`),resolveFileName=()=>N._resolveFilename(S,{id:H,filename:H,paths:N._nodeModulePaths(n)});if(I)try{return resolveFileName()}catch{return null}return resolveFileName()};S.exports=(n,S)=>resolveFrom(n,S),S.exports.silent=(n,S)=>resolveFrom(n,S,!0)})),op=__commonJSMin(((n,S)=>{let callsites=()=>{let n=Error.prepareStackTrace;Error.prepareStackTrace=(n,S)=>S;let S=Error().stack.slice(1);return Error.prepareStackTrace=n,S};S.exports=callsites,S.exports.default=callsites})),sp=__commonJSMin(((n,S)=>{let C=op();S.exports=n=>{let S=C();if(!n)return S[2].getFileName();let N=!1;S.shift();for(let C of S){let S=C.getFileName();if(typeof S==`string`){if(S===n){N=!0;continue}if(S!==`module.js`&&N&&S!==n)return S}}}})),lp=__commonJSMin(((n,S)=>{var{__gjsifyModuleDir:C,__gjsifyModuleFile:N}=(Ks(),__toCommonJS(Us)),F=C(`import-fresh/index.js`),I=N(`import-fresh/index.js`);let H=(Hs(),__toCommonJS(Es)),W=ap(),q=sp();S.exports=n=>{if(typeof n!=`string`)throw TypeError(`Expected a string`);let S=q(I),C=S?H.dirname(S):F,N=W(C,n),Y=X.cache[N];if(Y&&Y.parent){let n=Y.parent.children.length;for(;n--;)Y.parent.children[n].id===N&&Y.parent.children.splice(n,1)}delete X.cache[N];let Z=X.cache[S];return Z===void 0||Z.require===void 0?X(N):Z.require(N)}})),up=__commonJSMin(((n,S)=>{S.exports=function isArrayish(n){return n?n instanceof Array||Array.isArray(n)||n.length>=0&&n.splice instanceof Function:!1}})),dp=__commonJSMin(((n,S)=>{var C=(Ac(),__toCommonJS(Ec)),N=up(),F=function errorEx(n,S){(!n||n.constructor!==String)&&(S=n||{},n=Error.name);var F=function ErrorEXError(C){if(!this)return new ErrorEXError(C);C=C instanceof Error?C.message:C||this.message,Error.call(this,C),Error.captureStackTrace(this,F),this.name=n,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var n=C.split(/\r?\n/g);for(var F in S)if(S.hasOwnProperty(F)){var I=S[F];`message`in I&&(n=I.message(this[F],n)||n,N(n)||(n=[n]))}return n.join(`
|
|
123
123
|
`)},set:function(n){C=n}});var I=null,H=Object.getOwnPropertyDescriptor(this,`stack`),W=H.get,q=H.value;delete H.value,delete H.writable,H.set=function(n){I=n},H.get=function(){var n=(I||(W?W.call(this):q)).split(/\r?\n+/g);I||(n[0]=this.name+`: `+this.message);var C=1;for(var N in S)if(S.hasOwnProperty(N)){var F=S[N];if(`line`in F){var H=F.line(this[N]);H&&n.splice(C++,0,` `+H)}`stack`in F&&F.stack(this[N],n)}return n.join(`
|
|
124
124
|
`)},Object.defineProperty(this,"stack",H)};return Object.setPrototypeOf?(Object.setPrototypeOf(F.prototype,Error.prototype),Object.setPrototypeOf(F,Error)):C.inherits(F,Error),F};F.append=function(n,S){return{message:function(C,N){return C||=S,C&&(N[0]+=` `+n.replace(`%s`,C.toString())),N}}},F.line=function(n,S){return{line:function(C){return C||=S,C?n.replace(`%s`,C.toString()):null}}},S.exports=F})),fp=__commonJSMin(((n,S)=>{let hexify=n=>{let S=n.charCodeAt(0).toString(16).toUpperCase();return`0x`+(S.length%2?`0`:``)+S},parseError=(n,S,C)=>{if(!S)return{message:n.message+` while parsing empty string`,position:0};let N=n.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),F=N?+N[2]:n.message.match(/^Unexpected end of JSON.*/i)?S.length-1:null,I=N?n.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(N[1])} (${hexify(N[1])})`):n.message;if(F!=null){let n=F<=C?0:F-C,N=F+C>=S.length?S.length:F+C,H=(n===0?``:`...`)+S.slice(n,N)+(N===S.length?``:`...`);return{message:I+` while parsing ${S===H?``:`near `}${JSON.stringify(H)}`,position:F}}else return{message:I+` while parsing '${S.slice(0,C*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(n,S,C,N){C||=20;let F=parseError(n,S,C);super(F.message),Object.assign(this,F),this.code=`EJSONPARSE`,this.systemError=n,Error.captureStackTrace(this,N||this.constructor)}get name(){return this.constructor.name}set name(n){}get[Symbol.toStringTag](){return this.constructor.name}};let C=Symbol.for(`indent`),N=Symbol.for(`newline`),F=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,I=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(n,S,H)=>{let W=stripBOM(n);H||=20;try{let[,n=`
|
|
125
125
|
`,H=` `]=W.match(I)||W.match(F)||[,``,``],q=JSON.parse(W,S);return q&&typeof q==`object`&&(q[N]=n,q[C]=H),q}catch(S){if(typeof n!=`string`&&!Buffer.isBuffer(n)){let C=Array.isArray(n)&&n.length===0;throw Object.assign(TypeError(`Cannot parse ${C?`an empty array`:String(n)}`),{code:`EJSONPARSE`,systemError:S})}throw new JSONParseError(S,W,H,parseJson)}},stripBOM=n=>String(n).replace(/^\uFEFF/,``);S.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(n,S)=>{try{return JSON.parse(stripBOM(n),S)}catch{}}})),pp=__commonJSMin((n=>{n.__esModule=!0,n.LinesAndColumns=void 0;var S=`
|
|
@@ -894,7 +894,7 @@ case "\$1" in
|
|
|
894
894
|
exit 127 ;;
|
|
895
895
|
esac
|
|
896
896
|
exec "${F}" -m "${C}" run --node-script "$@"\n`,{mode:493}),chmodSync(I,493)}var wF,TF,EF,DF=__esmMin(()=>{Vl(),Dm(),Hs(),gn(),th(),AP(),CF(),qM(),wF=!1,TF=!1,EF=`node-shim`});function tokenizeSimpleCommand(n){let S=[],C=``,N=!1,F=null;for(let I=0;I<n.length;I++){let H=n[I];if(F===`'`){H===`'`?F=null:C+=H;continue}if(F===`"`){if(H===`"`)F=null;else if(H===`\\`&&(n[I+1]===`"`||n[I+1]===`\\`))C+=n[++I];else if(H===`$`||H==="`")return null;else C+=H;continue}if(H===`'`||H===`"`){F=H,N=!0;continue}if(H===` `||H===` `){N&&=(S.push(C),C=``,!1);continue}if(`|&;<>\`$()\\
|
|
897
|
-
\r*?{}[]~#!`.includes(H))return null;C+=H,N=!0}return F?null:(N&&S.push(C),S)}function gjsifyCommandArgv(n){let S=tokenizeSimpleCommand(n);return!S||S.length<2||S[0]!==`gjsify`?null:S.slice(1)}var OF=__esmMin(()=>{});function markDaemonCommand(){kF=!0}function isDaemonCommand(){return kF}var kF,AF=__esmMin(()=>{kF=!1});async function runTargetOnRuntime(n,S,C){if(!looksLikeFile(S))return ve.error(`gjsify run: --runtime ${n} needs a bundle FILE, but "${S}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${n===`gjs`?`gjs`:`node`} --outfile dist/app.${n===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let N=readPackageJson$1(js(process.cwd(),`package.json`)),F=checkRuntimeSupported(n,readDeclaredRuntimes(N),N?.name??S);if(!F.ok)return ve.error(`gjsify run: ${F.message}`),process.exit(1);let I=Os(S);n===`gjs`?await runGjsBundle(I,C,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(n,I,C,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(n){if(/\.gjs\.[mc]?js$/.test(n))return!0;try{let S=readFileSync(n,`utf-8`).slice(0,65536);return S.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(S)||/\bimports\.(?:gi|system)\b/.test(S)}catch{return!1}}function looksLikeFile(n){if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`/`)||n.includes(`/`)||n.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(n))return!0;try{return statSync(n).isFile()}catch{return!1}}async function runScriptInWorkspace(n,S,C){let N=findWorkspaceRoot(process.cwd())??process.cwd(),F;try{F=discoverWorkspaces(N)}catch(n){return ve.error(`gjsify run: could not read workspaces at ${N}: ${n.message}`),process.exit(1)}let I=F.find(S=>S.name===n||S.relativeLocation===n||Fs(S.location)===n);if(!I){let S=F.map(n=>n.relativeLocation).join(`, `)||`<none>`;return ve.error(`gjsify run: no workspace "${n}" under ${N} (available: ${S})`),process.exit(1)}await runScript(S,C,I.location)}async function runScript(n,S,C=process.cwd()){let N=js(C,`package.json`),F=readPackageJson$1(N);if(!F)return ve.error(`gjsify run: no package.json in ${C}`),process.exit(1);let I=F.scripts??{},H=I[n];if(typeof H!=`string`){let S=Object.keys(I).join(`, `)||`<none>`;return ve.error(`gjsify run: no script "${n}" in ${N} (available: ${S})`),process.exit(1)}let W=findWorkspaceRoot(C),q=[js(C,`node_modules`,`.bin`)];W&&W!==C&&q.push(js(W,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&q.unshift(process.env.GJSIFY_SHIM_DIR);let Y=nodeShimDir();Y&&q.unshift(Y);let X=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},Z={...process.env,...X,PATH:[...q,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:n,npm_package_name:F.name??``,npm_package_version:F.version??``},te=isGjs()?gjsifyInProcessArgv(H,S):null;if(te){process.env.PATH=Z.PATH,process.env.npm_lifecycle_event=Z.npm_lifecycle_event,process.env.npm_package_name=Z.npm_package_name,process.env.npm_package_version=Z.npm_package_version,Z.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=Z.FORCE_COLOR),C!==process.cwd()&&process.chdir(C);let n=!1;try{let{runCli:n}=await Promise.resolve().then(()=>(
|
|
897
|
+
\r*?{}[]~#!`.includes(H))return null;C+=H,N=!0}return F?null:(N&&S.push(C),S)}function gjsifyCommandArgv(n){let S=tokenizeSimpleCommand(n);return!S||S.length<2||S[0]!==`gjsify`?null:S.slice(1)}var OF=__esmMin(()=>{});function markDaemonCommand(){kF=!0}function isDaemonCommand(){return kF}var kF,AF=__esmMin(()=>{kF=!1});async function runTargetOnRuntime(n,S,C){if(!looksLikeFile(S))return ve.error(`gjsify run: --runtime ${n} needs a bundle FILE, but "${S}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${n===`gjs`?`gjs`:`node`} --outfile dist/app.${n===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let N=readPackageJson$1(js(process.cwd(),`package.json`)),F=checkRuntimeSupported(n,readDeclaredRuntimes(N),N?.name??S);if(!F.ok)return ve.error(`gjsify run: ${F.message}`),process.exit(1);let I=Os(S);n===`gjs`?await runGjsBundle(I,C,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(n,I,C,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(n){if(/\.gjs\.[mc]?js$/.test(n))return!0;try{let S=readFileSync(n,`utf-8`).slice(0,65536);return S.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(S)||/\bimports\.(?:gi|system)\b/.test(S)}catch{return!1}}function looksLikeFile(n){if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`/`)||n.includes(`/`)||n.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(n))return!0;try{return statSync(n).isFile()}catch{return!1}}async function runScriptInWorkspace(n,S,C){let N=findWorkspaceRoot(process.cwd())??process.cwd(),F;try{F=discoverWorkspaces(N)}catch(n){return ve.error(`gjsify run: could not read workspaces at ${N}: ${n.message}`),process.exit(1)}let I=F.find(S=>S.name===n||S.relativeLocation===n||Fs(S.location)===n);if(!I){let S=F.map(n=>n.relativeLocation).join(`, `)||`<none>`;return ve.error(`gjsify run: no workspace "${n}" under ${N} (available: ${S})`),process.exit(1)}await runScript(S,C,I.location)}async function runScript(n,S,C=process.cwd()){let N=js(C,`package.json`),F=readPackageJson$1(N);if(!F)return ve.error(`gjsify run: no package.json in ${C}`),process.exit(1);let I=F.scripts??{},H=I[n];if(typeof H!=`string`){let S=Object.keys(I).join(`, `)||`<none>`;return ve.error(`gjsify run: no script "${n}" in ${N} (available: ${S})`),process.exit(1)}let W=findWorkspaceRoot(C),q=[js(C,`node_modules`,`.bin`)];W&&W!==C&&q.push(js(W,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&q.unshift(process.env.GJSIFY_SHIM_DIR);let Y=nodeShimDir();Y&&q.unshift(Y);let X=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},Z={...process.env,...X,PATH:[...q,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:n,npm_package_name:F.name??``,npm_package_version:F.version??``},te=isGjs()?gjsifyInProcessArgv(H,S):null;if(te){process.env.PATH=Z.PATH,process.env.npm_lifecycle_event=Z.npm_lifecycle_event,process.env.npm_package_name=Z.npm_package_name,process.env.npm_package_version=Z.npm_package_version,Z.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=Z.FORCE_COLOR),C!==process.cwd()&&process.chdir(C);let n=!1;try{let{runCli:n}=await Promise.resolve().then(()=>(aH(),iH));await n(te)}catch(S){ve.error(S.message),n=!0}if(!n&&isDaemonCommand())return;let S=n?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(S)}let ne=S.length>0?`${H} ${S.map(shellEscape).join(` `)}`:H,re;try{re=await spawnToCompletion(ne,[],{completion:`exit`,cwd:C,env:Z,shell:!0})}catch(n){return ve.error(n.message),process.exit(1)}return re.code===0?process.exit(0):(ve.error(`script "${n}" exited with ${describeExit(re)}`),process.exit(1))}function shellEscape(n){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(n)?n:`'${n.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(n,S){let C=gjsifyCommandArgv(n);return C?[...C,...S]:null}var jF,MF=__esmMin(()=>{ye(),Vl(),Hs(),_P(),yP(),xP(),wP(),TP(),DF(),qM(),OF(),AF(),GM(),th(),Ah(),jF={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:n=>n.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:Oh,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,"unknown-options-as-args":!0}),handler:async n=>{let S=n.target,C=n.args??[],N=(n[`--`]??[]).filter(n=>typeof n==`string`),F=[...C,...N];if(n.nodeScript===!0){let isSet=n=>typeof n==`string`&&n.length>0,C=isSet(n.runtime)?`--runtime`:isSet(n.workspace)?`--workspace`:null;if(C)return ve.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(S,F,{completion:`exit`,exitOnSuccess:!0});return}let I=n.runtime;if(typeof I==`string`&&I.length>0){if(typeof n.workspace==`string`&&n.workspace.length>0)return ve.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(I))return ve.error(`gjsify run: unknown --runtime "${I}" (expected: ${Oh.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(I,S,F);return}if(typeof n.workspace==`string`&&n.workspace.length>0){await runScriptInWorkspace(n.workspace,S,F);return}let H=readPackageJson$1(js(process.cwd(),`package.json`));if(!(H?.scripts&&typeof H.scripts[S]==`string`)&&looksLikeFile(S)){let n=Os(S),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(n)?`gjs`:C;N===`gjs`?await runGjsBundle(n,F,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,n,F,{completion:`exit`,exitOnSuccess:!0});return}await runScript(S,F)}}}),NF,PF=__esmMin(()=>{ye(),Hs(),gN(),NF={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:n=>n.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 n=>{let S=process.cwd(),C=n.file?Os(n.file):null,N=detectNativePackages(S),F=buildNativeEnv(N),I=Object.entries(F).filter(([,n])=>n!==void 0);if(n.export){for(let[n,S]of I)ve.log(`export ${n}="${S}"`);return}if(N.length===0){ve.log(`No native gjsify packages detected in node_modules.`),ve.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ve.log(`Native packages detected:`);for(let n of N)ve.log(` ${n.name} → ${n.prebuildsDir}`);ve.log(``),ve.log(`To run your app directly with gjs, set:`);for(let[n,S]of I)ve.log(` export ${n}="${S}"`);C?ve.log(` gjs -m ${C}`):ve.log(` gjs -m <your-bundle.js>`),ve.log(``),ve.log(`Or use gjsify run to handle this automatically:`),C?ve.log(` gjsify run ${n.file}`):ve.log(` gjsify run <your-bundle.js>`)}}}),FF,IF=__esmMin(()=>{ye(),dN(),FF={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:n=>n.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async n=>{let S=runAllChecks(process.cwd()),C=detectPackageManager$1(),N=checkTypeSkew(process.cwd()),F=S.filter(n=>!n.found&&n.severity===`required`),I=S.filter(n=>!n.found&&n.severity===`optional`),H=[...F,...I];if(n.json)return ve.log(JSON.stringify({packageManager:C,deps:S,typeSkew:N},null,2)),process.exit(+(F.length>0));ve.log(`System dependency check
|
|
898
898
|
`);let W=S.filter(n=>n.severity===`required`),q=S.filter(n=>n.severity===`optional`);if(W.length>0){ve.log(`Required:`);for(let n of W){let S=n.found?`✓`:`✗`,C=n.version?` (${n.version})`:``;ve.log(` ${S} ${n.name}${C}`)}}if(q.length>0){ve.log(`
|
|
899
899
|
Optional:`);for(let n of q){let S=n.found?`✓`:`⚠`,C=n.version?` (${n.version})`:``,N=n.requiredBy&&n.requiredBy.length>0?` — needed by ${n.requiredBy.join(`, `)}`:``;ve.log(` ${S} ${n.name}${C}${N}`)}}if(N.length>0){ve.log(`
|
|
900
900
|
Type/runtime version skew:`);for(let n of N){let S=n.relation===`ahead`?`⚠`:`ℹ`;ve.log(` ${S} ${n.typePackage} describes ${n.declared}, installed ${n.pkgConfig} is ${n.installed}`)}N.some(n=>n.relation===`ahead`)&&ve.log(`
|
|
@@ -915,7 +915,7 @@ No install command available for your package manager. Install manually.`),proce
|
|
|
915
915
|
bunx @gjsify/cli@latest showcase <name>
|
|
916
916
|
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,sI={command:`showcase [name]`,description:`List or run curated gjsify showcase applications.`,builder:n=>n.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:Oh,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 n=>{if(!n.name||n.list){let S=discoverShowcases();if(n.json){ve.log(JSON.stringify(S,null,2));return}if(S.length===0){ve.log("No showcases found. The CLI ships a curated list in `showcases.json`; if it is missing the CLI install is incomplete.");return}let C=new Map;for(let n of S){let S=C.get(n.category)??[];S.push(n),C.set(n.category,S)}ve.log(`Available gjsify showcases:
|
|
917
917
|
`);for(let[n,S]of C){ve.log(` ${n.toUpperCase()}:`);let C=Math.max(...S.map(n=>n.name.length));for(let n of S){let S=` `.repeat(C-n.name.length+2),N=n.description?`${S}${n.description}`:``;ve.log(` ${n.name}${N}`)}ve.log(``)}ve.log(`Run a showcase: gjsify showcase <name>`);return}let S=findShowcase(n.name);if(!S)return ve.error(`Unknown showcase: "${n.name}"`),ve.error(`Run "gjsify showcase" to list available showcases.`),process.exit(1);let C=n.runtime??defaultExampleRuntime();if(!isExampleRuntime(C))return ve.error(`Unknown --runtime "${C}" (expected: ${Oh.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(C)){let n=runMinimalChecks().filter(n=>!n.found&&n.severity===`required`);if(n.length>0){ve.error(`Missing system dependencies:
|
|
918
|
-
`);for(let S of n)ve.error(` ✗ ${S.name}`);let S=buildInstallCommand(detectPackageManager$1(),n);return S&&ve.error(`\nInstall with:\n ${S}`),process.exit(1)}}let N=readCliVersion();if(C!==`gjs`){await runShowcaseOnRuntime(S,C,N);return}let F=N?`${S.packageName}@${N}`:S.packageName;ve.log(`Running showcase: ${S.name} ${runningAs(N)}(via gjsify dlx ${F})\n`);try{let{runCli:n}=await Promise.resolve().then(()=>(
|
|
918
|
+
`);for(let S of n)ve.error(` ✗ ${S.name}`);let S=buildInstallCommand(detectPackageManager$1(),n);return S&&ve.error(`\nInstall with:\n ${S}`),process.exit(1)}}let N=readCliVersion();if(C!==`gjs`){await runShowcaseOnRuntime(S,C,N);return}let F=N?`${S.packageName}@${N}`:S.packageName;ve.log(`Running showcase: ${S.name} ${runningAs(N)}(via gjsify dlx ${F})\n`);try{let{runCli:n}=await Promise.resolve().then(()=>(aH(),iH));await n([`dlx`,F])}catch(n){ve.error(n.message),process.exit(1)}}}});function resolveTemplatesRoot(){let n=Ps(fileURLToPath(import.meta.url)),S=[js(n,`..`,`dist-templates`),js(n,`dist-templates`)];try{let n=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);S.splice(1,0,js(Ps(n),`dist-templates`))}catch{}return S.find(n=>existsSync(n))}function discoverTemplates(){let n=resolveTemplatesRoot();if(!n)return[];let S=[];for(let C of readdirSync(n)){let N=js(n,C),F=js(N,`package.json`);if(!statSync(N).isDirectory()||!existsSync(F))continue;let I=lI[C]??``;try{let n=JSON.parse(readFileSync(F,`utf-8`));typeof n.description==`string`&&n.description.trim()&&(I=n.description)}catch{}S.push({name:C,description:I,path:N})}return S.sort((n,S)=>n.name.localeCompare(S.name)),S}function findTemplate(n){return discoverTemplates().find(S=>S.name===n)}var lI,uI=__esmMin(()=>{Vl(),gs(),Hs(),gn(),lI={"gtk-minimal":`Minimal GTK4 app — Gtk.Window + Gtk.Label (no Adwaita, no Blueprint).`,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 runScriptCommand(n){return pI[n]}function packageManagersForRuntime(n){return mI[n]}function hostRuntime(){let n=globalThis;return n.Bun===void 0?n.Deno===void 0?n.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(n,S){if(S)return n.find(n=>packageManagersForRuntime(n)?.includes(S));let C=hostRuntime();return n.includes(C)?C:n[0]}function startScriptFor(n){return n===`gjs`?`start`:`start:${n}`}var dI,fI,pI,mI,hI,gI=__esmMin(()=>{dI=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],fI={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},pI={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},mI={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},hI={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(n){let{flag:S,offered:C,manager:N,interactive:F}=n;if(S!==void 0)return C.length>0&&!C.includes(S)?{kind:`error`,message:`this template does not run on "${S}". Declared runtimes: ${C.join(`, `)}.`}:{kind:`value`,value:S};if(C.length===1)return{kind:`value`,value:C[0]};if(C.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let I=defaultRuntimeFor(C,N);return I===void 0?{kind:`error`,message:`no runtime this template declares installs with "${N}". Declared runtimes: ${C.join(`, `)}.`}:N===void 0?F?{kind:`prompt`,choices:C,initial:I}:{kind:`auto`,value:I,notice:`--runtime not given, using "${I}". Runs on: ${C.join(`, `)}.`}:{kind:`auto`,value:I,notice:`Setting up for ${I} — the runtime ${N} installs for.`}}function selectPackageManager(n){let{flag:S,runtime:C,install:N,interactive:F}=n,I=packageManagersForRuntime(C);return I===void 0||I.length===0?{kind:`error`,message:`no package manager known for runtime "${C}".`}:S===void 0?I.length===1?{kind:`auto`,value:I[0],notice:`Using ${I[0]} — the only package manager that installs for ${C}.`}:F?{kind:`prompt`,choices:I,initial:I[0]}:N?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${C}: ${I.join(`, `)}.`}:{kind:`auto`,value:I[0],notice:`--package-manager not given, using "${I[0]}" for ${C}.`}:I.includes(S)?{kind:`value`,value:S}:{kind:`error`,message:`"${S}" cannot install a project you intend to run on ${C}. Package managers for ${C}: ${I.join(`, `)}.`}}var _I=__esmMin(()=>{gI()});function applicationIdFor(n){let S=n.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(S)?`app-${S}`:S}`}function sanitizeProjectName(n){let S=n.trim();if(!S)throw Error(`Project name cannot be empty.`);let C=S.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!C)throw Error(`"${n}" is not a valid npm package name.`);return C}function isDirEmpty(n){return existsSync(n)?readdirSync(n).length===0:!0}async function createProject(n){let S=sanitizeProjectName(n.projectName),{template:C,force:N=!1,install:F=!1}=n,I=findTemplate(C);if(!I){let n=discoverTemplates().map(n=>n.name).join(`, `);throw Error(`Unknown template "${C}". Available templates: ${n||`(none — run "yarn build" first)`}`)}let H=supportedRuntimes(I),W=n.runtime??defaultRuntimeFor(H,n.packageManager)??hostRuntime(),q=packageManagersForRuntime(W);if(!q)throw Error(`Template "${I.name}" was asked for runtime "${W}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${H.join(`, `)||`(none)`}.`);let Y=n.packageManager??q[0];if(!q.includes(Y))throw Error(`"${Y}" cannot install a project you intend to run on ${W}. Package managers for ${W}: ${q.join(`, `)}.`);let X=Os(process.cwd(),S);if(existsSync(X)&&!isDirEmpty(X)&&!N)return ve.error(`Error: Directory "${S}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ve.log(`Creating new Gjsify project in ${X} (template: ${I.name})...`),mkdirSync(X,{recursive:!0}),cpSync(I.path,X,{recursive:!0}),substituteTemplateSentinels(X,S),F){let n=[...fI[Y]];ve.log(`Running ${Y} ${n[0]}...`);let S=spawnSync(Y,n,{cwd:X,stdio:`inherit`,shell:!0});S.error?ve.warn(`${Y} install could not start (${S.error.message}); re-run it manually.`):S.status!==0&&ve.warn(`${Y} install failed; re-run it manually in the project directory.`)}printNextSteps(S,I,F,Y,W)}function substituteTemplateSentinels(n,S){let C=[[vI,S],[yI,applicationIdFor(S)]],N=new Set([`node_modules`,`dist`,`lib`]),F=[n];for(;F.length>0;){let n=F.pop();for(let S of readdirSync(n,{withFileTypes:!0})){let I=js(n,S.name);if(S.isDirectory()){N.has(S.name)||F.push(I);continue}if(!S.isFile())continue;let H=S.name.lastIndexOf(`.`),W=H>=0?S.name.slice(H):``;if(!bI.has(W))continue;let q=readFileSync(I,`utf-8`),Y=q;for(let[n,S]of C)Y=Y.replaceAll(n,S);Y!==q&&writeFileSync(I,Y)}}}function printNextSteps(n,S,C,N,F){let I=runScriptCommand(N),H=templateScripts(S),W=startScriptFor(F);ve.log(``),ve.log(`Project created from template "${S.name}", set up for ${F}.`),ve.log(``),ve.log(`Next steps:`),ve.log(` cd ${n}`),C||ve.log(` ${N} install`),F===`gjs`&&H.dev?ve.log(` ${I} dev`):(ve.log(` ${I} build`),ve.log(` ${I} ${W}`)),ve.log(``);let q=supportedRuntimes(S).filter(n=>n!==F&&H[startScriptFor(n)]);if(q.length>0){ve.log(`Also runs on ${q.join(`, `)}:`);for(let n of q)ve.log(` ${I} ${startScriptFor(n)}`);ve.log(``)}}function templateManifest(n){try{return JSON.parse(readFileSync(js(n.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(n){let S=templateManifest(n).scripts;return S?Object.fromEntries(Object.entries(S).filter(n=>typeof n[1]==`string`)):{}}function supportedRuntimes(n){let S=templateManifest(n).gjsify?.example?.runtimes;return Array.isArray(S)?S.filter(n=>typeof n==`string`&&packageManagersForRuntime(n)!==void 0):[]}var vI,yI,bI,xI=__esmMin(()=>{ye(),Dh(),Vl(),Hs(),uI(),gI(),_I(),vI=`new-gjsify-app`,yI=`org.gjsify.example`,bI=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`])});function isCancelled(n){return n instanceof Error&&n.message===CI}function render(n,S,C){C||an.write(`\x1b[${n.length}A`);for(let C=0;C<n.length;C++){let N=n[C],F=C===S?`${SI.cyan}❯${SI.reset}`:` `,I=C===S?`${SI.bold}${SI.green}${N.label}${SI.reset}`:N.label,H=N.description?` ${SI.dim}${N.description}${SI.reset}`:``;an.write(`\x1b[2K\r ${F} ${I}${H}\n`)}}function promptChoice(n,S,C=0){return S.length===0?Promise.reject(Error(`Nothing to choose for "${n}".`)):new Promise((N,F)=>{let I=C>=0&&C<S.length?C:0;an.write(`${SI.bold}${n}${SI.reset} ${SI.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${SI.reset}\n`),render(S,I,!0),emitKeypressEvents(on),on.isTTY&&on.setRawMode(!0),on.resume();let cleanup=()=>{on.removeListener(`keypress`,onKeypress),on.isTTY&&on.setRawMode(!1),on.pause()},onKeypress=(n,C)=>{if(C){if(C.ctrl&&C.name===`c`){cleanup(),an.write(`
|
|
919
919
|
`),F(Error(CI));return}C.name===`up`||C.name===`k`?(I=(I-1+S.length)%S.length,render(S,I,!1)):C.name===`down`||C.name===`j`?(I=(I+1)%S.length,render(S,I,!1)):(C.name===`return`||C.name===`enter`)&&(cleanup(),N(S[I].value))}};on.on(`keypress`,onKeypress)})}function promptTemplate(n){return n.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,n.map(n=>({value:n,label:n.name,description:n.description})))}function promptRuntime(n,S){return promptChoice(`Select a runtime`,n.map(n=>({value:n,label:n,description:hI[n]??``})),n.indexOf(S))}function promptPackageManager(n,S){return promptChoice(`Select a package manager`,n.map(n=>({value:n,label:n,description:``})),n.indexOf(S))}async function settle(n,S){switch(n.kind){case`value`:return n.value;case`auto`:return ve.error(n.notice),n.value;case`prompt`:try{return await S(n.choices,n.initial)}catch(n){if(!isCancelled(n))throw n;ve.error(`Cancelled.`);return}case`error`:ve.error(`Error: ${n.message}`);return}}async function promptSetup(n){let{offered:S,install:C,interactive:N}=n,F=await settle(selectRuntime({flag:n.runtime,offered:S,manager:n.packageManager,interactive:N}),(n,S)=>promptRuntime(n,S));if(F===void 0)return;let I=await settle(selectPackageManager({flag:n.packageManager,runtime:F,install:C,interactive:N}),(n,S)=>promptPackageManager(n,S));if(I!==void 0)return{runtime:F,packageManager:I}}var SI,CI,wI=__esmMin(()=>{ye(),sn(),Ml(),gI(),_I(),SI={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},CI=`Cancelled by user`}),TI,EI=__esmMin(()=>{ye(),xI(),wI(),TI={command:`create [project-name]`,description:`Scaffold a new Gjsify project in a new directory.`,builder:n=>{let S=discoverTemplates(),C=S.map(n=>n.name),N=[...new Set(S.flatMap(n=>supportedRuntimes(n)))];return n.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:C.length>0?C: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:N.length>0?N: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:dI})},handler:async n=>{let S=!!process.stdin.isTTY,C=discoverTemplates(),N=n.template;if(!N){if(!S){let n=C.map(n=>n.name).join(`, `);return ve.error(`Error: --template is required in non-interactive mode. Available templates: ${n||`(none)`}`),process.exit(1)}let n=await promptTemplate(C).catch(n=>{if(!isCancelled(n))throw n;ve.error(`Cancelled.`)});if(n===void 0)return process.exit(1);N=n.name}let F=C.find(n=>n.name===N),I=await promptSetup({offered:F?supportedRuntimes(F):[],runtime:n.runtime,packageManager:n[`package-manager`],install:n.install,interactive:S});if(I===void 0)return process.exit(1);await createProject({projectName:n[`project-name`],template:N,runtime:I.runtime,force:n.force,install:n.install,packageManager:I.packageManager})}}});function defaultTargetFor(n){let S=Fs(n,Is(n));return Os(Ps(n),S)}var DI,OI,kI=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),DI=promisify(execFile),OI={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:n=>n.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 n=>{let S=Os(n.xml),C=n.target?Os(n.target):defaultTargetFor(S),N=[`--sourcedir=${n.sourcedir?Os(n.sourcedir):Ps(S)}`,`--target=${C}`,S];n.verbose&&ve.log(`[gjsify gresource] glib-compile-resources ${N.join(` `)}`),await mkdir$1(Ps(C),{recursive:!0});try{let{stdout:S,stderr:F}=await DI(`glib-compile-resources`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gresource] wrote ${C}`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gresource] glib-compile-resources failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function mergeCatalogues(n){let S=n.template,C=new Set;for(let{locale:S}of n.catalogues){if(C.has(S))throw Error(`mergeCatalogues: two catalogues both claim locale "${S}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${S}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);C.add(S)}for(let[C,N]of n.catalogues.entries()){let F=js(n.workDir,`${C}${n.extension}`),I=[n.mode,`--template=${S}`,`--locale=${N.locale}`,`--output-file=${F}`,N.po];n.onCall?.(I),execFileSync(`msgfmt`,I,{stdio:`pipe`}),S=F}return S}var AI=__esmMin(()=>{Dh(),Hs()});async function listLanguages(n){return(await readdir$1(n)).filter(n=>n.endsWith(`.po`)&&!n.startsWith(`.`)).map(n=>n.slice(0,-3)).sort()}function stripXmlComments(n){return n.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(n){await mkdir$1(n,{recursive:!0})}async function fileExists(n){try{return await stat$1(n),!0}catch{return!1}}async function compileMerged(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}let C=js(n.outDir,n.filename);await ensureDir(n.outDir);let N=await mkdtemp$1(js(tmpdir(),`gjsify-gettext-`));try{let F=await readFile$1(mergeCatalogues({mode:`--${n.format}`,template:n.template,extension:`-${Fs(n.template).replace(/\.in$/,``)}`,catalogues:S.map(S=>({locale:S,po:js(n.poDir,`${S}.po`)})),workDir:N,onCall:n.verbose?n=>ve.log(`[gjsify gettext] msgfmt ${n.join(` `)}`):void 0}),`utf-8`);await writeFile$1(C,n.removeXmlComments&&n.format===`xml`?stripXmlComments(F):F)}finally{await rm$1(N,{recursive:!0,force:!0})}n.verbose&&ve.log(`[gjsify gettext] merged ${S.length} language(s) into ${C}`)}async function compileCatalogues(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}for(let C of S){let S=js(n.outDir,C,`LC_MESSAGES`);await ensureDir(S);let N=[`--output-file=${js(S,n.filename)}`,js(n.poDir,`${C}.po`)];n.verbose&&ve.log(`[gjsify gettext] msgfmt ${N.join(` `)}`),await jI(`msgfmt`,N)}n.verbose&&ve.log(`[gjsify gettext] compiled ${S.length} language(s) into ${n.outDir}`)}function defaultFilename(n,S,C){switch(S){case`mo`:return`${n}.mo`;case`desktop`:return`${n}.desktop`;case`xml`:return C?Fs(C.replace(/\.in$/,``)):`${n}.xml`}}var jI,MI,NI=__esmMin(()=>{ye(),Dh(),Cl(),Dm(),Hs(),Ac(),AI(),jI=promisify(execFile),MI={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:n=>n.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 n=>{let S=Os(n.poDir),C=Os(n.outDir),N=n.domain,F=n.format??`mo`,I=n.template??n.metainfo,H=I?Os(I):void 0,W=n.filename??defaultFilename(N,F,H),q=!!n.verbose,Y=!!n[`remove-xml-comments`];if(!await fileExists(S)){ve.error(`[gjsify gettext] PO directory does not exist: ${S}`),process.exitCode=1;return}if(F!==`mo`&&H===void 0){ve.error(`[gjsify gettext] --format=${F} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(F===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{F===`mo`?await compileCatalogues({poDir:S,outDir:C,filename:W,verbose:q}):await compileMerged({poDir:S,outDir:C,format:F,template:H,filename:W,removeXmlComments:Y,verbose:q})}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gettext] msgfmt failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}}),PI,FI,II=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),PI=promisify(execFile),FI={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:n=>n.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 n=>{let S=Os(n.schemadir),C=n.targetdir?Os(n.targetdir):S,N=[];n.strict&&N.push(`--strict`),N.push(`--targetdir=${C}`),N.push(S),n.verbose&&ve.log(`[gjsify gsettings] glib-compile-schemas ${N.join(` `)}`),await mkdir$1(C,{recursive:!0});try{let{stdout:S,stderr:F}=await PI(`glib-compile-schemas`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gsettings] wrote ${C}/gschemas.compiled`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gsettings] glib-compile-schemas failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function readPackageJson(n){let S=Os(n,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${S}`)}try{return JSON.parse(C)}catch(n){throw Error(`gjsify flatpak: package.json at ${S} is not valid JSON: ${n.message}`)}}function looksLikeAppId(n){return typeof n==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(n)}function defaultCiContainer(n,S){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${n}-${S}`}`}var LI=__esmMin(()=>{Vl(),Hs()});function resolveRuntime(n,S){let C=S.runtime??n?.runtime??`gnome`;if(C!==`gnome`&&C!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${C}" (expected "gnome" or "freedesktop")`);let N=S.runtimeVersion??n?.runtimeVersion??(C===`gnome`?`50`:`24.08`);return C===`gnome`?{runtime:C,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:N}:{runtime:C,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:N}}function deriveAppendPath(n){let S=[];for(let C of n){let n=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(C);n&&S.push(`/usr/lib/sdk/${n[1]}/bin`)}return S.push(`/app/bin`),S}var RI,zI,BI=__esmMin(()=>{RI=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],zI=[]});function pickFlatpakBuildKeys(n,S){let C=n??{},N={},F=[];for(let n of HI){let I=C[n];if(I!==void 0){N[n]=I;continue}let H=S[n];H!==void 0&&F.push(n),N[n]=H}return{values:N,fromLegacy:F}}function resolveShipFlatpakSettings(n){let S=n.ship.flatpak??{},{values:C,fromLegacy:N}=pickFlatpakBuildKeys(S,n.flatpak),F=resolveRuntime(C,{}),I=C.sdkExtensions??[],{appendPath:H,finishArgs:W,cleanup:q}=C;return{settings:{runtime:F.runtimeId,runtimeVersion:F.runtimeVersion,sdk:F.sdk,branch:S.branch??`stable`,sdkExtensions:[...I],appendPath:H??(I.length>0?deriveAppendPath(I):[]),finishArgs:W??(n.kind===`cli`?zI:RI),cleanup:q??[]},warnings:N.length===0?[]:[deprecationWarning(N)]}}function deprecationWarning(n){let S=n.map(n=>`gjsify.flatpak.${n}`).join(`, `),C=n.map(n=>`gjsify.ship.flatpak.${n}`).join(`, `);return`DEPRECATION: ${S} ${n.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${VI}. Move ${n.length>1?`them`:`it`} to ${C} — 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 VI,HI,WI=__esmMin(()=>{BI(),VI=`1.0.0`,HI=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return GI}function validateAppMetadata(n){let S=n.metadata,C=n.configKey,N=[];return(!S.developer?.id||!S.developer?.name)&&N.push({field:`${C}.developer`,hint:`Set \`${C}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),S.summary||N.push({field:`${C}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),S.description||N.push({field:`${C}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),S.license?.project||N.push({field:`${C}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),S.homepageUrl||N.push({field:`${C}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),N}function renderMetainfoApp$1(n){return renderMetainfo(n,`desktop-application`)}function renderMetainfoCli$1(n){return renderMetainfo(n,`console-application`)}function renderDesktopEntry(n){let S=n.metadata,C=(S.categories??[`Utility`]).join(`;`)+`;`,N=S.keywords?.length?`Keywords=${S.keywords.join(`;`)};\n`:``,F=S.provides?.mimetypes??[],I=F.length?`MimeType=${F.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:n.name,SUMMARY:S.summary??n.name,COMMAND:`${n.command}${execFieldCode(F)}`,APP_ID:n.appId,CATEGORIES_LINE:C,KEYWORDS_LINE:N,MIMETYPES_LINE:I})}function execFieldCode(n){return n.some(n=>n.startsWith(`x-scheme-handler/`))?` %u`:n.length>0?` %f`:``}function renderMetainfo(n,S){let C=n.metadata,N=n.copyrightYear??new Date().getFullYear(),F=C.developer?.name??``,I=[];I.push(`<?xml version="1.0" encoding="UTF-8"?>`),I.push(`<!-- Copyright ${N} ${escapeXml(F)} -->`),I.push(`<component type="${S}">`),I.push(` <id>${escapeXml(n.appId)}</id>`),I.push(` <metadata_license>${escapeXml(C.license?.metadata??`CC0-1.0`)}</metadata_license>`),I.push(` <project_license>${escapeXml(C.license?.project??``)}</project_license>`),I.push(` <name>${escapeXml(n.name)}</name>`),pushTranslatorHint(I,C.summaryTranslatorHint,` `),I.push(` <summary>${escapeXml(C.summary??n.name)}</summary>`),C.iconRemote&&I.push(` <icon type="remote">${escapeXml(C.iconRemote)}</icon>`),I.push(` <description>`);for(let n of renderDescriptionBlocks(C.description??``,` `))I.push(n);if(I.push(` </description>`),C.developer?.id&&C.developer?.name){I.push(` <developer id="${escapeXml(C.developer.id)}">`);let n=C.developer.nameTranslatable===!0?``:` translate="no"`;I.push(` <name${n}>${escapeXml(C.developer.name)}</name>`),C.developer.email&&I.push(` <email>${escapeXml(C.developer.email)}</email>`),I.push(` </developer>`)}S===`desktop-application`&&I.push(` <launchable type="desktop-id">${escapeXml(n.appId)}.desktop</launchable>`),C.screenshots?.length&&(I.push(` <screenshots>`),C.screenshots.forEach((n,S)=>{let C=n.type??(S===0?`default`:void 0),N=C?` type="${escapeXml(C)}"`:``,F=n.environment?` environment="${escapeXml(n.environment)}"`:``;I.push(` <screenshot${N}${F}>`),I.push(` <image>${escapeXml(n.url)}</image>`),n.caption&&(pushTranslatorHint(I,n.captionTranslatorHint,` `),I.push(` <caption>${escapeXml(n.caption)}</caption>`)),I.push(` </screenshot>`)}),I.push(` </screenshots>`)),C.homepageUrl&&I.push(` <url type="homepage">${escapeXml(C.homepageUrl)}</url>`),C.bugtrackerUrl&&I.push(` <url type="bugtracker">${escapeXml(C.bugtrackerUrl)}</url>`),C.vcsBrowserUrl&&I.push(` <url type="vcs-browser">${escapeXml(C.vcsBrowserUrl)}</url>`),C.donationUrl&&I.push(` <url type="donation">${escapeXml(C.donationUrl)}</url>`),C.translateUrl&&I.push(` <url type="translate">${escapeXml(C.translateUrl)}</url>`);let H=normaliseContentRating(C.contentRating);if(H.attributes&&Object.keys(H.attributes).length>0){I.push(` <content_rating type="${escapeXml(H.type)}">`);for(let[n,S]of Object.entries(H.attributes))I.push(` <content_attribute id="${escapeXml(n)}">${escapeXml(S)}</content_attribute>`);I.push(` </content_rating>`)}else I.push(` <content_rating type="${escapeXml(H.type)}" />`);if(C.releases?.length){I.push(` <releases>`);for(let n of C.releases)if(n.description===void 0)I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}" />`);else{I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}">`),I.push(` <description>`);for(let S of renderDescriptionBlocks(n.description,` `))I.push(S);I.push(` </description>`),I.push(` </release>`)}I.push(` </releases>`)}if(C.categories?.length){I.push(` <categories>`);for(let n of C.categories)I.push(` <category>${escapeXml(n)}</category>`);I.push(` </categories>`)}if(C.keywords?.length){I.push(` <keywords>`);for(let n of C.keywords)I.push(` <keyword>${escapeXml(n)}</keyword>`);I.push(` </keywords>`)}if(S===`desktop-application`&&C.branding&&(I.push(` <branding>`),I.push(` <color type="primary" scheme_preference="light">${escapeXml(C.branding.accentLight)}</color>`),I.push(` <color type="primary" scheme_preference="dark">${escapeXml(C.branding.accentDark)}</color>`),I.push(` </branding>`)),C.kudos?.length){I.push(` <kudos>`);for(let n of C.kudos)I.push(` <kudo>${escapeXml(n)}</kudo>`);I.push(` </kudos>`)}let W=C.provides?.binaries??[n.command],q=C.provides?.mimetypes??[],Y=C.provides?.dbus??[];if(W.length||q.length||Y.length){I.push(` <provides>`);for(let n of W)I.push(` <binary>${escapeXml(n)}</binary>`);for(let n of q)I.push(` <mediatype>${escapeXml(n)}</mediatype>`);for(let n of Y)I.push(` <dbus type="${escapeXml(n.type)}">${escapeXml(n.id)}</dbus>`);I.push(` </provides>`)}if(C.supports?.controls?.length||C.supports?.internet){I.push(` <supports>`);for(let n of C.supports.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.supports.internet&&I.push(` <internet>${escapeXml(C.supports.internet)}</internet>`),I.push(` </supports>`)}if(C.requires?.displayLengthMin||C.requires?.controls?.length||C.requires?.internet){I.push(` <requires>`),C.requires.displayLengthMin&&I.push(` <display_length compare="ge">${C.requires.displayLengthMin}</display_length>`);for(let n of C.requires.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.requires.internet&&I.push(` <internet>${escapeXml(C.requires.internet)}</internet>`),I.push(` </requires>`)}if(C.recommends?.displayLengthMin||C.recommends?.controls?.length){I.push(` <recommends>`),C.recommends.displayLengthMin&&I.push(` <display_length compare="ge">${C.recommends.displayLengthMin}</display_length>`);for(let n of C.recommends.controls??[])I.push(` <control>${escapeXml(n)}</control>`);I.push(` </recommends>`)}return I.push(`</component>`),I.join(`
|
|
920
920
|
`)+`
|
|
921
921
|
`}function renderDescriptionBlocks(n,S){let C=typeof n==`string`?stringToBlocks(n):n,N=[];for(let n of C)if(`p`in n)pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<p>${escapeXml(n.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<ul>`);for(let C of n.ul)typeof C==`string`?N.push(`${S} <li>${escapeXml(C)}</li>`):(pushTranslatorHint(N,C.translatorHint,`${S} `),N.push(`${S} <li>${escapeXml(C.item)}</li>`));N.push(`${S}</ul>`)}return N}function stringToBlocks(n){return n.trim().split(/\n\n+/).map(n=>({p:n.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(n,S,C){S&&n.push(`${C}<!-- TRANSLATORS: ${S} -->`)}function normaliseContentRating(n){return n===void 0?{type:`oars-1.1`}:typeof n==`string`?{type:n}:{type:n.type??`oars-1.1`,attributes:n.attributes}}function substitute(n,S){let C=n;for(let[n,N]of Object.entries(S))C=C.split(`{{${n}}}`).join(N);return C}function escapeXml(n){return n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var GI,KI=__esmMin(()=>{GI=`[Desktop Entry]
|
|
@@ -1071,7 +1071,7 @@ $`,64,`ascii`),ae.writeUInt32LE(RL,60),ae.write(`PE\0\0`,RL,`ascii`),ae.writeUIn
|
|
|
1071
1071
|
`)}function renderPkgInfo(){return`${nR}${rR}`}function renderEntitlements(n){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.map(n=>`\t<key>${xmlText(n)}</key>\n\t<true/>`).join(`
|
|
1072
1072
|
`),`</dict>`,`</plist>`,``].join(`
|
|
1073
1073
|
`)}var eR,tR,nR,rR,iR=__esmMin(()=>{eR=`Contents/Info.plist`,tR=`Contents/PkgInfo`,nR=`APPL`,rR=`????`});function darwinFontsPath(n,S){let C=`${PL.fonts}/${n.appId}`,N=S.find(n=>n.path.startsWith(`${C}/`));if(N===void 0)return;let F=oR.darwin.dirs(n);return xs.relative(F.other,xs.dirname(place(oR.darwin,n,N.path)))}function appBundleDir(n){if(aR.test(n.name))throw Error(`gjsify ship: the macOS layout would put this app in "${n.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`${n.name}.app`}function launcherPath(n,S){return xs.join(n.dirs(S).launcher,`${S.binaryName}${n.launcherExt}`)}function windowsGuiLauncherPath(n){let S=oR.windows;if(S.launcherExt.length!==4)throw Error(`gjsify ship: the windows launcher extension is "${S.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 xs.join(S.dirs(n).launcher,`${n.binaryName}.exe`)}function windowsLaunchLogLeaf(n){return`${n.binaryName}.launch.log`}function layoutForOs(n){let S=cR.get(n);if(S===void 0)throw Error(`"${n}" is not a \`process.platform\` token this gjsify has a layout for. Known: ${sR.map(n=>oR[n].os).join(`, `)} — the \`\${process.platform}-\${process.arch}\` spelling, so \`win32\` and never \`windows\`.`);return S}function resolveLayout(n){let S=n.trim().toLowerCase();if(Object.hasOwn(oR,S))return oR[S];let C=cR.get(S);if(C!==void 0)return C;throw Error(`gjsify ship: "${n}" is not an operating system this command has a layout for. Known: ${sR.join(`, `)} (\`win32\` is accepted for \`windows\`, because that is the spelling \`--expect-target <os>-<arch>\` uses).`)}function hostLayout(n=process.platform){let S=cR.get(n);if(S===void 0)throw Error(`gjsify ship: this host is ${n}, which has no layout. Name the one you want — \`gjsify ship <${sR.join(`|`)}> --stage\` — assembly is not host-bound (ADR 0024 § A1).`);return S}function assertLayoutSupportsArch(n,S){let C=n.arches;if(!(C===null||C.only.includes(S)))throw Error(`gjsify ship: the ${n.name} layout is not assemblable for \`--arch ${S}\` — ${C.only.length===1?`the only architecture it has`:`the architectures it has`} ${C.only.length===1?`is`:`are`} ${C.only.join(`, `)}.\n ${C.why}.\n \`--arch\` names the architecture the PAYLOAD was built for and cross-compiles nothing, so there is no
|
|
1074
|
-
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(n,S,C){let N=n.dirs(S);if(C===`bin/${S.binaryName}`)return launcherPath(n,S);let F=`lib/${S.binaryName}/`,I=`${F}gi/`;return C.startsWith(I)?xs.join(N.native,C.slice(I.length)):C.startsWith(F)?xs.join(N.bundle,C.slice(F.length)):C.startsWith(`bin/`)?xs.join(N.launcher,C.slice(4)):C.startsWith(`share/`)?xs.join(N.data,C.slice(6)):xs.join(N.other,C)}function placeStage(n,S,C,N=[]){let F=new Map,I=[],claim=(S,C,N)=>{let H=F.get(S);if(H!==void 0)throw Error(`gjsify ship: in the ${n.name} layout both ${H} and ${C} install as ${S}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);F.set(S,C),I.push({...N,path:S})};for(let N of C)claim(place(n,S,N.path),N.path,N);for(let N of n.metadata(S,C))claim(N.path,`the ${n.name} layout's own metadata`,N);for(let S of N)claim(S.path,`the runtime staged into the ${n.name} artifact`,S);return I.sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var aR,oR,sR,cR,lR=__esmMin(()=>{Hs(),$L(),iR(),FL(),aR=/[/:\\]/,oR={linux:{name:`linux`,os:`linux`,shippedRuntime:`gjs`,launcherExt:``,root:()=>``,dirs:n=>({launcher:`bin`,bundle:`lib/${n.binaryName}`,native:`lib/${n.binaryName}/gi`,data:`share`,other:``}),metadata:()=>[],arches:null},darwin:{name:`darwin`,os:`darwin`,shippedRuntime:`node`,runtimeGap:'the staged launcher execs an interpreter off `PATH`, which a downloaded `.app` cannot assume — macOS ships no Node, and there is no RELOCATABLE GJS (`build-gtk-runtime-darwin.mjs`: "GJS ships no relocation"), so ADR 0024 § 4 derives Node here. A self-contained bundle needs `@gjsify/node-runtime-darwin-<arch>` and a `--app node` payload (#1354 M0), or `@gjsify/gjs-runtime-darwin-<arch>` (ADR 0024 stage 7).',fontGap:"the faces are staged in `share/fonts/<appId>` and `Info.plist` carries `ATSApplicationFontsPath` at it, which is macOS's own per-app activation — NOT the XDG_DATA_DIRS path, because Pango on macOS is CoreText-backed and GTK is not built against fontconfig there. That the activation reaches Pango's CoreText font map is UNVERIFIED: no leg in this repository runs a `.app`. Confirm with `PangoCairo.FontMap.get_default().list_families()` in the shipped bundle, and `PANGOCAIRO_BACKEND=bogus` to print which backend it was built with.",launcherExt:``,root:appBundleDir,dirs:n=>{let S=appBundleDir(n);return{launcher:`${S}/Contents/MacOS`,bundle:`${S}/Contents/Resources/lib`,native:`${S}/Contents/Frameworks`,data:`${S}/Contents/Resources/share`,other:`${S}/Contents/Resources`}},metadata:(n,S)=>[{path:`${appBundleDir(n)}/${eR}`,mode:420,source:{kind:`text`,text:renderInfoPlist(n,darwinFontsPath(n,S))}},{path:`${appBundleDir(n)}/${tR}`,mode:420,source:{kind:`text`,text:renderPkgInfo()}}],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 uses pangowin32, whose font map is populated from DirectWrite and never from fontconfig or from GDI. MEASURED on 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: `
|
|
1074
|
+
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(n,S,C){let N=n.dirs(S);if(C===`bin/${S.binaryName}`)return launcherPath(n,S);let F=`lib/${S.binaryName}/`,I=`${F}gi/`;return C.startsWith(I)?xs.join(N.native,C.slice(I.length)):C.startsWith(F)?xs.join(N.bundle,C.slice(F.length)):C.startsWith(`bin/`)?xs.join(N.launcher,C.slice(4)):C.startsWith(`share/`)?xs.join(N.data,C.slice(6)):xs.join(N.other,C)}function placeStage(n,S,C,N=[]){let F=new Map,I=[],claim=(S,C,N)=>{let H=F.get(S);if(H!==void 0)throw Error(`gjsify ship: in the ${n.name} layout both ${H} and ${C} install as ${S}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);F.set(S,C),I.push({...N,path:S})};for(let N of C)claim(place(n,S,N.path),N.path,N);for(let N of n.metadata(S,C))claim(N.path,`the ${n.name} layout's own metadata`,N);for(let S of N)claim(S.path,`the runtime staged into the ${n.name} artifact`,S);return I.sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var aR,oR,sR,cR,lR=__esmMin(()=>{Hs(),$L(),iR(),FL(),aR=/[/:\\]/,oR={linux:{name:`linux`,os:`linux`,shippedRuntime:`gjs`,launcherExt:``,root:()=>``,dirs:n=>({launcher:`bin`,bundle:`lib/${n.binaryName}`,native:`lib/${n.binaryName}/gi`,data:`share`,other:``}),metadata:()=>[],arches:null},darwin:{name:`darwin`,os:`darwin`,shippedRuntime:`node`,runtimeGap:'the staged launcher execs an interpreter off `PATH`, which a downloaded `.app` cannot assume — macOS ships no Node, and there is no RELOCATABLE GJS (`build-gtk-runtime-darwin.mjs`: "GJS ships no relocation"), so ADR 0024 § 4 derives Node here. A self-contained bundle needs `@gjsify/node-runtime-darwin-<arch>` and a `--app node` payload (#1354 M0), or `@gjsify/gjs-runtime-darwin-<arch>` (ADR 0024 stage 7).',fontGap:"the faces are staged in `share/fonts/<appId>` and `Info.plist` carries `ATSApplicationFontsPath` at it, which is macOS's own per-app activation — NOT the XDG_DATA_DIRS path, because Pango on macOS is CoreText-backed and GTK is not built against fontconfig there. That the activation reaches Pango's CoreText font map is UNVERIFIED: no leg in this repository runs a `.app`. Confirm with `PangoCairo.FontMap.get_default().list_families()` in the shipped bundle, and `PANGOCAIRO_BACKEND=bogus` to print which backend it was built with. An app that calls `initFonts()` from `@gjsify/gtk-host/fonts` for the Windows row needs no branch around it: the CoreText map answers G_IO_ERROR_NOT_SUPPORTED and that call deliberately does nothing here.",launcherExt:``,root:appBundleDir,dirs:n=>{let S=appBundleDir(n);return{launcher:`${S}/Contents/MacOS`,bundle:`${S}/Contents/Resources/lib`,native:`${S}/Contents/Frameworks`,data:`${S}/Contents/Resources/share`,other:`${S}/Contents/Resources`}},metadata:(n,S)=>[{path:`${appBundleDir(n)}/${eR}`,mode:420,source:{kind:`text`,text:renderInfoPlist(n,darwinFontsPath(n,S))}},{path:`${appBundleDir(n)}/${tR}`,mode:420,source:{kind:`text`,text:renderPkgInfo()}}],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 uses pangowin32, whose font map is populated from DirectWrite and never from fontconfig or from GDI. MEASURED on 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:``}),metadata:n=>n.arch===`x64`?[{path:windowsGuiLauncherPath(n),mode:493,source:{kind:`bytes`,data:buildGuiLauncher({logLeaf:windowsLaunchLogLeaf(n)})}}]:[],arches:{only:[`x64`],why:'gvsbuild publishes no arm64 GTK (it hardcodes `self.platform = "x64"`), so there is nothing to build `@gjsify/gtk-runtime-win32-arm64` out of and no GTK for a Windows/ARM artifact to load — the blocker is upstream and is tracked in gjsify/gjsify#1117'}}},sR=Object.keys(oR),cR=new Map(sR.map(n=>[oR[n].os,oR[n]]))});async function compileSchemasForStage(n){if(n.schemaFiles.length===0)return[];rmSync(n.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n.workDir,{recursive:!0});for(let S of n.schemaFiles)copyFileSync(S,js(n.workDir,Fs(S)));try{await uR(dR,[`--strict`,`--targetdir=${n.workDir}`,n.workDir])}catch(n){let S=n;throw S.code===`ENOENT`?Error(`gjsify ship: this layout has no install step, so \`${dR}\` has to run HERE to turn the payload's schemas into \`${pR}\` — and it is not on PATH. Install it (${fR}). 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: \`${dR} --strict\` refused this project's schemas.\n${(S.stderr??``).trimEnd()}\n \`--strict\` is deliberate: without it a malformed schema is SKIPPED at exit 0 and a cache
|
|
1075
1075
|
is written without it, so the app still aborts on the schema that was dropped. Fix the
|
|
1076
1076
|
file it names, or drop it from \`gjsify.ship.schemas\`.`)}return[{path:pR,mode:420,source:{kind:`file`,path:js(n.workDir,`gschemas.compiled`)}}]}var uR,dR,fR,pR,mR=__esmMin(()=>{Dh(),Hs(),Vl(),Ac(),FL(),uR=promisify(execFile),dR=`glib-compile-schemas`,fR="Fedora: `sudo dnf install glib2`, Debian/Ubuntu: `sudo apt install libglib2.0-bin`",pR=`${PL.schemas}/gschemas.compiled`});function buildTimestamp(n,S=process.env){let C=S.SOURCE_DATE_EPOCH;if(C!==void 0){let n=Number(C);if(!Number.isInteger(n)||n<0)throw Error(`gjsify ship: SOURCE_DATE_EPOCH must be a non-negative integer, got "${C}".`);return n}return Math.floor(statSync(n).mtimeMs/1e3)}function readPayloadFacts(n){let S=n.map(n=>n.path);return{hasDesktopEntry:S.some(n=>isUnder(n,PL.applications)&&n.endsWith(`.desktop`)),hasIcons:S.some(n=>isUnder(n,PL.icons)),hasSchemas:S.some(n=>isUnder(n,PL.schemas)&&n.endsWith(`.gschema.xml`)),hasMimeTypes:S.some(n=>isUnder(n,PL.mime)&&n.endsWith(`.xml`)),bundledTypelibs:S.filter(n=>n.endsWith(`.typelib`))}}function readLauncherInterpreters(n,S,C){let N=n.find(n=>n.path===launcherPath(S,C));if(N===void 0)return[];let F=new TextDecoder().decode(N.data),I=S.name===`windows`?`cmd`:`sh`,H=[];for(let n of I===`cmd`?batchCommands(F):shellExecLines(F)){let S=interpreterOf(n,I);S!==null&&H.push(S)}return[...new Set(H)]}function shellExecLines(n){return[...`\n${n}`.matchAll(/\n[ \t]*exec\s+([^\n]*)/g)].map(n=>n[1].trim())}function cmdTokens(n){let S=[],C=0;for(;C<n.length;){if(/\s/.test(n[C])){C+=1;continue}let N=C,F=!1;for(;C<n.length&&(F||!/\s/.test(n[C]));)n[C]===`"`&&(F=!F),C+=1;S.push({text:n.slice(N,C),end:C})}return S}function splitBatchBlock(n){let S=0,C=!1;for(let N=0;N<n.length;N++){let F=n[N];if(F===`"`)C=!C;else if(!C&&F===`(`)S+=1;else if(!C&&F===`)`&&(--S,S===0))return[n.slice(1,N).trim(),n.slice(N+1).trim()]}return null}function batchPrefix(n){if(n.startsWith(`(`)){let S=splitBatchBlock(n);return S===null?null:[S[0],S[1]]}let S=cmdTokens(n),word=n=>(S[n]?.text??``).toLowerCase(),after=C=>[n.slice(S[C]?.end??n.length).trim()];if(word(0)===`else`)return after(0);if(word(0)===`for`){let n=S.findIndex(n=>n.text.toLowerCase()===`do`);return n===-1?null:after(n)}if(word(0)!==`if`)return;let C=1;for(;word(C)===`not`||word(C)===`/i`;)C+=1;return gR.has(word(C))?after(C+1):word(C).includes(`==`)?after(C):_R.has(word(C+1))?after(C+2):null}function batchCommands(n){let S=[],C=n.split(/\r?\n/).map(n=>n.trim().replace(/^@+/,``).trim());for(let n=0;n<vR&&C.length>0;n++){let n=C.shift();if(n===``||n===`)`||n.startsWith(`::`))continue;let N=(cmdTokens(n)[0]?.text??``).toLowerCase();if(hR.has(N))continue;let F=batchPrefix(n);F===void 0?S.push(n):F!==null&&C.unshift(...F)}return S}function interpreterOf(n,S){if(S===`cmd`)return cmdProgramOf(n);let C=n.split(/\s+/).filter(n=>n.length>0);for(let n=0;n<2&&C.length>0;n++){let n=basenameOf(C[0]);if(n!==`env`)return n===``?null:n;C=C.slice(1).filter(n=>!n.startsWith(`-`)&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(n))}return null}function cmdProgramOf(n){let S=/^"([^"]*)"/.exec(n),C=((S===null?n.split(/\s+/)[0]??``:S[1]).replace(/^%[^%\s]*%/,``).split(/[/\\]/).pop()??``).replace(/\.exe$/i,``);return C===``?null:C}function basenameOf(n){let S=unquote(n).split(/[/\\]/);return S[S.length-1]??``}function unquote(n){let S=n[0];return(S===`"`||S===`'`)&&n.length>1&&n[n.length-1]===S?n.slice(1,-1):n}function assertLauncherMatchesInterpreter(n,S,C,N){let F=readLauncherInterpreters(n,S,C);if(F.length===0||F.includes(N))return;let I=N===`gjs`?`node`:`gjs`;if(F.includes(I))throw Error(`gjsify ship: the launcher ${launcherPath(S,C)} execs \`${I}\`, but this package would declare a dependency on \`${N}\`.\n An installed package that depends on one interpreter and runs another installs cleanly and fails
|
|
1077
1077
|
at first launch, on the user's machine.
|
|
@@ -1116,19 +1116,20 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
|
|
|
1116
1116
|
`+(n?C:S)}if(H)return`#!/bin/sh\nexec node "${H}" "$@"\n`;if(W)return`#!/bin/sh\n${q}exec gjs -m "${W}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(n,S,C,N=[]){let F=S?js(n,S):null,I=C?js(n,C):null;if(F)return buildLauncherShims({interpreter:`node`,target:F});if(I){let n=N.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:I,prependEnv:N.length===0?{}:{GI_TYPELIB_PATH:n,PATH:n}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(n,S,C){let N=new Map,F=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n,get=n=>{let S=N.get(n);return S||(S={},N.set(n,S)),S};if(typeof C==`string`)get(F).nodeTarget=C;else if(C&&typeof C==`object`)for(let[n,S]of Object.entries(C))typeof S==`string`&&S.length>0&&(get(n).nodeTarget=S);if(typeof S==`string`)get(F).gjsTarget=S;else if(S&&typeof S==`object`)for(let[n,C]of Object.entries(S))typeof C==`string`&&C.length>0&&(get(n).gjsTarget=C);return N}async function projectInstallViaNpm(n){let S=[`install`];n[`save-dev`]&&S.push(`--save-dev`),n[`save-peer`]&&S.push(`--save-peer`),n[`save-optional`]&&S.push(`--save-optional`),n.verbose&&S.push(`--loglevel`,`verbose`),n.packages&&n.packages.length>0&&S.push(...n.packages),await spawnNpm(S)}async function spawnNpm(n){return spawnToCompletion(`npm`,n,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:n})=>{if(n!==0)throw Error(`npm install exited with code ${n}`)}).catch(n=>{let S=n.code;ve.error(S===void 0?n.message:`npm install failed: ${n.message}`),process.exit(1)})}async function installGlobalAndLink(n,S){let C=defaultGlobalLayout();mkdirSync(C.prefix,{recursive:!0}),ve.log(`gjsify install --global → ${C.prefix}`),ve.log(` bins → ${C.binDir}`);let N=await acquireInstallLock(C.prefix,{});try{let N=await installPackages({prefix:C.prefix,specs:n,verbose:S.verbose}),F=n.map(specToPackageName);if(F.includes(`@gjsify/cli`)){let n=N.installed.find(n=>n.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(C.prefix,n,{verbose:S.verbose})}S.prune!==!1&&pruneAfterInstall(C.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(F,C),C.binDir)}finally{N.release()}}function pruneProjectPrefix(n){n.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:n.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(n,S){if(n.length===0)ve.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ve.log(`\nLinked ${n.length} bin(s):`);for(let S of n)ve.log(` • ${S.link} → ${S.target}`)}n.length>0&&!binDirOnPath(S)&&ve.warn(`\nNote: ${S} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${S}:$PATH"`)}async function ensureProjectGjsEngine(n,S,C={}){let N=C.cwd??process.cwd(),F=C.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(js(N,`node_modules`,`@gjsify`,`cli`,`package.json`))||!S||F(N))return;if(n.immutable){ve.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${xF} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
|
|
1117
1117
|
gjsify install ${xF}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let I=readCliVersionFrom(js(N,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ve.log(`\n${xF} 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 ${I}, in lockstep with the CLI.`),await(C.installFn??installGjsEnginePackages)(N,I,{verbose:n.verbose})}async function runPostInstallChecks(n){ve.log(`
|
|
1118
1118
|
--- gjsify post-install checks ---`);let S=runMinimalChecks(),C=S.filter(n=>!n.found&&n.severity===`required`);if(C.length>0){ve.warn(`Missing required system dependencies:
|
|
1119
|
-
`);for(let n of C)ve.warn(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),C);n&&ve.warn(`\nInstall with:\n ${n}`)}else ve.log(`System dependencies OK.`);await ensureProjectGjsEngine(n,S.find(n=>n.id===`gjs`)?.found??!1);let N=detectNativePackages(process.cwd());if(N.length>0){ve.log(`\nDetected ${N.length} @gjsify/* package(s) with native prebuilds:`);for(let n of N)ve.log(` • ${n.name}`);ve.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),S=js(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(S)&&existsSync(js(n,`.git`)))try{let C=spawnSync(nodeBinary(),[S,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});C.status!==0&&ve.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${C.status} — git hooks may not be active.`)}catch(n){ve.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var nB,rB,iB,aB,oB=__esmMin(()=>{ye(),Vl(),Hs(),gn(),Dh(),$z(),GM(),dN(),gN(),AP(),yF(),WP(),$P(),xP(),_P(),qM(),CF(),lF(),tB(),wP(),nB=process.platform===`win32`?`junction`:void 0,rB=18e5,iB={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:n=>n.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(`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:rB}).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 n=>{if(applyPlatformConfigFromFlags(n),n.immutable){if(n.packages&&n.packages.length>0)return ve.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(n.global)return ve.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(n[`refresh-lockfile`])return ve.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1)}if(n.global){if(!n.packages||n.packages.length===0)return ve.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let S of[`save-dev`,`save-peer`,`save-optional`])n[S]&&ve.warn(`gjsify install --global ignores --${S}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose,prune:n.prune});return}if(warnOnCliVersionSkew(process.cwd()),(n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),pruneProjectPrefix(n),await runPostInstallChecks(n);return}let S=n.timeout>0?n.timeout:0,C=S>0?new AbortController:null,N=C===null?null:setTimeout(()=>C.abort(Error(`install-overall-timeout`)),S),F=S>0?setTimeout(()=>{let n=Math.round(S/100)/10;ve.error(`gjsify install: the ${n}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)},S+1e4):null;F?.unref?.();try{await projectInstallNative(n,C?.signal),pruneProjectPrefix(n),await runPostInstallChecks(n)}catch(n){if(C!==null&&C.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(S/100)/10;return ve.error(`gjsify install: timed out after ${n}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 n}finally{N!==null&&clearTimeout(N),F!==null&&clearTimeout(F)}}},aB=`@gjsify/cli`});function readDirectChildren(n){let S;try{S=readdirSync(`/proc/${n}/task`)}catch{return null}let C=[],N=!1;for(let F of S)try{let S=readFileSync(`/proc/${n}/task/${F}/children`,`utf-8`);N=!0;for(let n of S.trim().split(/\s+/)){let S=Number(n);Number.isInteger(S)&&S>0&&C.push(S)}}catch{}return N?C:null}function buildPpidMap(){let n=new Map,S=[];try{S=`1.16093.16099.16106.16107.16114.24930.24941.acpi.bootconfig.buddyinfo.bus.cgroups.cmdline.consoles.cpuinfo.crypto.devices.diskstats.dma.driver.dynamic_debug.execdomains.fb.filesystems.fs.interrupts.iomem.ioports.irq.kallsyms.kcore.key-users.keys.kmsg.kpagecgroup.kpagecount.kpageflags.latency_stats.loadavg.locks.mdstat.meminfo.misc.modules.mounts.mtrr.net.pagetypeinfo.partitions.pressure.schedstat.scsi.self.slabinfo.softirqs.stat.swaps.sys.sysrq-trigger.sysvipc.thread-self.timer_list.tty.uptime.version.version_signature.vmallocinfo.vmstat.zoneinfo`.split(`.`)}catch{return n}for(let C of S){let S=Number(C);if(!(!Number.isInteger(S)||S<=0))try{let C=readFileSync(`/proc/${S}/stat`,`utf-8`),N=C.slice(C.lastIndexOf(`)`)+2).split(` `),F=Number(N[1]);if(!Number.isInteger(F)||F<=0)continue;let I=n.get(F);I?I.push(S):n.set(F,[S])}catch{}}return n}function collectDescendants(n){let S=[],C=new Set([n]),N=[n],F=null;for(;N.length>0;){let n=N.shift(),I=readDirectChildren(n);I===null&&(F??=buildPpidMap(),I=F.get(n)??[]);for(let n of I)C.has(n)||(C.add(n),S.push(n),N.push(n))}return S}function signalTree(n,S,C){for(let n=S.length-1;n>=0;n--)try{process.kill(S[n],C)}catch{}try{n.kill(C)}catch{}}function killActiveChildren(){let n=new Map;for(let S of sB){let C=S.pid?collectDescendants(S.pid):[];n.set(S,C),signalTree(S,C,`SIGTERM`)}setTimeout(()=>{for(let S of sB){let C=new Set(S.pid?collectDescendants(S.pid):[]);for(let N of n.get(S)??[])C.add(N);signalTree(S,[...C],`SIGKILL`)}},cB).unref?.()}function assertEveryIncludeMatches(n,S){if(!S||S.length===0)return;let C=S.filter(S=>filterWorkspaces(n,{include:[S]}).length===0);if(C.length===0)return;let N=[`gjsify foreach: --include matched no workspace (${C.length} of ${S.length} pattern(s)):`];for(let S of C){N.push(` ${JSON.stringify(S)}`);let C=stripSurroundingQuotes(S);if(C!==S&&filterWorkspaces(n,{include:[C]}).length>0){N.push(` → matches as ${JSON.stringify(C)}: 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 F=n.map(n=>n.name).filter(n=>n.toLowerCase().includes(C.replace(/\*/g,``).toLowerCase())).slice(0,3);F.length>0&&N.push(` → did you mean: ${F.join(`, `)}?`)}throw N.push(` ${n.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.`),ve.error(N.join(`
|
|
1119
|
+
`);for(let n of C)ve.warn(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),C);n&&ve.warn(`\nInstall with:\n ${n}`)}else ve.log(`System dependencies OK.`);await ensureProjectGjsEngine(n,S.find(n=>n.id===`gjs`)?.found??!1);let N=detectNativePackages(process.cwd());if(N.length>0){ve.log(`\nDetected ${N.length} @gjsify/* package(s) with native prebuilds:`);for(let n of N)ve.log(` • ${n.name}`);ve.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),S=js(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(S)&&existsSync(js(n,`.git`)))try{let C=spawnSync(nodeBinary(),[S,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});C.status!==0&&ve.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${C.status} — git hooks may not be active.`)}catch(n){ve.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var nB,rB,iB,aB,oB=__esmMin(()=>{ye(),Vl(),Hs(),gn(),Dh(),$z(),GM(),dN(),gN(),AP(),yF(),WP(),$P(),xP(),_P(),qM(),CF(),lF(),tB(),wP(),nB=process.platform===`win32`?`junction`:void 0,rB=18e5,iB={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:n=>n.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(`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:rB}).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 n=>{if(applyPlatformConfigFromFlags(n),n.immutable){if(n.packages&&n.packages.length>0)return ve.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(n.global)return ve.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(n[`refresh-lockfile`])return ve.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1)}if(n.global){if(!n.packages||n.packages.length===0)return ve.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let S of[`save-dev`,`save-peer`,`save-optional`])n[S]&&ve.warn(`gjsify install --global ignores --${S}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose,prune:n.prune});return}if(warnOnCliVersionSkew(process.cwd()),(n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),pruneProjectPrefix(n),await runPostInstallChecks(n);return}let S=n.timeout>0?n.timeout:0,C=S>0?new AbortController:null,N=C===null?null:setTimeout(()=>C.abort(Error(`install-overall-timeout`)),S),F=S>0?setTimeout(()=>{let n=Math.round(S/100)/10;ve.error(`gjsify install: the ${n}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)},S+1e4):null;F?.unref?.();try{await projectInstallNative(n,C?.signal),pruneProjectPrefix(n),await runPostInstallChecks(n)}catch(n){if(C!==null&&C.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(S/100)/10;return ve.error(`gjsify install: timed out after ${n}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 n}finally{N!==null&&clearTimeout(N),F!==null&&clearTimeout(F)}}},aB=`@gjsify/cli`});function readDirectChildren(n){let S;try{S=readdirSync(`/proc/${n}/task`)}catch{return null}let C=[],N=!1;for(let F of S)try{let S=readFileSync(`/proc/${n}/task/${F}/children`,`utf-8`);N=!0;for(let n of S.trim().split(/\s+/)){let S=Number(n);Number.isInteger(S)&&S>0&&C.push(S)}}catch{}return N?C:null}function buildPpidMap(){let n=new Map,S=[];try{S=`1.16078.16084.16091.16092.16099.24913.24924.acpi.bootconfig.buddyinfo.bus.cgroups.cmdline.consoles.cpuinfo.crypto.devices.diskstats.dma.driver.dynamic_debug.execdomains.fb.filesystems.fs.interrupts.iomem.ioports.irq.kallsyms.kcore.key-users.keys.kmsg.kpagecgroup.kpagecount.kpageflags.latency_stats.loadavg.locks.mdstat.meminfo.misc.modules.mounts.mtrr.net.pagetypeinfo.partitions.pressure.schedstat.scsi.self.slabinfo.softirqs.stat.swaps.sys.sysrq-trigger.sysvipc.thread-self.timer_list.tty.uptime.version.version_signature.vmallocinfo.vmstat.zoneinfo`.split(`.`)}catch{return n}for(let C of S){let S=Number(C);if(!(!Number.isInteger(S)||S<=0))try{let C=readFileSync(`/proc/${S}/stat`,`utf-8`),N=C.slice(C.lastIndexOf(`)`)+2).split(` `),F=Number(N[1]);if(!Number.isInteger(F)||F<=0)continue;let I=n.get(F);I?I.push(S):n.set(F,[S])}catch{}}return n}function collectDescendants(n){let S=[],C=new Set([n]),N=[n],F=null;for(;N.length>0;){let n=N.shift(),I=readDirectChildren(n);I===null&&(F??=buildPpidMap(),I=F.get(n)??[]);for(let n of I)C.has(n)||(C.add(n),S.push(n),N.push(n))}return S}function signalTree(n,S,C){for(let n=S.length-1;n>=0;n--)try{process.kill(S[n],C)}catch{}try{n.kill(C)}catch{}}function killActiveChildren(){let n=new Map;for(let S of sB){let C=S.pid?collectDescendants(S.pid):[];n.set(S,C),signalTree(S,C,`SIGTERM`)}setTimeout(()=>{for(let S of sB){let C=new Set(S.pid?collectDescendants(S.pid):[]);for(let N of n.get(S)??[])C.add(N);signalTree(S,[...C],`SIGKILL`)}},cB).unref?.()}function assertEveryIncludeMatches(n,S){if(!S||S.length===0)return;let C=S.filter(S=>filterWorkspaces(n,{include:[S]}).length===0);if(C.length===0)return;let N=[`gjsify foreach: --include matched no workspace (${C.length} of ${S.length} pattern(s)):`];for(let S of C){N.push(` ${JSON.stringify(S)}`);let C=stripSurroundingQuotes(S);if(C!==S&&filterWorkspaces(n,{include:[C]}).length>0){N.push(` → matches as ${JSON.stringify(C)}: 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 F=n.map(n=>n.name).filter(n=>n.toLowerCase().includes(C.replace(/\*/g,``).toLowerCase())).slice(0,3);F.length>0&&N.push(` → did you mean: ${F.join(`, `)}?`)}throw N.push(` ${n.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.`),ve.error(N.join(`
|
|
1120
1120
|
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(n){return n.length>=2&&(n[0]===`'`||n[0]===`"`)&&n[n.length-1]===n[0]?n.slice(1,-1):n}async function runSequential(n,S,C,N,F,I){for(let H of n)await runOne(H,S,C,!1,N,F,I)}async function runParallel(n,S,C,N,F,I,H){let W=0,q=[];for(let Y=0;Y<N;Y++)q.push((async()=>{for(;W<n.length;)await runOne(n[W++],S,C,!0,F,I,H)})());await Promise.all(q)}async function runTopologicalParallel(n,S,C,N,F,I,H,W){let q=new Set(n.map(n=>n.name)),Y=new Map;for(let S of n){let n=new Set,C=S.manifest;for(let S of[C.dependencies,I?C.devDependencies:void 0,C.optionalDependencies])if(S)for(let[C,N]of Object.entries(S))typeof N==`string`&&N.startsWith(`workspace:`)&&q.has(C)&&n.add(C);Y.set(S.name,n)}let X=new Map(n.map(n=>[n.name,n])),Z=n.length,te=new Set,ne=0,re=!process.stdout.isTTY||F,ie=new Map,ae=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),oe=(Number.isFinite(ae)&&ae>0?ae:20)*6e4;return new Promise((n,I)=>{let q=null,ae=Date.now(),describeInflight=()=>[...ie.entries()].map(([n,S])=>`${n} (${Math.round((Date.now()-S)/1e3)}s)`).join(`, `),failFast=n=>{q||(q=n,killActiveChildren(),setTimeout(()=>settle(),lB).unref?.())},se=setInterval(()=>{let n=Date.now()-ae;n<3e5||ie.size===0||(ve.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(n/6e4)}min — in-flight: ${describeInflight()}`),n>=oe&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(n/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);se.unref?.();let settle=()=>{clearInterval(se),q?I(q):n()},pump=()=>{if(!q){for(;ne<N;){let n=[...Y.entries()].filter(([,n])=>[...n].every(n=>te.has(n))).map(([n])=>n);if(n.length===0)break;let N=n.sort()[0];Y.delete(N),ne++,ie.set(N,Date.now()),re&&ve.error(`[gjsify foreach] start ${N} (${te.size}/${Z} done, ${ne} in flight)`),runOne(X.get(N),S,C,!0,F,H,W).then(()=>{te.add(N)}).catch(n=>{failFast(n instanceof Error?n:Error(String(n)))}).finally(()=>{ne--,ie.delete(N),ae=Date.now(),q?ne===0&&settle():Y.size===0&&ne===0?settle():pump()})}Y.size>0&&ne===0&&!q&&(clearInterval(se),I(Error(`gjsify foreach --topological: stuck — workspaces ${[...Y.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(n,S,C,N,F,I,H){if(I){F&&ve.error(`[${n.name}] $ ${S} ${C.join(` `)}`),await spawnPrefixed(S,C,n.location,N?`[${n.name}] `:null);return}if(H&&H.tryRestore(n))return;let W=H?.snapshotOutputs(n),q=detectPackageManager(),Y=q===`gjsify`?[`run`,S,...C]:[`run`,S,...C.length>0?[`--`,...C]:[]];F&&ve.error(`[${n.name}] $ ${q} ${Y.join(` `)}`),await spawnPrefixed(q,Y,n.location,N?`[${n.name}] `:null),H&&W&&H.storeAfterSuccess(n,W)}async function spawnPrefixed(n,S,C,N){let F=null,I=[];try{let H=await spawnToCompletion(n,S,{completion:`exit`,cwd:C,stdio:N?`pipe`:`inherit`,color:!0,onSpawn:n=>{F=n,sB.add(n);let S=!process.stdout.isTTY;N&&n.stdout&&n.stderr&&(I.push(prefixLines(n.stdout,process.stdout,N,S)),I.push(prefixLines(n.stderr,process.stderr,N,S)))}});for(let n of I)n();if(H.code!==0)throw Error(`${n} ${S.join(` `)} exited with code ${H.code}`)}finally{F&&sB.delete(F)}}var sB,cB,lB,uB,dB=__esmMin(()=>{ye(),_P(),Vl(),Dm(),GM(),qM(),wz(),LF(),WF(),qF(),sB=new Set,cB=5e3,lB=15e3,uB={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:n=>n.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}),handler:async n=>{let S=findWorkspaceRoot(process.cwd())??process.cwd(),C=discoverWorkspaces(S),N=n.exec===!0,F=n.script,I=n.args??[];if(!N){let S=(n[`--`]??[]).filter(n=>typeof n==`string`);S.length>0&&(I=[...I,...S])}if(N){let S=(n[`--`]??[]).filter(n=>typeof n==`string`);if(S.length>0&&(F?I=[...I,...S]:(F=S[0],I=[...I,...S.slice(1)])),!F)return ve.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(C,n.include);let H=filterWorkspaces(C,{include:n.include,exclude:n.exclude,noPrivate:n.private===!1});if(n[`with-dependencies`]===!0){let S=affectedClosure(buildDependencyGraph(C,{includeDev:n[`topological-dev`]===!0}),H.map(n=>n.name));H=filterWorkspaces(C.filter(n=>S.has(n.name)),{exclude:n.exclude,noPrivate:n.private===!1})}if(!N){if(!F)return ve.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let n=F;H=H.filter(S=>typeof(S.manifest.scripts??{})[n]==`string`)}if(typeof n.shard==`string`&&n.shard.length>0){let S=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(n.shard);if(!S)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let C=Number(S[1]),N=Number(S[2]);if(N<1||C<1||C>N)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(N>1){let n=[...H].sort((n,S)=>n.name<S.name?-1:+(n.name>S.name));H=n.filter((n,S)=>S%N===C-1),ve.log(`gjsify foreach: shard ${C}/${N} → ${H.length} of ${n.length} workspace(s)`)}}if(H.length===0){ve.log(`gjsify foreach: no workspaces match (${N?`exec`:`script`}="${F}", include=${JSON.stringify(n.include??[])}, exclude=${JSON.stringify(n.exclude??[])})`);return}(n.topological||n[`topological-dev`])&&(H=topologicalSort(buildDependencyGraph(H,{includeDev:n[`topological-dev`]===!0})));let W=n.verbose===!0,q=F,Y=n.cached??buildCacheEnabledByEnv();if(n.cached===!0&&N)return ve.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let X=Y&&!N?new BuildCacheRunner({root:S,workspaces:C,script:q,args:I,targets:H.map(n=>n.name)}):void 0,Z=n.parallel===!0?cliRuntimeClosure(C):new Set,te=Z.size>0?H.filter(n=>Z.has(n.name)):[],ne=te.length>0?H.filter(n=>!Z.has(n.name)):H;try{if(te.length>0){ve.error(`[gjsify foreach] serial prefix: ${te.length} package(s) the running CLI imports — ${te.map(n=>n.name).join(`, `)}`);for(let n of te)ve.error(`[gjsify foreach] start ${n.name} (serial prefix)`),await runOne(n,q,I,!0,W,N,X)}if(n.parallel&&!n.topological&&!n[`topological-dev`]){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runParallel(ne,q,I,S,W,N,X)}else if(n.parallel){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runTopologicalParallel(ne,q,I,S,W,n[`topological-dev`]===!0,N,X)}else await runSequential(ne,q,I,W,N,X)}catch(n){return killActiveChildren(),ve.error(n.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(n,S,C,N={}){let F=(S.scripts??{})[C];if(typeof F!=`string`){if(N.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${C}" in ${n}/package.json`)}let I=findWorkspaceRoot(n),H=[js(n,`node_modules`,`.bin`)];I&&I!==n&&H.push(js(I,`node_modules`,`.bin`));let W=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},q={...process.env,...W,PATH:[...H,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:C,npm_package_name:S.name??``,npm_package_version:S.version??``,...N.env};if(N.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let Y=await spawnToCompletion(F,[],{completion:`return`,cwd:n,env:q,shell:!0,stdio:N.stdio===`inherit-stderr`?`inherit-stderr`:N.stdio===`pipe`?`pipe`:`inherit`});if(Y.code!==0)throw Error(`gjsify lifecycle-script: "${C}" in ${n} exited with ${describeExit(Y)}`);return!0}var fB=__esmMin(()=>{Hs(),_P(),qM()});async function packWorkspace(n,S={}){let C=js(n,`package.json`);if(!existsSync(C))throw Error(`gjsify pack: no package.json at ${n}`);let N=readFileSync(C,`utf-8`),F=JSON.parse(N),I=typeof F.name==`string`?F.name:``,H=typeof F.version==`string`?F.version:`0.0.0`;if(!I)throw Error(`gjsify pack: package.json at ${n} has no "name"`);let W=S.lifecycleScripts??[`prepack`];for(let C of W)await runLifecycleScript(n,F,C,{optional:!0,stdio:S.lifecycleStdio});let q=readFileSync(C,`utf-8`),Y=q===N?F:JSON.parse(q),X=S.skipWorkspaceRewrite?Y:rewriteWorkspaceDeps(Y,n),Z=JSON.stringify(X,null,indentOf(q))+`
|
|
1121
1121
|
`,te=collectPackedFiles(n,Y);assertTypeDeclarationsShipped(n,Y,te);let ne=[{name:`package/`,directory:!0,mode:493}],re=[],ie=0;for(let S of te){let C;C=S===`package.json`?new TextEncoder().encode(Z):new Uint8Array(readFileSync(js(n,S)));let N=statSync(js(n,S)).mode&511;ne.push({name:`package/${S}`,body:C,mode:N,mtime:0}),re.push({path:S,size:C.byteLength,mode:N}),ie+=C.byteLength}let ae=await gzip(createTarball(ne)),oe=`${I.startsWith(`@`)?I.slice(1).replace(`/`,`-`):I}-${H}.tgz`,se=createHash(`sha1`).update(ae).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ae).digest(`base64`)}`,ce=S.destination?Os(S.destination):n,le=js(ce,oe);return S.dryRun||(mkdirSync(ce,{recursive:!0}),writeFileSync(le,ae)),{filename:oe,name:I,version:H,size:ae.byteLength,unpackedSize:ie,shasum:se,integrity:Q,entryCount:re.length,files:re,absolutePath:S.dryRun?null:le}}function collectPackedFiles(n,S){let C=forceIncluded(S),N=Array.isArray(S.files)?S.files.filter(n=>typeof n==`string`):null,F=new Set;if(N)for(let S of expandFilesPatterns(n,N))F.add(S);else{let S=loadIgnore(n);for(let C of walkAll(n))S(C)||F.add(C)}for(let S of C)existsSync(js(n,S))&&F.add(S);return[...F].sort()}function collectTypeDeclarationRefs(n){let S=new Set,add=n=>{if(typeof n!=`string`)return;let C=n.replace(/^\.\//,``);C.includes(`*`)||S.add(C)};for(let S of[`types`,`typings`])add(n[S]);let walk=n=>{if(!(!n||typeof n!=`object`)){if(Array.isArray(n)){for(let S of n)walk(S);return}for(let[S,C]of Object.entries(n))S===`types`||S===`typings`?add(C):walk(C)}};return walk(n.exports),[...S]}function assertTypeDeclarationsShipped(n,S,C){let N=new Set(C),F=collectTypeDeclarationRefs(S).filter(S=>{let C=js(n,S);return existsSync(C)&&statSync(C).isFile()&&!N.has(S)});if(F.length===0)return;let I=typeof S.name==`string`?S.name:`(unnamed)`,H=Array.isArray(S.files)?JSON.stringify(S.files):`(none)`;throw Error(`gjsify pack: ${I} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${H}):\n`+F.map(n=>` - ${n}`).join(`
|
|
1122
1122
|
`)+`
|
|
1123
1123
|
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(n){let S=new Set;S.add(`package.json`);for(let n of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])S.add(n);let C=typeof n.main==`string`?n.main:null;C&&S.add(C.replace(/^\.\//,``));let N=n.bin;if(typeof N==`string`)S.add(N.replace(/^\.\//,``));else if(N&&typeof N==`object`)for(let n of Object.values(N))typeof n==`string`&&S.add(n.replace(/^\.\//,``));return[...S]}function walkAll(n,S=``){let C=[],N=S?js(n,S):n,F;try{F=readdirSync(N,{withFileTypes:!0})}catch{return C}for(let N of F){if(mB.has(N.name)||N.name.startsWith(`.tsbuildinfo`))continue;let F=S?`${S}/${N.name}`:N.name;N.isDirectory()?C.push(...walkAll(n,F)):N.isFile()&&C.push(F)}return C}function expandFilesPatterns(n,S){let C=new Set,N=null;for(let F of S){let S=F.replace(/^\.\//,``).replace(/\/$/,``);if(!S)continue;if(!/[*?[\]]/.test(S)){let N=js(n,S);if(!existsSync(N))continue;let F=statSync(N);if(F.isDirectory())for(let N of walkAll(n,S))C.add(N);else F.isFile()&&C.add(S);continue}N??=walkAll(n);let I=filesGlobToRegExp(S),H=filesGlobToRegExp(`${S}/**`);for(let n of N)(I.test(n)||H.test(n))&&C.add(n)}return[...C]}function filesGlobToRegExp(n){let S=`^`;for(let C=0;C<n.length;C++){let N=n[C];if(N===`*`)n[C+1]===`*`?(S+=`.*`,C++,n[C+1]===`/`&&C++):S+=`[^/]*`;else if(N===`?`)S+=`[^/]`;else if(N===`[`){let N=C+1,F=`[`;for(n[N]===`!`&&(F+=`^`,N++);N<n.length&&n[N]!==`]`;N++)F+=n[N];N<n.length?(S+=`${F}]`,C=N):S+=`\\[`}else".+^${}()|\\]".includes(N)?S+=`\\${N}`:S+=N}return RegExp(`${S}$`)}function loadIgnore(n){let S=js(n,`.npmignore`),C=js(n,`.gitignore`),N=[],F=existsSync(S)?S:existsSync(C)?C:null;if(F){let n=readFileSync(F,`utf-8`).split(`
|
|
1124
1124
|
`);for(let S of n){let n=S.trim();!n||n.startsWith(`#`)||n.startsWith(`!`)||N.push(globToRegex(n))}}return n=>{for(let S of N)if(S.test(n))return!0;return!1}}function globToRegex(n){let S=n.replace(/^\//,``);return S=S.replace(/[.+^${}()|[\]\\]/g,`\\$&`),S=S.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),S=S.replace(/\?/g,`[^/]`),RegExp(`^${S}($|/)`)}function collectWorkspaceProtocolDeps(n){let S=[];for(let C of hB){let N=n[C];if(N)for(let[n,F]of Object.entries(N))typeof F==`string`&&F.startsWith(`workspace:`)&&S.push(`${C}.${n}`)}return S}function findPackWorkspaceRoot(n){let S=findWorkspaceRoot(n);if(S)return S;let C=n;for(let n=0;n<12;n++){let n=js(C,`package.json`);if(existsSync(n)&&readPackageJson$2(n)?.workspaces!==void 0)return C;let S=Os(C,`..`);if(S===C)break;C=S}return null}function rewriteWorkspaceDeps(n,S){let C=findPackWorkspaceRoot(S);if(!C){let C=collectWorkspaceProtocolDeps(n);if(C.length>0)throw Error(`gjsify pack: ${String(n.name)} declares workspace: ranges (${C.join(`, `)}) but ${S} 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 n}let N=new Map;for(let n of discoverWorkspaces(C))n.name&&n.version&&N.set(n.name,n.version);let F=JSON.parse(JSON.stringify(n));for(let n of hB){let S=F[n];if(S)for(let[I,H]of Object.entries(S)){if(typeof H!=`string`||!H.startsWith(`workspace:`))continue;let W=N.get(I);if(!W)throw Error(`gjsify pack: ${F.name} declares ${H} on ${I} (${n}) but no sibling workspace with that name exists in the monorepo at ${C}`);let q=H.slice(10);q===`*`||q===``?S[I]=W:q===`^`||q===`~`?S[I]=`${q}${W}`:S[I]=q}}return F}function indentOf(n){let S=n.match(/\n([ \t]+)"/);return S?S[1]:` `}var pB,mB,hB,gB=__esmMin(()=>{Vl(),No(),Hs(),UP(),GM(),qM(),KM(),fB(),pB={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:n=>n.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 n=>{let S=await packWorkspace(Os(n.path??process.cwd()),{destination:n[`pack-destination`],dryRun:n[`dry-run`]===!0,lifecycleScripts:n[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`});n.json?process.stdout.write(`${JSON.stringify([S],null,2)}\n`):process.stdout.write(`${S.filename}\n`)}},mB=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`]),hB=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function decodeJwtPayload(n){let S=n.split(`.`);if(S.length!==3)return null;try{let n=S[1].replace(/-/g,`+`).replace(/_/g,`/`),C=typeof atob==`function`?atob(n):Buffer.from(n,`base64`).toString(`binary`);return JSON.parse(C)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(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(n)}`;S?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I=await fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}});if(!I.ok){let n=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${n.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(n){let{packageName:S,registry:C,idToken:N,log:F}=n,I=`${C.endsWith(`/`)?C.slice(0,-1):C}/-/npm/v1/oidc/token/exchange/package/${S.startsWith(`@`)?(()=>{let n=S.indexOf(`/`),C=S.slice(1,n),N=S.slice(n+1);return`@${encodeURIComponent(C)}%2f${encodeURIComponent(N)}`})():encodeURIComponent(S)}`;F?.(`gjsify oidc: POST ${I}`);let H=n.maxRetries??3,W=n.retryBaseMs??1e3;for(let n=0;;n++){let C;try{C=await fetch(I,{method:`POST`,headers:{Authorization:`Bearer ${N}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(C){if(n<H){let C=Math.min(W*2**n,8e3);F?.(`gjsify oidc: network error for ${S} (attempt ${n+1}/${H+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${S} after ${n+1} attempt(s): ${C instanceof Error?C.message:String(C)}`,0,``,S,decodeJwtPayload(N)??void 0)}let q=await C.text().catch(()=>``);if(!C.ok){if(_B.has(C.status)&&n<H){let N=Math.min(W*2**n,8e3);F?.(`gjsify oidc: transient ${C.status} ${C.statusText} for ${S} (attempt ${n+1}/${H+1}), retrying in ${N}ms`),await sleep(N);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${S}: ${C.status} ${C.statusText} — ${q.slice(0,300)}`,C.status,q,S,decodeJwtPayload(N)??void 0)}let Y;try{Y=JSON.parse(q)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${S}: ${q.slice(0,200)}`,C.status,q,S)}if(!Y.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${S}`,C.status,q,S);return Y.token}}async function getNpmTrustedToken(n){let S=`npm:${new URL(n.registry).hostname}`,C=await fetchGithubOidcToken(S,n.log);return{token:await exchangeOidcForNpmToken({...n,idToken:C}),audience:S}}var _B,sleep,OidcUnavailableError,OidcExchangeError,vB=__esmMin(()=>{_B=new Set([408,425,429,500,502,503,504]),sleep=n=>new Promise(S=>setTimeout(S,n)),OidcUnavailableError=class extends Error{reason;constructor(n,S){super(n),this.reason=S,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(n,S,C,N,F){super(n),this.status=S,this.body=C,this.packageName=N,this.claims=F,this.name=`OidcExchangeError`}}});async function diagnose404(n){let{packageName:S,version:C,registry:N,npmrc:F}=n,I={};try{I=await whoami(N,F)}catch{return{reason:`unknown`,message:formatUnknown(S,C)}}return I.username&&I.username.length>0?{reason:`live-token-404`,username:I.username,message:formatLiveToken404(S,C,I.username)}:{reason:`dead-token`,message:formatDeadToken(S,C)}}function formatDeadToken(n,S){return[`gjsify publish: ${n}@${S} — 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(`
|
|
1125
1125
|
`)}function formatLiveToken404(n,S,C){return[`gjsify publish: ${n}@${S} — 404 Not Found`,``,`Authenticated as: ${C}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${n} 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(`
|
|
1126
|
-
`)}function formatUnknown(n,S){return`gjsify publish: ${n}@${S} — 404 Not Found`}function is404DiagnosticCandidate(n){let S=n.trim();return!!(S.length===0||/^not found$/i.test(S)||/"error"\s*:\s*"Not Found"/i.test(S))}var yB=__esmMin(()=>{ep()});function
|
|
1126
|
+
`)}function formatUnknown(n,S){return`gjsify publish: ${n}@${S} — 404 Not Found`}function is404DiagnosticCandidate(n){let S=n.trim();return!!(S.length===0||/^not found$/i.test(S)||/"error"\s*:\s*"Not Found"/i.test(S))}var yB=__esmMin(()=>{ep()});function backoffFor(n){return bB[Math.min(Math.max(n,0),bB.length-1)]??3e4}function probeTimeoutFor(n,S){return Math.min(n,Math.max(S,xB))}async function verifyPublishedVersion(n){let{registry:S,name:C,version:N,budgetMs:F}=n,I=n.fetchImpl??((...n)=>globalThis.fetch(...n)),H=n.sleep??(n=>new Promise(S=>setTimeout(S,n))),W=n.now??(()=>Date.now()),q=n.probeTimeoutMs??3e4,Y=`${S.endsWith(`/`)?S.slice(0,-1):S}/${escapePackageName(C)}`,X=W(),Z=0,te={state:`error`,detail:`no probe was sent`};for(let S=0;Z++,te=await probeOnce({url:Y,version:N,doFetch:I,probeTimeoutMs:probeTimeoutFor(q,F-(W()-X)),authorization:n.authorization}),n.log?.(`gjsify publish: read-back probe ${Z} of ${C}@${N} → ${te.state}`+(te.state===`present`?``:` (${te.detail})`)),te.state!==`present`;S++){let n=F-(W()-X);if(n<=0)break;await H(Math.min(backoffFor(S),n))}return{confirmed:te.state===`present`,attempts:Z,elapsedMs:W()-X,url:Y,last:te}}async function probeOnce(n){let{url:S,version:C,doFetch:N,probeTimeoutMs:F}=n,I=new AbortController,H=setTimeout(()=>I.abort(),F),W;try{W=await N(S,{headers:{accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...n.authorization?{authorization:n.authorization}:{}},signal:I.signal})}catch(n){return{state:`error`,detail:`request failed (${n instanceof Error?n.message:String(n)})`}}finally{clearTimeout(H)}if(W.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!W.ok)return{state:`error`,status:W.status,detail:`${W.status} ${W.statusText}`};let q;try{q=await W.json()}catch(n){let S=n instanceof Error?n.message:String(n);return{state:`error`,status:W.status,detail:`packument is not JSON (${S})`}}let Y=q?.versions,X=Y&&typeof Y==`object`?Object.keys(Y):[],Z=Y&&typeof Y==`object`?Y[C]:void 0;if(!Z){let n=X.length>0?X[X.length-1]:`(none)`;return{state:`absent`,status:W.status,detail:`packument carries ${X.length} version(s), newest ${n} — ${C} is not among them`}}let te=Z.dist?.tarball;return typeof te!=`string`||te.length===0?{state:`absent`,status:W.status,detail:`packument has ${C} but its \`dist.tarball\` is missing`}:{state:`present`,status:W.status,tarball:te}}function formatUnconfirmedPublish(n){let{name:S,version:C,putUrl:N,putStatus:F,putStatusText:I,payloadBytes:H,readback:W}=n,q=n.claim??`accepted`,Y=(W.elapsedMs/1e3).toFixed(1),X=W.last.state===`present`?`served`:W.last.detail,Z=q===`already-published`?`npm says ${C} is ALREADY PUBLISHED but the registry does not serve it.`:`npm ACCEPTED the upload but the registry does not serve it.`,te=q===`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: ${S}@${C} — ${Z}`,` PUT ${N} (${H} bytes) → ${F} ${I}`,` read-back GET ${W.url} (accept: application/vnd.npm.install-v1+json, cache-control: no-cache)`,` answered ${W.last.state}: ${X}`,` after ${W.attempts} probe(s) over ${Y}s`,...te].join(`
|
|
1127
|
+
`)}var bB,xB,SB,CB=__esmMin(()=>{np(),bB=[2e3,4e3,8e3,15e3,3e4],xB=2e3,SB=3e5});function beginPrompt(){wB++}function endPrompt(n=defaultWrite){if(wB=Math.max(0,wB-1),wB>0||TB.length===0)return;let S=TB.splice(0,TB.length);for(let C of S)n(C)}function writeAroundPrompt(n,S=defaultWrite){if(wB>0){TB.push(n);return}S(n)}function defaultWrite(n){process.stdout.write(n)}var wB,TB,EB=__esmMin(()=>{wB=0,TB=[]});function isTtyStdin(){let n=process.stdin;return!!n.isTTY&&typeof n.setRawMode==`function`}function applyKey(n,S,C){return S===`\r`||S===`
|
|
1127
1128
|
`?{buf:n,echo:`
|
|
1128
|
-
`,done:!0,interrupt:!1}:S===
|
|
1129
|
-
`,done:!1,interrupt:!0}:S===
|
|
1130
|
-
Enter OTP: `,
|
|
1131
|
-
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(n,S=promptLine,C={}){this.promptFn=S,this.registry=C.registry;let N=n&&n.length>0?n:void 0;N?(this.cached=N,this.registry&&writeCachedOtp(this.registry,N)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(n,S){if(S!==void 0&&this.generation>S&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(n??(this.generation>0?jB:AB));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(n){let S=(await this.promptFn(n)).trim();return S&&(this.cached=S,this.generation++,this.registry&&writeCachedOtp(this.registry,S)),S}invalidate(n){n!==void 0&&this.generation!==n||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});async function publishWorkspace(n){let{wsDir:S,tag:C,access:N,provenance:F,tolerate:I,tolerateUntrustedNew:H,trustedFlag:W,verbose:q,json:Y,otpProvider:X}=n,Z=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:Y?`inherit-stderr`:`inherit`}),te=await packWorkspaceToBytes(S),ne=readFileSync(js(S,`package.json`),`utf-8`),re=await loadRewrittenManifest(S,JSON.parse(ne)),ie=await loadNpmrc(S),ae=n.registry??process.env.npm_config_registry??registryFor(Z.name,ie)??qf,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,se=`${oe}/${escapePackageName(Z.name)}`,Q=`${Z.name.includes(`/`)?Z.name.slice(Z.name.indexOf(`/`)+1):Z.name}-${Z.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:C,access:N,tarballBytes:te,tarballUrl:`${oe}/${Z.name}/-/${Q}`,packed:{...Z,wireFilename:Q},provenance:F}),le=buildPublishHeaders(se,{npmrc:ie}),ue=W===!0||W===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,de=`token`;if(ue)try{let{token:n,audience:S}=await getNpmTrustedToken({packageName:Z.name,registry:ae,log:q?n=>ve.error(n):void 0});le.authorization=`Bearer ${n}`,de=`oidc`,q&&ve.error(`gjsify publish: OIDC token obtained (audience=${S})`)}catch(n){if(n instanceof OidcExchangeError&&n.status===404&&/package not found/i.test(n.body)&&H)return{ok:!0,action:`skipped-untrusted-new`,name:Z.name,version:Z.version};if(W===!0)return{ok:!1,action:`oidc-failed`,name:Z.name,version:Z.version,error:n};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:Z.name,version:Z.version,error:n};if(q){let S=n instanceof Error?n.message:String(n);ve.error(`gjsify publish: OIDC auto-detect failed (${S}) — falling back to token auth`)}}q&&(ve.error(`gjsify publish: PUT ${se} (${Z.name}@${Z.version})`),ve.error(` auth-mode: ${de}`),ve.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ve.error(` payload size: ${JSON.stringify(ce).length} bytes`));let fe=JSON.stringify(ce),doPut=n=>{let S={...le};return n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`),fetch(se,{method:`PUT`,headers:S,body:fe})},pe=await withOtpRetry(doPut,X,{seedFirstAttempt:n.seedOtpFirst});if(await isOtpChallenge(pe))return{ok:!1,action:`otp-required`,name:Z.name,version:Z.version,status:pe.status};if(pe.ok)return{ok:!0,action:`published`,name:Z.name,version:Z.version,filename:Z.filename,size:Z.size,integrity:Z.integrity,tag:C,registry:oe};let me=await pe.text().catch(()=>`<no body>`);if((pe.status===409||pe.status===403&&/previously published/i.test(me))&&I)return{ok:!0,action:`republish-tolerated`,name:Z.name,version:Z.version,status:pe.status};if(pe.status===404&&de===`token`&&is404DiagnosticCandidate(me)){let n=await diagnose404({packageName:Z.name,version:Z.version,registry:oe,npmrc:ie});if(n.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:Z.name,version:Z.version,status:404,diag:n}}return{ok:!1,action:`error`,name:Z.name,version:Z.version,status:pe.status,statusText:pe.statusText,text:me}}function reportPublishOutcome(n,S){switch(n.action){case`published`:{let C={ok:!0,name:n.name,version:n.version,filename:n.filename,size:n.size,integrity:n.integrity,tag:n.tag,registry:n.registry};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${n.name}@${n.version}\n`);return}case`republish-tolerated`:{let C={ok:!0,action:`republish-tolerated`,name:n.name,version:n.version,status:n.status};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${n.name}@${n.version} (already published, tolerated)\n`);return}case`skipped-untrusted-new`:S?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:n.name,version:n.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${n.name}@${n.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`otp-required`:return ve.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(n.error,n.name,S),process.exit(1);case`oidc-no-token`:{let C=n.error instanceof Error?n.error.message:String(n.error);return ve.error(`gjsify publish: OIDC token exchange failed for ${n.name} (${C}) and no fallback npm token is configured — refusing to publish without credentials.`),S&&process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return S?process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,status:404,diagnostic:n.diag.reason,username:n.diag.username},null,2)}\n`):process.stderr.write(`${n.diag.message}\n`),process.exit(1);case`error`:return ve.error(`gjsify publish: ${n.name}@${n.version} — ${n.status} ${n.statusText}`),ve.error(n.text),process.exit(1)}}async function packWorkspaceToBytes(n){let S=js(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),C=await packWorkspace(n,{destination:S,dryRun:!1,lifecycleScripts:[]});if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let N=new Uint8Array(readFileSync(C.absolutePath));try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmSync(C.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmdirSync(S)}catch{}return N}async function loadRewrittenManifest(n,S){let C=js(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),N=await packWorkspace(n,{destination:C,dryRun:!1}),{rmSync:F}=await Promise.resolve().then(()=>(Vl(),Rl));if(!N.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:I,parseTar:H}=await Promise.resolve().then(()=>(UP(),HP)),W=new Uint8Array(readFileSync(N.absolutePath));F(C,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let q=await I(W);for(let n of H(q))if(n.name===`package/package.json`&&n.body)return JSON.parse(new TextDecoder().decode(n.body));return S}function buildPublishPayload(n){let{pkg:S,tag:C,access:N,tarballBytes:F,tarballUrl:I,packed:H,provenance:W}=n,q={...S,_id:`${H.name}@${H.version}`,dist:{integrity:H.integrity,shasum:H.shasum,tarball:I}};W&&(q._hasShrinkwrap=!1);let Y={_id:H.name,name:H.name,description:typeof S.description==`string`?S.description:``,"dist-tags":{[C]:H.version},versions:{[H.version]:q},readme:``,_attachments:{[H.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(F),length:F.byteLength}}};return N&&(Y.access=N),Y}function base64Encode(n){let S=``,C=32768;for(let N=0;N<n.length;N+=C)S+=String.fromCharCode(...n.subarray(N,N+C));return btoa(S)}function handleOidcFailure(n,S,C){if(n instanceof OidcUnavailableError){let N=`gjsify publish: OIDC not available — ${n.message}`;C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-unavailable`,reason:n.reason,message:n.message})}\n`):process.stderr.write(`${N}\n`);return}if(n instanceof OidcExchangeError){let N=n.status===401||n.status===403?`npm rejected the OIDC exchange (${n.status}) — check that ${S} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(S)}/access pointing at this workflow.`:n.message;if(C)process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-exchange`,status:n.status,body:n.body,claims:n.claims,message:n.message})}\n`);else if(process.stderr.write(`✗ ${S}: ${N}\n`),n.body&&process.stderr.write(` ↳ npm said: ${n.body.slice(0,300)}\n`),n.claims){let S=n.claims,C=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(n=>S[n]!==void 0).map(n=>`${n}=${JSON.stringify(S[n])}`).join(`, `);C&&process.stderr.write(` ↳ JWT claims npm received: ${C}\n`)}return}let N=n instanceof Error?n.message:String(n);C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`unknown`,message:N})}\n`):process.stderr.write(`✗ ${S}: ${N}\n`)}var NB,PB=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),ep(),np(),gB(),vB(),yB(),aI(),MB(),EB(),NB={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:n=>n.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(`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 n=>{let S=Os(n.path??process.cwd()),C=n.tag??`latest`,N=n.access,F=n.otp,I=n[`tolerate-republish`]===!0,H=n[`tolerate-untrusted-new`]===!0,W=n.provenance===!0,q=n[`dry-run`]===!0,Y=n[`check-trusted`]===!0,X=n.trusted,Z=!!process.env.GJSIFY_PUBLISH_DEBUG;if(W&&ve.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Y){let C=js(S,`package.json`),N=JSON.parse(readFileSync(C,`utf-8`));if(typeof N.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${C} has no \`name\` field\n`),process.exit(2);if(N.private===!0){let S={ok:!0,action:`check-trusted`,name:N.name,skipped:`private`};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`- ${N.name}: skipped (private package)\n`);return}let F=await loadNpmrc(S),I=process.env.npm_config_registry??registryFor(N.name,F)??qf;try{await getNpmTrustedToken({packageName:N.name,registry:I,log:Z?n=>ve.error(n):void 0});let S={ok:!0,action:`check-trusted`,name:N.name,registry:I};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`✓ ${N.name}: trusted publisher OK\n`);return}catch(S){handleOidcFailure(S,N.name,n.json===!0);return}}if(q){let C=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`}),N={ok:!0,action:`dry-run`,name:C.name,version:C.version,filename:C.filename,size:C.size,shasum:C.shasum,integrity:C.integrity};n.json?process.stdout.write(`${JSON.stringify(N,null,2)}\n`):process.stdout.write(`+ ${C.name}@${C.version} (dry-run, ${C.size} bytes, ${C.entryCount} files)\n`);return}let te=!!(process.stdin.isTTY&&process.stdout.isTTY),ne=await loadNpmrc(S),re;try{re=JSON.parse(readFileSync(js(S,`package.json`),`utf-8`)).name}catch{}let ie=process.env.npm_config_registry??(re?registryFor(re,ne):void 0)??ne.registry??qf,ae=new OtpProvider(F,te?promptLine:async()=>``,{registry:ie});reportPublishOutcome(await publishWorkspace({wsDir:S,tag:C,access:N,provenance:W,tolerate:I,tolerateUntrustedNew:H,trustedFlag:X,verbose:Z,json:n.json===!0,otpProvider:ae,seedOtpFirst:F!==void 0}),n.json===!0)}}}),FB,IB=__esmMin(()=>{ep(),aI(),FB={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:n=>n.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??S.registry??qf,N=C.endsWith(`/`)?C.slice(0,-1):C,F=n.json===!0;if(!hasAnyCredential(S))return F?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:N})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${N}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1129
|
+
`,done:!0,interrupt:!1}:S===DB?{buf:n,echo:`
|
|
1130
|
+
`,done:!1,interrupt:!0}:S===OB||S===kB?n.length>0?{buf:n.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:n,echo:``,done:!1,interrupt:!1}:S>=` `?{buf:n+S,echo:C?`*`:S,done:!1,interrupt:!1}:{buf:n,echo:``,done:!1,interrupt:!1}}async function runRawSession(n){let S=process.stdin,C=process.stdout,N=null,cleanup=()=>{S.removeListener(`data`,onData);try{S.setRawMode(!1)}catch{}typeof S.pause==`function`&&S.pause()},onData=n=>{let S=typeof n==`string`?n:n.toString(`utf-8`);for(let n of S){if(!N)continue;let S=applyKey(N.buf,n,N.mask);if(N.buf=S.buf,S.echo&&C.write(S.echo),S.interrupt)return cleanup(),process.exit(130);if(S.done){let{resolve:n}=N;N=null,n(S.buf)}}};S.setRawMode(!0),typeof S.resume==`function`&&S.resume(),S.setEncoding(`utf-8`),S.on(`data`,onData);let read=(n,S)=>new Promise(F=>{beginPrompt(),C.write(n),N={mask:S,buf:``,resolve:n=>{endPrompt(),F(n)}}});try{return await n(read)}finally{cleanup()}}function readLine(){return new Promise(n=>{let S=``,onData=C=>{S+=typeof C==`string`?C:C.toString(`utf-8`);let N=S.search(/[\r\n]/);N>=0&&(cleanup(),n(S.slice(0,N)))},onEnd=()=>{cleanup(),n(S.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(n){if(!isTtyStdin()){beginPrompt(),process.stdout.write(n);try{return await readLine()}finally{endPrompt()}}return runRawSession(S=>S(n,!1))}async function promptCredentials(n){if(!isTtyStdin()){let S=n;S||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let C=await readLine();return{username:S,password:C}}return runRawSession(async S=>({username:n??await S(`Username: `,!1),password:await S(`Password: `,!0)}))}var DB,OB,kB,AB=__esmMin(()=>{EB(),DB=``,OB=``,kB=`\b`});function isOtpCacheEnabled(){let n=process.env[jB];return!(n===`1`||n===`true`||n===`yes`)}function normalizeRegistry(n){return n.endsWith(`/`)?n.slice(0,-1):n}function cacheBaseDir(n){if(n?.dir)return n.dir;let S=process.env.XDG_RUNTIME_DIR;return js(S&&S.length>0?S:tmpdir(),MB)}function cacheFileFor(n,S){let C=normalizeRegistry(n).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return js(cacheBaseDir(S),`otp-${C||`default`}.json`)}function readCachedOtp(n,S){if(!isOtpCacheEnabled())return;let C=S?.now??Date.now(),N=cacheFileFor(n,S);try{if(!existsSync(N))return;let S=JSON.parse(readFileSync(N,`utf8`));if(!S||typeof S.otp!=`string`||typeof S.expiresAt!=`number`){deleteCacheFile(N);return}if(S.registry!==normalizeRegistry(n))return;if(C>=S.expiresAt){deleteCacheFile(N);return}return S.otp.length>0?S.otp:void 0}catch{deleteCacheFile(N);return}}function writeCachedOtp(n,S,C){if(!isOtpCacheEnabled()||!S||S.length===0)return;let N=C?.now??Date.now(),F=C?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(C),{recursive:!0,mode:448});let I=cacheFileFor(n,C),H={otp:S,expiresAt:N+F,registry:normalizeRegistry(n)};writeFileSync(I,JSON.stringify(H),{mode:384}),chmodSync(I,384)}catch{}}function clearCachedOtp(n,S){deleteCacheFile(cacheFileFor(n,S))}function deleteCacheFile(n){try{existsSync(n)&&rmSync(n,{force:!0})}catch{}}var jB,MB,NB=__esmMin(()=>{Vl(),Dm(),Hs(),jB=`GJSIFY_NO_OTP_CACHE`,MB=`gjsify-otp`});async function isOtpChallenge(n){if(n.status!==401)return!1;if((n.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let S=await n.clone().text().catch(()=>``);return/one-time pass/i.test(S)||/\bEOTP\b/.test(S)}async function withOtpRetry(n,S,C={}){let N=C.maxPrompts??2,F=C.question,I=S.current(),H=C.seedFirstAttempt===!0&&I!==void 0,W=S.epoch(),q=await n(H?I:void 0);if(!await isOtpChallenge(q))return q;if(H&&S.invalidate(W),!H&&S.current()!==void 0){if(W=S.epoch(),q=await n(S.current()),!await isOtpChallenge(q))return q;S.invalidate(W)}for(let C=0;C<N;C++){let C=await S.refresh(F,W);if(!C||(W=S.epoch(),q=await n(C),!await isOtpChallenge(q)))return q;S.invalidate(W)}return q}var PB,FB,OtpProvider,IB=__esmMin(()=>{AB(),NB(),PB=`This operation requires a one-time password.
|
|
1131
|
+
Enter OTP: `,FB=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
|
|
1132
|
+
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(n,S=promptLine,C={}){this.promptFn=S,this.registry=C.registry;let N=n&&n.length>0?n:void 0;N?(this.cached=N,this.registry&&writeCachedOtp(this.registry,N)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(n,S){if(S!==void 0&&this.generation>S&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(n??(this.generation>0?FB:PB));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(n){let S=(await this.promptFn(n)).trim();return S&&(this.cached=S,this.generation++,this.registry&&writeCachedOtp(this.registry,S)),S}invalidate(n){n!==void 0&&this.generation!==n||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});async function publishWorkspace(n){let{wsDir:S,tag:C,access:N,provenance:F,tolerate:I,tolerateUntrustedNew:H,trustedFlag:W,verbose:q,json:Y,otpProvider:X}=n,Z=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:Y?`inherit-stderr`:`inherit`}),te=await packWorkspaceToBytes(S),ne=readFileSync(js(S,`package.json`),`utf-8`),re=await loadRewrittenManifest(S,JSON.parse(ne)),ie=await loadNpmrc(S),ae=n.registry??process.env.npm_config_registry??registryFor(Z.name,ie)??qf,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,se=`${oe}/${escapePackageName(Z.name)}`,Q=`${Z.name.includes(`/`)?Z.name.slice(Z.name.indexOf(`/`)+1):Z.name}-${Z.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:C,access:N,tarballBytes:te,tarballUrl:`${oe}/${Z.name}/-/${Q}`,packed:{...Z,wireFilename:Q},provenance:F}),le=buildPublishHeaders(se,{npmrc:ie}),ue=W===!0||W===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,de=`token`;if(ue)try{let{token:n,audience:S}=await getNpmTrustedToken({packageName:Z.name,registry:ae,log:q?n=>ve.error(n):void 0});le.authorization=`Bearer ${n}`,de=`oidc`,q&&ve.error(`gjsify publish: OIDC token obtained (audience=${S})`)}catch(n){if(n instanceof OidcExchangeError&&n.status===404&&/package not found/i.test(n.body)&&H)return{ok:!0,action:`skipped-untrusted-new`,name:Z.name,version:Z.version};if(W===!0)return{ok:!1,action:`oidc-failed`,name:Z.name,version:Z.version,error:n};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:Z.name,version:Z.version,error:n};if(q){let S=n instanceof Error?n.message:String(n);ve.error(`gjsify publish: OIDC auto-detect failed (${S}) — falling back to token auth`)}}q&&(ve.error(`gjsify publish: PUT ${se} (${Z.name}@${Z.version})`),ve.error(` auth-mode: ${de}`),ve.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ve.error(` payload size: ${JSON.stringify(ce).length} bytes`));let fe=JSON.stringify(ce),doPut=n=>{let S={...le};return n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`),fetch(se,{method:`PUT`,headers:S,body:fe})},pe=await withOtpRetry(doPut,X,{seedFirstAttempt:n.seedOtpFirst});if(q){ve.error(` response: ${pe.status} ${pe.statusText}`);let n=await pe.clone().text().catch(()=>``);n&&ve.error(` body: ${n.slice(0,300)}`)}let readBack=async()=>{let S=n.verifyBudgetMs??3e5;if(!(S<=0))return verifyPublishedVersion({registry:oe,name:Z.name,version:Z.version,budgetMs:S,authorization:le.authorization,log:q?n=>ve.error(n):void 0})};if(await isOtpChallenge(pe))return{ok:!1,action:`otp-required`,name:Z.name,version:Z.version,status:pe.status};if(pe.ok){let n=await readBack();return n?.confirmed&&q&&ve.error(` read-back: confirmed after ${n.attempts} probe(s) in ${n.elapsedMs} ms`),n&&!n.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:Z.name,version:Z.version,registry:oe,putStatus:pe.status,putStatusText:pe.statusText,putUrl:se,payloadBytes:fe.length,readback:n}:{ok:!0,action:`published`,name:Z.name,version:Z.version,filename:Z.filename,size:Z.size,integrity:Z.integrity,tag:C,registry:oe,readback:n}}let me=await pe.text().catch(()=>`<no body>`);if((pe.status===409||pe.status===403&&/previously published/i.test(me))&&I){let n=await readBack();return n&&!n.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:Z.name,version:Z.version,registry:oe,putStatus:pe.status,putStatusText:pe.statusText,putUrl:se,payloadBytes:fe.length,readback:n}:{ok:!0,action:`republish-tolerated`,name:Z.name,version:Z.version,status:pe.status,readback:n}}if(pe.status===404&&de===`token`&&is404DiagnosticCandidate(me)){let n=await diagnose404({packageName:Z.name,version:Z.version,registry:oe,npmrc:ie});if(n.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:Z.name,version:Z.version,status:404,diag:n}}return{ok:!1,action:`error`,name:Z.name,version:Z.version,status:pe.status,statusText:pe.statusText,text:me}}function reportPublishOutcome(n,S,C=!1){switch(n.action){case`published`:{let C={ok:!0,name:n.name,version:n.version,filename:n.filename,size:n.size,integrity:n.integrity,tag:n.tag,registry:n.registry};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${n.name}@${n.version}\n`);return}case`publish-unconfirmed`:{let N=formatUnconfirmedPublish(n);if(S?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:n.name,version:n.version,registry:n.registry,claim:n.claim,putStatus:n.putStatus,probes:n.readback.attempts,elapsedMs:n.readback.elapsedMs,readbackUrl:n.readback.url,readbackState:n.readback.last.state,deferred:C},null,2)}\n`):process.stderr.write(`${N}\n`),C){if(process.env.GITHUB_ACTIONS){let S=n.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${n.name}@${n.version} ${S} (HTTP ${n.putStatus}) but did not resolve on ${n.registry} within ${(n.readback.elapsedMs/1e3).toFixed(1)}s — the release-closure job must confirm it\n`)}return}return process.exit(1)}case`republish-tolerated`:{let C={ok:!0,action:`republish-tolerated`,name:n.name,version:n.version,status:n.status};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${n.name}@${n.version} (already published, tolerated)\n`);return}case`skipped-untrusted-new`:S?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:n.name,version:n.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${n.name}@${n.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`otp-required`:return ve.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(n.error,n.name,S),process.exit(1);case`oidc-no-token`:{let C=n.error instanceof Error?n.error.message:String(n.error);return ve.error(`gjsify publish: OIDC token exchange failed for ${n.name} (${C}) and no fallback npm token is configured — refusing to publish without credentials.`),S&&process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return S?process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,status:404,diagnostic:n.diag.reason,username:n.diag.username},null,2)}\n`):process.stderr.write(`${n.diag.message}\n`),process.exit(1);case`error`:return ve.error(`gjsify publish: ${n.name}@${n.version} — ${n.status} ${n.statusText}`),ve.error(n.text),process.exit(1)}}async function packWorkspaceToBytes(n){let S=js(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),C=await packWorkspace(n,{destination:S,dryRun:!1,lifecycleScripts:[]});if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let N=new Uint8Array(readFileSync(C.absolutePath));try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmSync(C.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmdirSync(S)}catch{}return N}async function loadRewrittenManifest(n,S){let C=js(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),N=await packWorkspace(n,{destination:C,dryRun:!1}),{rmSync:F}=await Promise.resolve().then(()=>(Vl(),Rl));if(!N.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:I,parseTar:H}=await Promise.resolve().then(()=>(UP(),HP)),W=new Uint8Array(readFileSync(N.absolutePath));F(C,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let q=await I(W);for(let n of H(q))if(n.name===`package/package.json`&&n.body)return JSON.parse(new TextDecoder().decode(n.body));return S}function buildPublishPayload(n){let{pkg:S,tag:C,access:N,tarballBytes:F,tarballUrl:I,packed:H,provenance:W}=n,q={...S,_id:`${H.name}@${H.version}`,dist:{integrity:H.integrity,shasum:H.shasum,tarball:I}};W&&(q._hasShrinkwrap=!1);let Y={_id:H.name,name:H.name,description:typeof S.description==`string`?S.description:``,"dist-tags":{[C]:H.version},versions:{[H.version]:q},readme:``,_attachments:{[H.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(F),length:F.byteLength}}};return N&&(Y.access=N),Y}function base64Encode(n){let S=``,C=32768;for(let N=0;N<n.length;N+=C)S+=String.fromCharCode(...n.subarray(N,N+C));return btoa(S)}function handleOidcFailure(n,S,C){if(n instanceof OidcUnavailableError){let N=`gjsify publish: OIDC not available — ${n.message}`;C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-unavailable`,reason:n.reason,message:n.message})}\n`):process.stderr.write(`${N}\n`);return}if(n instanceof OidcExchangeError){let N=n.status===401||n.status===403?`npm rejected the OIDC exchange (${n.status}) — check that ${S} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(S)}/access pointing at this workflow.`:n.message;if(C)process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-exchange`,status:n.status,body:n.body,claims:n.claims,message:n.message})}\n`);else if(process.stderr.write(`✗ ${S}: ${N}\n`),n.body&&process.stderr.write(` ↳ npm said: ${n.body.slice(0,300)}\n`),n.claims){let S=n.claims,C=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(n=>S[n]!==void 0).map(n=>`${n}=${JSON.stringify(S[n])}`).join(`, `);C&&process.stderr.write(` ↳ JWT claims npm received: ${C}\n`)}return}let N=n instanceof Error?n.message:String(n);C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`unknown`,message:N})}\n`):process.stderr.write(`✗ ${S}: ${N}\n`)}var LB,RB=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),ep(),np(),gB(),vB(),yB(),CB(),aI(),IB(),AB(),LB={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:n=>n.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.",type:`number`,default:SB/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.path??process.cwd()),C=n.tag??`latest`,N=n.access,F=n.otp,I=n[`tolerate-republish`]===!0,H=n[`tolerate-untrusted-new`]===!0,W=n[`verify-timeout`]??3e5/1e3;if(!Number.isFinite(W)||W<0)return ve.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(n[`verify-timeout`])}`),process.exit(2);let q=Math.round(W*1e3),Y=n[`verify-defer`]===!0,X=n.provenance===!0,Z=n[`dry-run`]===!0,te=n[`check-trusted`]===!0,ne=n.trusted,re=!!process.env.GJSIFY_PUBLISH_DEBUG;if(X&&ve.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),te){let C=js(S,`package.json`),N=JSON.parse(readFileSync(C,`utf-8`));if(typeof N.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${C} has no \`name\` field\n`),process.exit(2);if(N.private===!0){let S={ok:!0,action:`check-trusted`,name:N.name,skipped:`private`};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`- ${N.name}: skipped (private package)\n`);return}let F=await loadNpmrc(S),I=process.env.npm_config_registry??registryFor(N.name,F)??qf;try{await getNpmTrustedToken({packageName:N.name,registry:I,log:re?n=>ve.error(n):void 0});let S={ok:!0,action:`check-trusted`,name:N.name,registry:I};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`✓ ${N.name}: trusted publisher OK\n`);return}catch(S){handleOidcFailure(S,N.name,n.json===!0);return}}if(Z){let C=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`}),N={ok:!0,action:`dry-run`,name:C.name,version:C.version,filename:C.filename,size:C.size,shasum:C.shasum,integrity:C.integrity};n.json?process.stdout.write(`${JSON.stringify(N,null,2)}\n`):process.stdout.write(`+ ${C.name}@${C.version} (dry-run, ${C.size} bytes, ${C.entryCount} files)\n`);return}let ie=!!(process.stdin.isTTY&&process.stdout.isTTY),ae=await loadNpmrc(S),oe;try{oe=JSON.parse(readFileSync(js(S,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(oe?registryFor(oe,ae):void 0)??ae.registry??qf,Q=new OtpProvider(F,ie?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:S,tag:C,access:N,provenance:X,tolerate:I,tolerateUntrustedNew:H,trustedFlag:ne,verbose:re,json:n.json===!0,otpProvider:Q,seedOtpFirst:F!==void 0,verifyBudgetMs:q}),n.json===!0,Y)}}}),zB,BB=__esmMin(()=>{ep(),aI(),zB={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:n=>n.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??S.registry??qf,N=C.endsWith(`/`)?C.slice(0,-1):C,F=n.json===!0;if(!hasAnyCredential(S))return F?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:N})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${N}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1132
1133
|
`)+`
|
|
1133
1134
|
`),process.exit(1);let I;try{I=await whoami(C,S)}catch(n){let S=n instanceof Error?n.message:String(n);return F?process.stdout.write(`${JSON.stringify({error:S,registry:N})}\n`):(process.stderr.write(`gjsify whoami: ${S}\n`),process.stderr.write(`Registry: ${N}\n`)),process.exit(1)}if(I.username&&I.username.length>0){F?process.stdout.write(`${JSON.stringify({username:I.username,registry:N})}\n`):(process.stdout.write(`Logged in as: ${I.username}\n`),process.stdout.write(`Registry: ${N}\n`));return}F?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:N})}\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(`
|
|
1134
1135
|
`)+`
|
|
@@ -1137,12 +1138,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
|
|
|
1137
1138
|
`)+`
|
|
1138
1139
|
`),C}function removeAuthToken(n){let S=userconfigNpmrcPath(),C=authTokenKey(n),N=readUserconfig(S);if(!N)return{path:S,removed:!1};let F=N.split(`
|
|
1139
1140
|
`),I=F.filter(n=>!n.replace(/\s+/g,``).startsWith(`${C}=`)),H=I.length!==F.length;return H&&writeUserconfig(S,I.join(`
|
|
1140
|
-
`)),{path:S,removed:H}}var
|
|
1141
|
-
Enter OTP: `),!X)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(N,X),Z=await putUser(``,X)}}if(Z.status===409){let n=await fetch(`${W}?write=true`,{headers:authHeaders(X)});if(n.ok){let S=await n.json().catch(()=>({}));for(let n of Object.keys(S))(!q[n]||n===`roles`)&&(q[n]=S[n]);q._rev&&(Z=await putUser(`/-rev/${q._rev}`,X))}}if(Z.status===400)throw new LoginError(`gjsify login: there is no user with the username "${F}" on ${N}.`);if(!Z.ok){let n=await Z.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${Z.status} ${Z.statusText} from ${N}\n${n.slice(0,400)}`)}let te=await Z.json().catch(()=>({}));if(!te.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 ne=writeAuthToken(N,te.token);return X&&writeCachedOtp(N,X),{username:(await whoami(N,await loadNpmrc(n.cwd??process.cwd()))).username??F,registry:N,npmrcPath:ne}}var LoginError,
|
|
1142
|
-
`)[0].slice(0,200)}var
|
|
1141
|
+
`)),{path:S,removed:H}}var VB=__esmMin(()=>{Vl(),Dm(),Hs()});async function runLogin(n){let S=await loadNpmrc(n.cwd??process.cwd()),C=n.registry??process.env.npm_config_registry??(n.scope?registryFor(n.scope.startsWith(`@`)?`${n.scope}/_`:`@${n.scope}/_`,S):void 0)??qf,N=C.endsWith(`/`)?C:`${C}/`,{username:F,password:I}=await promptCredentials(n.username);if(!F)throw new LoginError(`gjsify login: a username is required.`);if(!I)throw new LoginError(`gjsify login: a password is required.`);let H=`Basic ${btoa(`${F}:${I}`)}`,W=`${N}-/user/org.couchdb.user:${encodeURIComponent(F)}`,q={_id:`org.couchdb.user:${F}`,name:F,password:I,type:`user`,roles:[],date:void 0};function authHeaders(n){let S={authorization:H,"content-type":`application/json`,accept:`*/*`};return n&&(S[`npm-otp`]=n),S}async function putUser(n,S){return fetch(`${W}${n}`,{method:`PUT`,headers:authHeaders(S),body:JSON.stringify(q)})}let Y=typeof n.otp==`string`&&n.otp.length>0,X=n.otp??readCachedOtp(N),Z=await putUser(``,X);if(Z.status===401&&!Y){let n=(Z.headers.get(`www-authenticate`)??``).toLowerCase(),S=await Z.clone().text().catch(()=>``);if(n.includes(`otp`)||/one-time pass/i.test(S)){if(clearCachedOtp(N),X=await promptLine(`This operation requires a one-time password.
|
|
1142
|
+
Enter OTP: `),!X)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(N,X),Z=await putUser(``,X)}}if(Z.status===409){let n=await fetch(`${W}?write=true`,{headers:authHeaders(X)});if(n.ok){let S=await n.json().catch(()=>({}));for(let n of Object.keys(S))(!q[n]||n===`roles`)&&(q[n]=S[n]);q._rev&&(Z=await putUser(`/-rev/${q._rev}`,X))}}if(Z.status===400)throw new LoginError(`gjsify login: there is no user with the username "${F}" on ${N}.`);if(!Z.ok){let n=await Z.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${Z.status} ${Z.statusText} from ${N}\n${n.slice(0,400)}`)}let te=await Z.json().catch(()=>({}));if(!te.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 ne=writeAuthToken(N,te.token);return X&&writeCachedOtp(N,X),{username:(await whoami(N,await loadNpmrc(n.cwd??process.cwd()))).username??F,registry:N,npmrcPath:ne}}var LoginError,HB,UB=__esmMin(()=>{ye(),ep(),aI(),VB(),AB(),NB(),LoginError=class extends Error{constructor(n){super(n),this.name=`LoginError`}},HB={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:n=>n.option(`registry`,{description:`Registry URL to log in to. Default: ${qf} (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 n=>{try{let{username:S,registry:C,npmrcPath:N}=await runLogin({registry:n.registry,scope:n.scope,username:n.username,otp:n.otp});n.json?process.stdout.write(`${JSON.stringify({username:S,registry:C})}\n`):process.stdout.write(`Logged in as ${S} on ${C}\n(token written to ${N})\n`)}catch(n){if(n instanceof LoginError)return ve.error(n.message),process.exit(1);throw n}}}}),WB,GB=__esmMin(()=>{ep(),aI(),VB(),NB(),WB={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:n=>n.option(`registry`,{description:`Registry URL to log out of. Default: ${qf} (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 n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??(n.scope?registryFor(n.scope.startsWith(`@`)?`${n.scope}/_`:`@${n.scope}/_`,S):void 0)??qf,N=C.endsWith(`/`)?C:`${C}/`,F=resolveAuthForUrl(`${N}-/whoami`,S),I=!1;if(F?.startsWith(`Bearer `)){let n=F.slice(7);try{I=(await fetch(`${N}-/user/token/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{authorization:F,accept:`*/*`}})).ok}catch{}}clearCachedOtp(N);let{path:H,removed:W}=removeAuthToken(N);n.json?process.stdout.write(`${JSON.stringify({registry:N,revoked:I,removed:W})}\n`):W?process.stdout.write(`Logged out of ${N}${I?` (token revoked)`:``}\n(removed from ${H})\n`):process.stdout.write(`No token for ${N} found in ${H} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(n){let S=n,C=KB[0];for(let n=0;n<8&&!existsSync(js(S,...C));n++){let n=Ps(S);if(n===S)return[];S=n}let N=[];for(let n of KB){let C=js(S,...n);if(!existsSync(C))continue;let F;try{F=readdirSync(C,{withFileTypes:!0})}catch{continue}for(let S of F){if(!S.isDirectory())continue;let F=js(C,S.name),I=js(F,`package.json`);if(existsSync(I))try{let C=JSON.parse(readFileSync(I,`utf8`));if(!C||typeof C.name!=`string`||C.name.length===0)continue;N.push({location:F,relativeLocation:js(...n,S.name),name:C.name,version:typeof C.version==`string`?C.version:`0.0.0`,manifest:C,private:C.private===!0})}catch{}}}return N}function mergePublishables(n,S){let C=new Set(n.map(n=>n.name));return[...n,...discoverNonWorkspacePublishables(S).filter(n=>!C.has(n.name))]}var KB,qB=__esmMin(()=>{Vl(),Hs(),KB=[[`packages`,`node-gi`],[`packages`,`napi`],[`packages`,`node-runtime`]]});function trustUrl(n,S){return`${n.endsWith(`/`)?n.slice(0,-1):n}/-/package/${escapePackageName(S)}/trust`}function githubTrustBody(n){let S={repository:n.repository,workflow_ref:{file:normalizeWorkflowFile(n.workflow)}};return n.environment&&(S.environment=n.environment),[{type:`github`,claims:S,permissions:n.permissions&&n.permissions.length>0?n.permissions:[JB]}]}function normalizeWorkflowFile(n){return n.split(`/`).pop()??n}function validateRepository(n){let S=n.split(`/`);return S.length===2&&S[0].length>0&&S[1].length>0}function matchesGithubTrust(n,S){if(n.type!==`github`)return!1;let C=n.claims?.repository,N=n.claims?.workflow_ref?.file;return C===S.repository&&N===normalizeWorkflowFile(S.workflow)}function classifyTrustList(n,S,C){return n===404?`unpublished`:n===401?`auth-required`:n>=200&&n<300?(Array.isArray(S)?S:[]).some(n=>matchesGithubTrust(n,C))?`trusted`:`untrusted`:`error`}function parseRepoFromGitRemote(n){let S=n.trim();if(!S)return null;S=S.replace(/^git\+/,``),S=S.replace(/\.git$/,``);let C=S.match(/^[^/@]+@[^:]+:(.+)$/);if(C)return twoSegments(C[1]);let N=S.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return N?twoSegments(N[1]):null}function twoSegments(n){let S=n.split(`/`).filter(n=>n.length>0);return S.length<2?null:`${S[S.length-2]}/${S[S.length-1]}`}var JB,YB=__esmMin(()=>{np(),JB=`createPackage`});function createTrustRequester(n){return async(S,C,N)=>{let doFetch=F=>{let I=buildHeaders(C,{npmrc:n.npmrc});I.accept=`application/json`,N!==void 0&&(I[`content-type`]=`application/json`),F&&(I[`npm-otp`]=F);let H={method:S,headers:I};return N!==void 0&&(H.body=JSON.stringify(N)),fetch(C,H)},F=await withOtpRetry(doFetch,n.otpProvider),I=await F.text().catch(()=>``),H;try{H=I?JSON.parse(I):void 0}catch{}return{status:F.status,json:H,text:I,headers:F.headers}}}function firstLine(n){return n.split(`
|
|
1143
|
+
`)[0].slice(0,200)}var XB,ZB=__esmMin(()=>{ye(),Dh(),Vl(),Hs(),ep(),GM(),qB(),aI(),IB(),YB(),XB={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:n=>n.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 ${qf}).`,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 n=>{let S=process.cwd(),C=await loadNpmrc(S);if(!hasAnyCredential(C))return ve.error("gjsify trust: no npm token configured. Run `gjsify login` first."),process.exit(1);let N=n.registry??process.env.npm_config_registry??C.registry??qf;if(n[`dry-run`]!==!0){let n;try{n=await whoami(N,C)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`gjsify trust: npm auth check failed (${S}).\nYour ~/.npmrc token is dead or revoked — refresh it with \`npm login\`, then re-run.
|
|
1143
1144
|
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!n.username)return ve.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);ve.log(`gjsify trust: authenticated as ${n.username}`)}let F=n.repository;if(!F){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(F=parseRepoFromGitRemote(n.stdout)??void 0)}if(!F)return ve.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(F))return ve.error(`gjsify trust: --repository must be "owner/repo", got "${F}".`),process.exit(1);let I=normalizeWorkflowFile(n.workflow),H=n.environment,W=n.list===!0,q=n[`dry-run`]===!0,Y=n.force===!0,X=js(S,`.github`,`workflows`,I);existsSync(X)||ve.warn(`gjsify trust: note — ${X} not found; configuring trust for "${I}" anyway.`);let Z=filterWorkspaces(mergePublishables(discoverWorkspaces(S,{includeRoot:!0}),S),{noPrivate:n.private!==!0,include:n.packages&&n.packages.length>0?n.packages:void 0}).filter(n=>n.name);if(Z.length===0)return ve.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ve.log(`gjsify trust: ${Z.length} package(s) | repo=${F} workflow=${I}`),q&&ve.log(`(dry-run — nothing will be written)`),ve.log();let te=createTrustRequester({npmrc:C,otpProvider:new OtpProvider(n.otp)}),ne=0,re=0,ie=0,ae=0,oe=[],se=[];for(let S of Z){let N=S.name,X=trustUrl(n.registry??registryFor(N,C)??qf,N);process.stdout.write(`→ ${N.padEnd(42)} `);let Z=await te(`GET`,X),Q=classifyTrustList(Z.status,Z.json,{repository:F,workflow:I});if(W){Q===`trusted`?ve.log(`trusted`):Q===`unpublished`?ve.log(`unpublished`):Q===`auth-required`?ve.log(`auth-required (could not read)`):Q===`untrusted`?ve.log(`not trusted`):ve.log(`error (HTTP ${Z.status})`);continue}if(Q===`trusted`&&!Y){ve.log(`already configured — skip`),re++;continue}if(Q===`unpublished`){ve.log(`not on npm yet — needs first-publish, skip`),ie++,oe.push(N);continue}if(q){ve.log(`would configure`),ne++;continue}let ce=await te(`POST`,X,githubTrustBody({repository:F,workflow:I,environment:H}));ce.status>=200&&ce.status<300?(ve.log(`configured`),ne++):ce.status===409?(ve.log(`already configured (409) — done`),re++):ce.status===404?(ve.log(`not on npm yet — needs first-publish, skip`),ie++,oe.push(N)):(ve.log(`FAILED (HTTP ${ce.status})`),ae++,se.push(`${N} — HTTP ${ce.status}${ce.text?`: ${firstLine(ce.text)}`:``}`))}if(!W){if(ve.log(),ve.log(`Done: ${ne} ${q?`would-configure`:`configured`}, ${re} already-configured, ${ie} unpublished, ${ae} failed.`),oe.length>0){ve.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let n of oe)ve.log(` ${n}`)}if(se.length>0){ve.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let n of se)ve.log(` ${n}`);process.exit(1)}}}}});function resolveRepoRoot(n){let S=findWorkspaceRoot(n);if(S)return S;let C=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:n,encoding:`utf8`});if(C.status===0){let n=C.stdout.trim();if(n&&existsSync(n))return n}return n}function assertEveryPatternMatches(n,S){let C=S.filter(S=>{try{return discoverWorkspaces(n,{patterns:[S]}).length===0}catch{return!0}});if(C.length===0)return;let N=[`gjsify onboard: --packages matched no package directory (${C.length} of ${S.length} pattern(s)) under ${n}:`];for(let n of C)N.push(` ${JSON.stringify(n)}`);throw N.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(N.join(`
|
|
1144
1145
|
`))}function collectOnboardPackages(n,S,C={}){let N=[],F=[],I=new Set,take=(n,S,C)=>{let H=0;for(let n of S)!n.name||I.has(n.name)||(I.add(n.name),F.push(n),H++);N.push({kind:n,patterns:C,count:H})};if(existsSync(js(n,`package.json`)))try{take(`workspaces`,discoverWorkspaces(n,{includeRoot:!0}))}catch{}return C.patterns&&C.patterns.length>0&&take(`packages`,discoverWorkspaces(n,{patterns:[...C.patterns]}),C.patterns),take(`scanned-dirs`,mergePublishables([],S)),{packages:F,sources:N}}function describeSources(n){return n.filter(n=>n.count>0).map(n=>n.patterns?`${n.kind}(${n.patterns.join(`,`)})=${n.count}`:`${n.kind}=${n.count}`).join(` + `)}function declaredRepository(n){let S=n.manifest.repository,C=typeof S==`string`?S:S?.url;return typeof C!=`string`||C.length===0?null:parseRepoFromGitRemote(C)}function assertRepositoryAgreement(n,S){let C=S.toLowerCase(),N=n.map(n=>({ws:n,declared:declaredRepository(n)})).filter(n=>n.declared!==null&&n.declared.toLowerCase()!==C);if(N.length===0)return;let F=new Map;for(let{ws:n,declared:S}of N){let C=F.get(S)??[];C.push(n.name),F.set(S,C)}let I=[`gjsify onboard: ${N.length} selected package(s) declare a DIFFERENT repository than ${S}:`];for(let[n,S]of F){let C=S.slice(0,5).join(`, `),N=S.length>5?`, … (+${S.length-5} more)`:``;I.push(` ${n}: ${S.length} package(s) — ${C}${N}`)}throw I.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(I.join(`
|
|
1145
|
-
`))}var JB=__esmMin(()=>{Vl(),Dh(),GM(),Hs(),UB(),GB(),qM()});function describeRateLimitHeaders(n){if(!n)return`no headers captured`;let S=[];return n.forEach((n,C)=>{(/^retry-after$/i.test(C)||/ratelimit/i.test(C))&&S.push(`${C}: ${n}`)}),S.length>0?S.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(n){let S=n?.get(`retry-after`);if(!S)return null;let C=Number.parseInt(S.trim(),10);return!Number.isFinite(C)||C<0?null:C*1e3}async function packumentExists(n,S){let C=n.endsWith(`/`)?n.slice(0,-1):n;try{let n=await fetch(`${C}/${S.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return n.status===404?!1:n.ok?!0:null}catch{return null}}function actionForState(n){switch(n){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(n){return new Promise(S=>setTimeout(S,n))}async function requestWaitingOutRateLimit(n,S,C,N,F={}){let I=F.sleep??defaultSleep,H=F.maxRateLimitWaitMs??3e5,W=F.rateLimitBaseDelayMs??2e3,q=F.gate;q&&await q.wait();let Y=await n(S,C,N),X=0;for(let Z=0;Y.status===429&&X<H;Z++){let te=retryAfterMs(Y.headers),ne=Math.min(te??W*2**Z,YB),re=Math.min(ne,H-X);F.onRateLimit?.({url:C,headers:describeRateLimitHeaders(Y.headers),waitMs:re,fromRetryAfter:te!==null}),q?.penalize(re),await(q?q.wait():I(re)),X+=re,Y=await n(S,C,N)}return Y}async function probeTrustState(n,S,C,N={}){let F=C.registryOverride??registryFor(S.name,C.npmrc)??qf,I=trustUrl(F,S.name),H={repository:C.repository,workflow:C.workflow},W=N.sleep??defaultSleep,q=await requestWaitingOutRateLimit(n,`GET`,I,void 0,N),Y=classifyTrustList(q.status,q.json,H);return Y===`auth-required`&&N.retryOn401!==!1&&(await W(N.retryDelayMs??400),q=await n(`GET`,I),Y=classifyTrustList(q.status,q.json,H)),(Y===`untrusted`||Y===`auth-required`)&&await(N.exists??packumentExists)(F,S.name)===!1&&(Y=`unpublished`),{ws:S,registry:F,url:I,state:Y,httpStatus:q.status,action:actionForState(Y)}}async function probeAllTrustStates(n,S,C,N,F={}){if(S.length===0)return[];let I=S.length,H=0,report=n=>(H++,F.onProgress?.(H,I,n),n);return[report(await probeTrustState(n,S[0],N,F)),...await mapWithConcurrency(S.slice(1),Math.max(1,C),async S=>report(await probeTrustState(n,S,N,F)))]}async function mapWithConcurrency(n,S,C){let N=Array.from({length:n.length}),F=0,I=Array.from({length:Math.min(Math.max(1,S),n.length)},async()=>{for(;;){let S=F++;if(S>=n.length)return;N[S]=await C(n[S])}});return await Promise.all(I),N}var YB,RateLimitGate,XB=__esmMin(()=>{ep(),GB(),YB=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(n={}){this.now=n.now??(()=>Date.now()),this.sleeper=n.sleep??defaultSleep}async wait(){let n=this.until-this.now();n>0&&await this.sleeper(n)}penalize(n){this.until=Math.max(this.until,this.now()+n)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(n,S,C){let N=C.failed??0;if(C.asJson)process.stdout.write(`${JSON.stringify({ok:N===0,dryRun:C.dryRun,root:C.root,sources:C.sources,discovered:C.discovered,total:S.length,published:n.filter(n=>n.result===`published`||n.result===`published+trusted`).length,trusted:n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length,alreadyDone:n.filter(n=>n.result===`already-done`).length,failed:N,results:n},null,2)}\n`);else{let S=C.dryRun?N>0?`Dry-run INCOMPLETE — nothing changed, but ${N} 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: ${n.filter(n=>n.result.includes(`published`)).length} published, ${n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length} trusted, ${n.filter(n=>n.result===`already-done`).length} already done, ${N} failed.`;process.stdout.write(`\n${S}\n`)}process.exit(+(N>0))}function statusCell(n){switch(n.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${n.httpStatus})`}}async function ensureAuthenticated(n){let{npmrc:S,registry:C,cwd:N,nonInteractive:F,dryRun:I,otp:H,log:W}=n;if(hasAnyCredential(S))try{let n=await whoami(C,S);if(n.username)return n.username}catch{}if(I){W(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(F)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");W(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:C,otp:H,cwd:N})).username}catch(n){throw n instanceof LoginError?Error(n.message):n}}async function buildIfPresent(n,S){if(typeof(n.manifest.scripts??{}).build!=`string`)return;let C=detectPackageManager(),N=[`run`,`build`];S(` $ ${C} ${N.join(` `)}`);let{code:F}=await spawnToCompletion(C,N,{completion:`return`,cwd:n.location,env:{...process.env}});if(F!==0)throw Error(`build exited with code ${F}`)}function describePublishFailure(n){switch(n.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${n.diag.reason})`;case`error`:return`HTTP ${n.status} ${n.statusText}`;default:return`unknown`}}var ZB,QB,$B=__esmMin(()=>{ye(),Dh(),ep(),GM(),aI(),MB(),SB(),PB(),qB(),zB(),qF(),_P(),JB(),GB(),XB(),ZB=4,QB={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:n=>n.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 ${qf}).`,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:ZB}).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 n=>{let S=process.cwd(),C=n[`dry-run`]===!0,N=n.json===!0,F=n.yes===!0,log=(n=``)=>{N?process.stderr.write(`${n}\n`):writeAroundPrompt(`${n}\n`)},I=await loadNpmrc(S),H=n.registry??process.env.npm_config_registry??I.registry??qf,W;try{W=await ensureAuthenticated({npmrc:I,registry:H,cwd:S,nonInteractive:F,dryRun:C,otp:n.otp,log})}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:S})}\n`):ve.error(S),process.exit(1)}I=await loadNpmrc(S),W&&log(`gjsify onboard: authenticated as ${W}`);let q=n.repository;if(!q){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(q=parseRepoFromGitRemote(n.stdout)??void 0)}if(!q||!validateRepository(q)){let n=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:n})}\n`):ve.error(n),process.exit(1)}let Y=normalizeWorkflowFile(n.workflow),X=n.environment,Z=resolveRepoRoot(S),te,ne;try{n.packages&&n.packages.length>0&&assertEveryPatternMatches(Z,n.packages);let C=collectOnboardPackages(Z,S,{patterns:n.packages});te=C.packages,ne=describeSources(C.sources)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:S})}\n`):ve.error(S),process.exit(1)}let re=filterWorkspaces(te,{noPrivate:!0,include:n.include,exclude:n.exclude}).filter(n=>n.name);if(re.length===0){let n=`gjsify onboard: no publishable packages found under ${Z} (discovered ${te.length}${ne?` — ${ne}`:``}). `+(te.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 N?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:n})}\n`):ve.error(n),process.exit(1)}try{assertRepositoryAgreement(re,q)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:S})}\n`):ve.error(S),process.exit(1)}log(`gjsify onboard: root=${Z} | ${ne}`),log(`gjsify onboard: ${re.length} of ${te.length} package(s) selected | repo=${q} workflow=${Y}`),C&&log(`(dry-run — nothing will be published or configured)`),log();let ie=new OtpProvider(n.otp,F?async()=>``:void 0,{registry:H}),ae=createTrustRequester({npmrc:I,otpProvider:ie}),oe=new RateLimitGate,se=!1,onRateLimit=n=>{se||(se=!0,log(` npm rate limit hit. ${n.headers}. Waiting ${Math.round(n.waitMs/1e3)}s (${n.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:oe,onRateLimit},ce=Math.max(1,Math.min(50,Math.ceil(re.length/10))),le=0,ue=0,de=0;re.length>ce&&log(`Reading trust state for ${re.length} package(s)…`);let fe=await probeAllTrustStates(ae,re,Math.max(1,n.concurrency),{registryOverride:n.registry,npmrc:I,repository:q,workflow:Y},{...Q,onProgress:(n,S,C)=>{if(C.action===`trust`||C.action===`publish-and-trust`?le++:C.action===`skip`?ue++:de++,n%ce!==0&&n!==S||S<=ce)return;let N=[`${le} to do`,`${ue} already done`];de>0&&N.push(`${de} unreadable`),log(` read ${n}/${S} — ${N.join(`, `)}`)}}),pe=fe.filter(n=>n.action===`publish-and-trust`),me=fe.filter(n=>n.action===`trust`),he=fe.filter(n=>n.action===`skip`),ge=fe.filter(n=>n.action===`blocked`);for(let S of fe)S.action===`skip`&&n.verbose!==!0||log(` ${statusCell(S)} ${S.ws.name}`);!n.verbose&&he.length>0&&log(` (${he.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${he.length} already done, ${pe.length} to publish+trust, ${me.length} to trust, ${ge.length} unreadable.`);let _e=ge.filter(n=>n.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 ye=[];if(C){for(let n of fe)ye.push({name:n.ws.name,result:n.action===`skip`?`already-done`:n.action===`blocked`?`failed`:`skipped-dry-run`,detail:n.action===`publish-and-trust`?`would publish + trust`:n.action===`trust`?`would trust`:n.action===`blocked`?`state HTTP ${n.httpStatus}`:void 0});finish(ye,fe,{asJson:N,dryRun:C,failed:ge.length,root:Z,sources:ne,discovered:te.length});return}let be=githubTrustBody({repository:q,workflow:Y,environment:X}),xe=Math.max(1,n[`write-concurrency`]),Se=pe.length+me.length,Ce=Array.from({length:fe.length}),we=0,Te=0,Ee=0,configureTrust=async(n,S,C)=>{let N=await requestWaitingOutRateLimit(ae,`POST`,n.url,be,Q),F=`${++Te}/${Se}`;N.status>=200&&N.status<300?(log(` [${F}] trusted ${n.ws.name}`),Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}):N.status===409?Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}:N.status===404?(log(` [${F}] ${n.ws.name}: published but not yet trust-configurable (re-run onboard)`),Ce[S]={name:n.ws.name,result:C?`published`:`failed`,detail:`trust config deferred (404)`},C||we++):(log(` [${F}] trust failed (HTTP ${N.status}) — ${n.ws.name}`),Ce[S]={name:n.ws.name,result:`failed`,detail:`trust HTTP ${N.status}`},N.status===429&&Ee++,we++)},De=[];for(let S=0;S<fe.length;S++){let C=fe[S];if(C.action===`skip`){Ce[S]={name:C.ws.name,result:`already-done`};continue}if(C.action===`blocked`){log(`→ ${C.ws.name}: cannot read trust state (HTTP ${C.httpStatus}) — skipped`),Ce[S]={name:C.ws.name,result:`failed`,detail:`state HTTP ${C.httpStatus}`},we++;continue}if(C.action===`trust`){De.push({p:C,i:S});continue}log(`→ ${C.ws.name}: building + publishing…`);try{n.build!==!1&&await buildIfPresent(C.ws,log)}catch(n){let N=n instanceof Error?n.message:String(n);log(` build failed: ${N}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`build: ${N}`},we++;continue}let N=await publishWorkspace({wsDir:C.ws.location,tag:`latest`,access:n.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:C.registry,verbose:!1,json:!1,otpProvider:ie,seedOtpFirst:!1});if(!N.ok){let n=describePublishFailure(N);log(` publish failed: ${n}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`publish: ${n}`},we++;continue}log(` published ${N.name}@${`version`in N?N.version:``}`),await configureTrust(C,S,N.action!==`skipped-untrusted-new`)}De.length>0&&(De.length>1&&log(`→ configuring ${De.length} Trusted Publisher(s), ${xe} at a time…`),await mapWithConcurrency(De,xe,async({p:n,i:S})=>configureTrust(n,S,!1)));for(let n of Ce)n&&ye.push(n);Ee>0&&(log(),log(`${Ee} 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 ${xe}) provokes the limit less.`)),finish(ye,fe,{asJson:N,dryRun:C,failed:we,root:Z,sources:ne,discovered:te.length})}}});function pathFor(n){return n===`win32`?Cs:xs}function isInside$1(n,S,C){let N=pathFor(C);if(!N.isAbsolute(n)||!N.isAbsolute(S))return!1;let F=S.endsWith(N.sep)?S:S+N.sep;return n===S||n.startsWith(F)}function classifyInstall(n){let S=n.env??process.env,C=n.platform??process.platform,N=pathFor(C),F=N.resolve(n.selfDir);if(S.FLATPAK_ID||isInside$1(F,tV,C)){let n=S.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:S.FLATPAK_ID?`FLATPAK_ID=${S.FLATPAK_ID}`:`running from ${tV}`,updateWith:`flatpak update ${n}`,managedElsewhere:!0}}return isInside$1(F,N.resolve(n.xdgPrefix),C)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${n.xdgPrefix}`,managedElsewhere:!1}:C!==`win32`&&eV.some(n=>isInside$1(F,n,C))?{kind:`system-package`,evidence:`running from the system prefix ${F}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:F.split(N.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${F}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${F}, which matches no known install layout`,managedElsewhere:!1}}var eV,tV,nV=__esmMin(()=>{Hs(),eV=[`/usr/`,`/opt/`,`/snap/`],tV=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(n){let S=n.platform??process.platform,C=S===`win32`?Cs:xs,norm=n=>S===`win32`?C.resolve(n).toLowerCase():C.resolve(n);if(n.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${n.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${n.binDir}`};if(norm(C.dirname(n.resolvedBin))===norm(n.binDir))return{ok:!0};let N=n.runningVersion?` (v${n.runningVersion})`:``;return{ok:!1,message:`BUT \`${n.binName}\` on PATH resolves to\n ${n.resolvedBin}${N}\nwhich is NOT the install that was just updated, so the next \`${n.binName}\`\nyou run will not be v${n.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${rV}\`)\n or put ${n.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 \`${n.binName} --version\`.`}}function readSelfDir(){let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n)return Ps(Os(n));let S=fileURLToPath(import.meta.url),C=Ps(Os(S));for(let n=0;n<8&&C!==Ps(C);n++){if(existsSync(js(C,`package.json`)))return C;C=Ps(C)}return Ps(Os(S))}function readCurrentVersion(){try{let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n){let S=JSON.parse(readFileSync(n,`utf-8`));return S.name===rV&&typeof S.version==`string`?S.version:null}let S=Ps(Os(fileURLToPath(import.meta.url)));for(let n=0;n<8&&S!==Ps(S);n++){let n=js(S,`package.json`);if(existsSync(n)){let S=JSON.parse(readFileSync(n,`utf-8`));if(S.name===rV&&typeof S.version==`string`)return S.version}S=Ps(S)}}catch{}return null}function resolveTag(n,S){let C=n[`dist-tags`]??{};return C[S]?C[S]:n.versions&&typeof n.versions==`object`&&n.versions[S]?S:null}var rV,iV,aV,oV=__esmMin(()=>{ye(),Vl(),Hs(),gn(),ep(),yF(),nV(),CF(),lF(),tB(),rV=`@gjsify/cli`,iV={command:`self-update`,description:`Update the installed ${rV} to the latest release (or pinned --tag).`,builder:n=>n.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async n=>{let S=defaultGlobalLayout(),C=js(js(S.prefix,`node_modules`,rV),`package.json`),N=readCurrentVersion(),F=existsSync(C);ve.log(`Current ${rV}: v${N??`(unknown)`}`);let I=classifyInstall({selfDir:readSelfDir(),xdgPrefix:S.prefix});if(I.managedElsewhere)return ve.error(`\ngjsify self-update: this gjsify is managed by something else — ${I.evidence}.\nUpdating it from here would write ${S.prefix} and leave you running two installs.\n\nUpdate with: ${I.updateWith}\n`),process.exit(1);F||ve.warn(`\nWarning: no @gjsify/cli install found under ${S.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`),ve.log(`Fetching dist-tags for ${rV}@${n.tag} ...`);let H;try{H=await fetchPackument(rV)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`Failed to fetch packument: ${S}`),process.exit(1)}let W=resolveTag(H,n.tag);if(!W)return ve.error(`Unknown dist-tag '${n.tag}' on ${rV}. Known tags: ${Object.keys(H[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ve.log(`Latest matching --tag ${n.tag}: v${W}`);let q=F&&!hasBundlerEngineInstalled(S.prefix),Y=q&&!n.skipDeps&&!n.check;if(N===W&&!n.force&&!Y){ve.log(`Already up to date (v${W}).`),q&&n.skipDeps&&ve.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)."),n.check||ve.log(`Run with --force to reinstall anyway.`);return}if(Y&&N===W&&!n.force&&ve.log(`@gjsify/cli is at v${W} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),n.check)return ve.log(N?`Update available: v${N} → v${W}`:`Install required: → v${W}`),process.exit(1);let X=!n.skipDeps,Z=X?` + runtime dependencies`:` (bundle only)`;ve.log(`Installing ${rV}@${W}${Z} ...`);let te=makeProgressReporter();try{await installPackages({prefix:S.prefix,specs:[`${rV}@${W}`],verbose:!1,skipDeps:!X,progress:te})}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`self-update: install failed — ${S}`),ve.error("Re-run `gjsify self-update` to retry."),process.exit(1)}X&&await installGjsEnginePackages(S.prefix,W,{verbose:!1}),n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let ne=linkGlobalBins([rV],S);if(ne.length===0)ve.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let n of ne)ve.log(` • ${n.link} → ${n.target}`);if(globalLayoutIsDefault()){let n=verifyPathResolution({binName:aV,binDir:S.binDir,resolvedBin:resolveBinOnPath(aV),runningVersion:N,targetVersion:W});if(!n.ok)return ve.error(`\nInstalled ${rV} v${W} at ${S.prefix}`),ve.error(n.message),process.exit(1)}ve.log(`\nUpdated ${rV} to v${W}.`),X?ve.log(`Runtime dependencies were resolved alongside the bundle.`):ve.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},aV=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1146
|
+
`))}var QB=__esmMin(()=>{Vl(),Dh(),GM(),Hs(),qB(),YB(),qM()});function describeRateLimitHeaders(n){if(!n)return`no headers captured`;let S=[];return n.forEach((n,C)=>{(/^retry-after$/i.test(C)||/ratelimit/i.test(C))&&S.push(`${C}: ${n}`)}),S.length>0?S.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(n){let S=n?.get(`retry-after`);if(!S)return null;let C=Number.parseInt(S.trim(),10);return!Number.isFinite(C)||C<0?null:C*1e3}async function packumentExists(n,S){let C=n.endsWith(`/`)?n.slice(0,-1):n;try{let n=await fetch(`${C}/${S.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return n.status===404?!1:n.ok?!0:null}catch{return null}}function actionForState(n){switch(n){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(n){return new Promise(S=>setTimeout(S,n))}async function requestWaitingOutRateLimit(n,S,C,N,F={}){let I=F.sleep??defaultSleep,H=F.maxRateLimitWaitMs??3e5,W=F.rateLimitBaseDelayMs??2e3,q=F.gate;q&&await q.wait();let Y=await n(S,C,N),X=0;for(let Z=0;Y.status===429&&X<H;Z++){let te=retryAfterMs(Y.headers),ne=Math.min(te??W*2**Z,$B),re=Math.min(ne,H-X);F.onRateLimit?.({url:C,headers:describeRateLimitHeaders(Y.headers),waitMs:re,fromRetryAfter:te!==null}),q?.penalize(re),await(q?q.wait():I(re)),X+=re,Y=await n(S,C,N)}return Y}async function probeTrustState(n,S,C,N={}){let F=C.registryOverride??registryFor(S.name,C.npmrc)??qf,I=trustUrl(F,S.name),H={repository:C.repository,workflow:C.workflow},W=N.sleep??defaultSleep,q=await requestWaitingOutRateLimit(n,`GET`,I,void 0,N),Y=classifyTrustList(q.status,q.json,H);return Y===`auth-required`&&N.retryOn401!==!1&&(await W(N.retryDelayMs??400),q=await n(`GET`,I),Y=classifyTrustList(q.status,q.json,H)),(Y===`untrusted`||Y===`auth-required`)&&await(N.exists??packumentExists)(F,S.name)===!1&&(Y=`unpublished`),{ws:S,registry:F,url:I,state:Y,httpStatus:q.status,action:actionForState(Y)}}async function probeAllTrustStates(n,S,C,N,F={}){if(S.length===0)return[];let I=S.length,H=0,report=n=>(H++,F.onProgress?.(H,I,n),n);return[report(await probeTrustState(n,S[0],N,F)),...await mapWithConcurrency(S.slice(1),Math.max(1,C),async S=>report(await probeTrustState(n,S,N,F)))]}async function mapWithConcurrency(n,S,C){let N=Array.from({length:n.length}),F=0,I=Array.from({length:Math.min(Math.max(1,S),n.length)},async()=>{for(;;){let S=F++;if(S>=n.length)return;N[S]=await C(n[S])}});return await Promise.all(I),N}var $B,RateLimitGate,eV=__esmMin(()=>{ep(),YB(),$B=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(n={}){this.now=n.now??(()=>Date.now()),this.sleeper=n.sleep??defaultSleep}async wait(){let n=this.until-this.now();n>0&&await this.sleeper(n)}penalize(n){this.until=Math.max(this.until,this.now()+n)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(n,S,C){let N=C.failed??0;if(C.asJson)process.stdout.write(`${JSON.stringify({ok:N===0,dryRun:C.dryRun,root:C.root,sources:C.sources,discovered:C.discovered,total:S.length,published:n.filter(n=>n.result===`published`||n.result===`published+trusted`).length,trusted:n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length,alreadyDone:n.filter(n=>n.result===`already-done`).length,failed:N,results:n},null,2)}\n`);else{let S=C.dryRun?N>0?`Dry-run INCOMPLETE — nothing changed, but ${N} 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: ${n.filter(n=>n.result.includes(`published`)).length} published, ${n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length} trusted, ${n.filter(n=>n.result===`already-done`).length} already done, ${N} failed.`;process.stdout.write(`\n${S}\n`)}process.exit(+(N>0))}function statusCell(n){switch(n.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${n.httpStatus})`}}async function ensureAuthenticated(n){let{npmrc:S,registry:C,cwd:N,nonInteractive:F,dryRun:I,otp:H,log:W}=n;if(hasAnyCredential(S))try{let n=await whoami(C,S);if(n.username)return n.username}catch{}if(I){W(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(F)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");W(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:C,otp:H,cwd:N})).username}catch(n){throw n instanceof LoginError?Error(n.message):n}}async function buildIfPresent(n,S){if(typeof(n.manifest.scripts??{}).build!=`string`)return;let C=detectPackageManager(),N=[`run`,`build`];S(` $ ${C} ${N.join(` `)}`);let{code:F}=await spawnToCompletion(C,N,{completion:`return`,cwd:n.location,env:{...process.env}});if(F!==0)throw Error(`build exited with code ${F}`)}function describePublishFailure(n){switch(n.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${n.diag.reason})`;case`publish-unconfirmed`:return`npm ${n.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${n.putStatus}) but ${n.name}@${n.version} did not resolve on ${n.registry} after ${n.readback.attempts} probe(s) over ${(n.readback.elapsedMs/1e3).toFixed(1)}s`;case`error`:return`HTTP ${n.status} ${n.statusText}`;default:return`unknown`}}var tV,nV,rV=__esmMin(()=>{ye(),Dh(),ep(),GM(),aI(),IB(),EB(),RB(),ZB(),UB(),qF(),_P(),QB(),YB(),eV(),tV=4,nV={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:n=>n.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 ${qf}).`,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:tV}).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 n=>{let S=process.cwd(),C=n[`dry-run`]===!0,N=n.json===!0,F=n.yes===!0,log=(n=``)=>{N?process.stderr.write(`${n}\n`):writeAroundPrompt(`${n}\n`)},I=await loadNpmrc(S),H=n.registry??process.env.npm_config_registry??I.registry??qf,W;try{W=await ensureAuthenticated({npmrc:I,registry:H,cwd:S,nonInteractive:F,dryRun:C,otp:n.otp,log})}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:S})}\n`):ve.error(S),process.exit(1)}I=await loadNpmrc(S),W&&log(`gjsify onboard: authenticated as ${W}`);let q=n.repository;if(!q){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(q=parseRepoFromGitRemote(n.stdout)??void 0)}if(!q||!validateRepository(q)){let n=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:n})}\n`):ve.error(n),process.exit(1)}let Y=normalizeWorkflowFile(n.workflow),X=n.environment,Z=resolveRepoRoot(S),te,ne;try{n.packages&&n.packages.length>0&&assertEveryPatternMatches(Z,n.packages);let C=collectOnboardPackages(Z,S,{patterns:n.packages});te=C.packages,ne=describeSources(C.sources)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:S})}\n`):ve.error(S),process.exit(1)}let re=filterWorkspaces(te,{noPrivate:!0,include:n.include,exclude:n.exclude}).filter(n=>n.name);if(re.length===0){let n=`gjsify onboard: no publishable packages found under ${Z} (discovered ${te.length}${ne?` — ${ne}`:``}). `+(te.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 N?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:n})}\n`):ve.error(n),process.exit(1)}try{assertRepositoryAgreement(re,q)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:S})}\n`):ve.error(S),process.exit(1)}log(`gjsify onboard: root=${Z} | ${ne}`),log(`gjsify onboard: ${re.length} of ${te.length} package(s) selected | repo=${q} workflow=${Y}`),C&&log(`(dry-run — nothing will be published or configured)`),log();let ie=new OtpProvider(n.otp,F?async()=>``:void 0,{registry:H}),ae=createTrustRequester({npmrc:I,otpProvider:ie}),oe=new RateLimitGate,se=!1,onRateLimit=n=>{se||(se=!0,log(` npm rate limit hit. ${n.headers}. Waiting ${Math.round(n.waitMs/1e3)}s (${n.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:oe,onRateLimit},ce=Math.max(1,Math.min(50,Math.ceil(re.length/10))),le=0,ue=0,de=0;re.length>ce&&log(`Reading trust state for ${re.length} package(s)…`);let fe=await probeAllTrustStates(ae,re,Math.max(1,n.concurrency),{registryOverride:n.registry,npmrc:I,repository:q,workflow:Y},{...Q,onProgress:(n,S,C)=>{if(C.action===`trust`||C.action===`publish-and-trust`?le++:C.action===`skip`?ue++:de++,n%ce!==0&&n!==S||S<=ce)return;let N=[`${le} to do`,`${ue} already done`];de>0&&N.push(`${de} unreadable`),log(` read ${n}/${S} — ${N.join(`, `)}`)}}),pe=fe.filter(n=>n.action===`publish-and-trust`),me=fe.filter(n=>n.action===`trust`),he=fe.filter(n=>n.action===`skip`),ge=fe.filter(n=>n.action===`blocked`);for(let S of fe)S.action===`skip`&&n.verbose!==!0||log(` ${statusCell(S)} ${S.ws.name}`);!n.verbose&&he.length>0&&log(` (${he.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${he.length} already done, ${pe.length} to publish+trust, ${me.length} to trust, ${ge.length} unreadable.`);let _e=ge.filter(n=>n.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 ye=[];if(C){for(let n of fe)ye.push({name:n.ws.name,result:n.action===`skip`?`already-done`:n.action===`blocked`?`failed`:`skipped-dry-run`,detail:n.action===`publish-and-trust`?`would publish + trust`:n.action===`trust`?`would trust`:n.action===`blocked`?`state HTTP ${n.httpStatus}`:void 0});finish(ye,fe,{asJson:N,dryRun:C,failed:ge.length,root:Z,sources:ne,discovered:te.length});return}let be=githubTrustBody({repository:q,workflow:Y,environment:X}),xe=Math.max(1,n[`write-concurrency`]),Se=pe.length+me.length,Ce=Array.from({length:fe.length}),we=0,Te=0,Ee=0,configureTrust=async(n,S,C)=>{let N=await requestWaitingOutRateLimit(ae,`POST`,n.url,be,Q),F=`${++Te}/${Se}`;N.status>=200&&N.status<300?(log(` [${F}] trusted ${n.ws.name}`),Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}):N.status===409?Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}:N.status===404?(log(` [${F}] ${n.ws.name}: published but not yet trust-configurable (re-run onboard)`),Ce[S]={name:n.ws.name,result:C?`published`:`failed`,detail:`trust config deferred (404)`},C||we++):(log(` [${F}] trust failed (HTTP ${N.status}) — ${n.ws.name}`),Ce[S]={name:n.ws.name,result:`failed`,detail:`trust HTTP ${N.status}`},N.status===429&&Ee++,we++)},De=[];for(let S=0;S<fe.length;S++){let C=fe[S];if(C.action===`skip`){Ce[S]={name:C.ws.name,result:`already-done`};continue}if(C.action===`blocked`){log(`→ ${C.ws.name}: cannot read trust state (HTTP ${C.httpStatus}) — skipped`),Ce[S]={name:C.ws.name,result:`failed`,detail:`state HTTP ${C.httpStatus}`},we++;continue}if(C.action===`trust`){De.push({p:C,i:S});continue}log(`→ ${C.ws.name}: building + publishing…`);try{n.build!==!1&&await buildIfPresent(C.ws,log)}catch(n){let N=n instanceof Error?n.message:String(n);log(` build failed: ${N}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`build: ${N}`},we++;continue}let N=await publishWorkspace({wsDir:C.ws.location,tag:`latest`,access:n.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:C.registry,verbose:!1,json:!1,otpProvider:ie,seedOtpFirst:!1});if(!N.ok){let n=describePublishFailure(N);log(` publish failed: ${n}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`publish: ${n}`},we++;continue}log(` published ${N.name}@${`version`in N?N.version:``}`),await configureTrust(C,S,N.action!==`skipped-untrusted-new`)}De.length>0&&(De.length>1&&log(`→ configuring ${De.length} Trusted Publisher(s), ${xe} at a time…`),await mapWithConcurrency(De,xe,async({p:n,i:S})=>configureTrust(n,S,!1)));for(let n of Ce)n&&ye.push(n);Ee>0&&(log(),log(`${Ee} 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 ${xe}) provokes the limit less.`)),finish(ye,fe,{asJson:N,dryRun:C,failed:we,root:Z,sources:ne,discovered:te.length})}}});function pathFor(n){return n===`win32`?Cs:xs}function isInside$1(n,S,C){let N=pathFor(C);if(!N.isAbsolute(n)||!N.isAbsolute(S))return!1;let F=S.endsWith(N.sep)?S:S+N.sep;return n===S||n.startsWith(F)}function classifyInstall(n){let S=n.env??process.env,C=n.platform??process.platform,N=pathFor(C),F=N.resolve(n.selfDir);if(S.FLATPAK_ID||isInside$1(F,aV,C)){let n=S.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:S.FLATPAK_ID?`FLATPAK_ID=${S.FLATPAK_ID}`:`running from ${aV}`,updateWith:`flatpak update ${n}`,managedElsewhere:!0}}return isInside$1(F,N.resolve(n.xdgPrefix),C)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${n.xdgPrefix}`,managedElsewhere:!1}:C!==`win32`&&iV.some(n=>isInside$1(F,n,C))?{kind:`system-package`,evidence:`running from the system prefix ${F}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:F.split(N.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${F}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${F}, which matches no known install layout`,managedElsewhere:!1}}var iV,aV,oV=__esmMin(()=>{Hs(),iV=[`/usr/`,`/opt/`,`/snap/`],aV=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(n){let S=n.platform??process.platform,C=S===`win32`?Cs:xs,norm=n=>S===`win32`?C.resolve(n).toLowerCase():C.resolve(n);if(n.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${n.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${n.binDir}`};if(norm(C.dirname(n.resolvedBin))===norm(n.binDir))return{ok:!0};let N=n.runningVersion?` (v${n.runningVersion})`:``;return{ok:!1,message:`BUT \`${n.binName}\` on PATH resolves to\n ${n.resolvedBin}${N}\nwhich is NOT the install that was just updated, so the next \`${n.binName}\`\nyou run will not be v${n.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${sV}\`)\n or put ${n.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 \`${n.binName} --version\`.`}}function readSelfDir(){let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n)return Ps(Os(n));let S=fileURLToPath(import.meta.url),C=Ps(Os(S));for(let n=0;n<8&&C!==Ps(C);n++){if(existsSync(js(C,`package.json`)))return C;C=Ps(C)}return Ps(Os(S))}function readCurrentVersion(){try{let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n){let S=JSON.parse(readFileSync(n,`utf-8`));return S.name===sV&&typeof S.version==`string`?S.version:null}let S=Ps(Os(fileURLToPath(import.meta.url)));for(let n=0;n<8&&S!==Ps(S);n++){let n=js(S,`package.json`);if(existsSync(n)){let S=JSON.parse(readFileSync(n,`utf-8`));if(S.name===sV&&typeof S.version==`string`)return S.version}S=Ps(S)}}catch{}return null}function resolveTag(n,S){let C=n[`dist-tags`]??{};return C[S]?C[S]:n.versions&&typeof n.versions==`object`&&n.versions[S]?S:null}var sV,cV,lV,uV=__esmMin(()=>{ye(),Vl(),Hs(),gn(),ep(),yF(),oV(),CF(),lF(),tB(),sV=`@gjsify/cli`,cV={command:`self-update`,description:`Update the installed ${sV} to the latest release (or pinned --tag).`,builder:n=>n.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async n=>{let S=defaultGlobalLayout(),C=js(js(S.prefix,`node_modules`,sV),`package.json`),N=readCurrentVersion(),F=existsSync(C);ve.log(`Current ${sV}: v${N??`(unknown)`}`);let I=classifyInstall({selfDir:readSelfDir(),xdgPrefix:S.prefix});if(I.managedElsewhere)return ve.error(`\ngjsify self-update: this gjsify is managed by something else — ${I.evidence}.\nUpdating it from here would write ${S.prefix} and leave you running two installs.\n\nUpdate with: ${I.updateWith}\n`),process.exit(1);F||ve.warn(`\nWarning: no @gjsify/cli install found under ${S.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`),ve.log(`Fetching dist-tags for ${sV}@${n.tag} ...`);let H;try{H=await fetchPackument(sV)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`Failed to fetch packument: ${S}`),process.exit(1)}let W=resolveTag(H,n.tag);if(!W)return ve.error(`Unknown dist-tag '${n.tag}' on ${sV}. Known tags: ${Object.keys(H[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ve.log(`Latest matching --tag ${n.tag}: v${W}`);let q=F&&!hasBundlerEngineInstalled(S.prefix),Y=q&&!n.skipDeps&&!n.check;if(N===W&&!n.force&&!Y){ve.log(`Already up to date (v${W}).`),q&&n.skipDeps&&ve.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)."),n.check||ve.log(`Run with --force to reinstall anyway.`);return}if(Y&&N===W&&!n.force&&ve.log(`@gjsify/cli is at v${W} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),n.check)return ve.log(N?`Update available: v${N} → v${W}`:`Install required: → v${W}`),process.exit(1);let X=!n.skipDeps,Z=X?` + runtime dependencies`:` (bundle only)`;ve.log(`Installing ${sV}@${W}${Z} ...`);let te=makeProgressReporter();try{await installPackages({prefix:S.prefix,specs:[`${sV}@${W}`],verbose:!1,skipDeps:!X,progress:te})}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`self-update: install failed — ${S}`),ve.error("Re-run `gjsify self-update` to retry."),process.exit(1)}X&&await installGjsEnginePackages(S.prefix,W,{verbose:!1}),n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let ne=linkGlobalBins([sV],S);if(ne.length===0)ve.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let n of ne)ve.log(` • ${n.link} → ${n.target}`);if(globalLayoutIsDefault()){let n=verifyPathResolution({binName:lV,binDir:S.binDir,resolvedBin:resolveBinOnPath(lV),runningVersion:N,targetVersion:W});if(!n.ok)return ve.error(`\nInstalled ${sV} v${W} at ${S.prefix}`),ve.error(n.message),process.exit(1)}ve.log(`\nUpdated ${sV} to v${W}.`),X?ve.log(`Runtime dependencies were resolved alongside the bundle.`):ve.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},lV=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1146
1147
|
/**
|
|
1147
1148
|
* gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
|
|
1148
1149
|
* on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
|
|
@@ -1667,22 +1668,22 @@ async function main() {
|
|
|
1667
1668
|
}
|
|
1668
1669
|
|
|
1669
1670
|
await main();
|
|
1670
|
-
`}function pickDefaultBinName(n,S){let C=n?.gjsify?.bin;if(C&&typeof C==`object`){let n=Object.keys(C)[0];if(n)return n}let N=n?.bin;if(N&&typeof N==`object`){let n=Object.keys(N)[0];if(n)return n}return S.startsWith(`@`)?S.slice(S.indexOf(`/`)+1):S}var
|
|
1671
|
-
`).find(n=>/^exec (?:gjs -m )?'/.test(n));if(!C)continue;let I=C.match(/'([^']+)'/);if(!I)continue;let H=I[1];if(isInside(S,H)){N.push(F);for(let n of[`.cmd`,`.ps1`])existsSync(F+n)&&N.push(F+n)}}catch(n){C&&ve.warn(` ? could not inspect ${F}: ${n.message}`)}}return N}var
|
|
1672
|
-
No packages removed.`),process.exit(1))}}});function handleInit({cwd:n,force:S}){let writeOne=(C,N)=>{let F=Os(n,C);if(existsSync(F)&&!S){ve.log(`[gjsify format] ${C} exists at ${F} — pass --force to overwrite.`);return}writeFileSync(F,N,`utf-8`),ve.log(`[gjsify format] wrote ${F}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ve.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var
|
|
1673
|
-
[gjsify upgrade --align] --dry-run: no files changed.`);return}let F=applyToFiles(N,S.exact);ve.log(`\n✏️ updated ${N.length} dep(s) across ${F} package.json file(s).`)}async function resolveCandidateGroups(n,S,C,N){let F=[],I=0;async function worker(){for(;;){let H=I++;if(H>=n.length)return;let W=n[H];try{let n=(await fetchPackument(W.name,{npmrc:S}))[`dist-tags`]?.latest;if(!n){C&&ve.warn(` ${W.name}: no dist-tags.latest, skipping`);continue}let I=W.highestVersion;if(!I){C&&ve.warn(` ${W.name}: unable to parse any current range`);continue}let H=classifyDiff(I,n);if(H===`none`||N===`minor`&&H===`major`||N===`patch`&&(H===`major`||H===`minor`))continue;F.push({...W,latestVersion:n,diff:H})}catch(n){C&&ve.warn(` ${W.name}: fetch failed (${n.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),F.sort((n,S)=>n.name.localeCompare(S.name)),F}function classifyDiff(n,S){let C=parse(n),N=parse(S);return!C||!N?`none`:C.major===N.major?C.minor===N.minor?C.patch===N.patch?(C.prerelease??[]).join(`.`)===(N.prerelease??[]).join(`.`)?`none`:`prerelease`:N.patch>C.patch?`patch`:`none`:N.minor>C.minor?`minor`:`none`:N.major>C.major?`major`:`none`}function colorForDiff(n){switch(n){case`major`:return
|
|
1674
|
-
Select upgrades: comma- or space-separated indices, `+
|
|
1671
|
+
`}function pickDefaultBinName(n,S){let C=n?.gjsify?.bin;if(C&&typeof C==`object`){let n=Object.keys(C)[0];if(n)return n}let N=n?.bin;if(N&&typeof N==`object`){let n=Object.keys(N)[0];if(n)return n}return S.startsWith(`@`)?S.slice(S.indexOf(`/`)+1):S}var dV,fV,pV=__esmMin(()=>{ye(),Vl(),Hs(),dV=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,fV={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:n=>n.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:n=>{let S=Os(process.cwd(),n.output);if(existsSync(S)&&!n.force)return ve.error(`${n.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let C=Os(process.cwd(),`package.json`),N=null;if(existsSync(C))try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{}let F=n.target??N?.name;if(!F)return ve.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let I=n[`bin-name`]??pickDefaultBinName(N,F),H=n[`bootstrap-url`]??dV;writeFileSync(S,loadInstallerTemplate().replace(/const DEFAULT_TARGET = '[^']+';/,`const DEFAULT_TARGET = ${JSON.stringify(F)};`).replace(/const DEFAULT_BIN_NAME = '[^']+';/,`const DEFAULT_BIN_NAME = ${JSON.stringify(I)};`).replace(/const DEFAULT_BOOTSTRAP_URL =\s*'[^']+';/,`const DEFAULT_BOOTSTRAP_URL = ${JSON.stringify(H)};`),{mode:493}),ve.log(`Wrote ${n.output} (target=${F}, bin=${I}).`),ve.log(``),ve.log(`Install one-liner for your README:`),ve.log(` curl -fsSL https://github.com/<you>/<repo>/raw/main/${n.output} -o /tmp/i.mjs \\`),ve.log(` && gjs -m /tmp/i.mjs && rm /tmp/i.mjs`)}}}),mV,hV=__esmMin(()=>{ye(),Vl(),$P(),CF(),lF(),tB(),mV={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:n=>n.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 n=>{let S=n.global?defaultGlobalLayout():null,C=S?S.prefix:process.cwd();if(!existsSync(`${C}/node_modules`)){ve.log(`gjsify prune: nothing installed at ${C}`);return}let N=resolveHostPlatform({env:{...n.os?{npm_config_os:n.os}:{},...n.cpu?{npm_config_cpu:n.cpu}:{},...n.libc?{npm_config_libc:n.libc}:{}}}),F=await acquireInstallLock(C,{}),I;try{I=executePrune(planPrune({prefix:C,target:N}),{dryRun:n.dryRun})}finally{F.release()}if(ve.log(formatPruneReport(I,{dryRun:n.dryRun,verbose:n.verbose})),I.failed.length>0)return process.exit(1)}}});function isInside(n,S){let C=Ms(n,S);return C===``?!0:C!==`..`&&!C.startsWith(`..${zs}`)&&!As(C)}function findBinShimsForPackage(n,S,C){if(!existsSync(n))return[];let N=[],F;try{F=readdirSync(n)}catch{return[]}for(let I of F){let F=js(n,I);try{if(!statSync(F).isFile())continue;let n=readFileSync(F,`utf-8`);if(!n.startsWith(`#!/bin/sh`))continue;let C=n.split(`
|
|
1672
|
+
`).find(n=>/^exec (?:gjs -m )?'/.test(n));if(!C)continue;let I=C.match(/'([^']+)'/);if(!I)continue;let H=I[1];if(isInside(S,H)){N.push(F);for(let n of[`.cmd`,`.ps1`])existsSync(F+n)&&N.push(F+n)}}catch(n){C&&ve.warn(` ? could not inspect ${F}: ${n.message}`)}}return N}var gV,_V=__esmMin(()=>{ye(),Vl(),Hs(),CF(),gV={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:n=>n.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:n=>{if(!n.global)return ve.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let S=defaultGlobalLayout(),C=n[`dry-run`]??!1,N=n.verbose??!1,F=`gjsify uninstall${C?` (dry-run)`:``} --global`;ve.log(`${F} ← ${S.prefix}`),ve.log(`${` `.repeat(F.length)} bins ← ${S.binDir}`);let I=!1;for(let F of n.packages){let n=specToPackageName(F),H=js(S.prefix,`node_modules`,n);if(!existsSync(H)){ve.warn(` ✗ ${n} — not installed at ${H}`);continue}let W=findBinShimsForPackage(S.binDir,H,N);if(C){ve.log(` • would remove ${H}`);for(let n of W)ve.log(` • would remove ${n}`)}else{rmSync(H,{recursive:!0,force:!0}),ve.log(` • removed ${H}`);for(let n of W)unlinkSync(n),ve.log(` • removed ${n}`)}I=!0}I||(ve.error(`
|
|
1673
|
+
No packages removed.`),process.exit(1))}}});function handleInit({cwd:n,force:S}){let writeOne=(C,N)=>{let F=Os(n,C);if(existsSync(F)&&!S){ve.log(`[gjsify format] ${C} exists at ${F} — pass --force to overwrite.`);return}writeFileSync(F,N,`utf-8`),ve.log(`[gjsify format] wrote ${F}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ve.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var vV,yV=__esmMin(()=>{ye(),Vl(),Hs(),YI(),vV={command:`format [paths..]`,description:`Format JS/TS source files via oxfmt (CSS/JSON formatting is not supported).`,builder:n=>n.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 n=>{let S=process.cwd();if(n.init){handleInit({cwd:S,force:n.force??!1});return}let C=n.paths?.length?n.paths:[`.`],N=[];n.check?N.push(`--check`):n.write===!1?N.push(`--list-different`):N.push(`--write`);let F=n.configPath??findOxfmtConfig(S)??void 0;F&&N.push(`--config`,Os(F)),N.push(...C);try{setOxcExitCode(await runOxfmt(N,{cwd:S,verbose:n.verbose}))}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}}),bV,xV=__esmMin(()=>{Hs(),YI(),bV={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:n=>n.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 n=>{let S=process.cwd(),C=n.paths?.length?n.paths:[`.`],N=[];n.fix&&N.push(`--fix`);let F=n.configPath??findOxlintConfig(S)??void 0;F&&N.push(`--config`,Os(F)),N.push(...C);try{setOxcExitCode(await runOxlint(N,{cwd:S,verbose:n.verbose}))}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}}),SV,CV=__esmMin(()=>{Hs(),YI(),SV={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:n=>n.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 n=>{let S=process.cwd(),C=n.paths?.length?n.paths:[`.`],N=n.verbose??!1,F=n.write!==!1;try{let I=[F?`--write`:`--list-different`],H=n.configPath??findOxfmtConfig(S)??void 0;H&&I.push(`--config`,Os(H)),I.push(...C);let W=await runOxfmt(I,{cwd:S,verbose:N}),q=[];F&&q.push(`--fix`);let Y=n.configPath??findOxlintConfig(S)??void 0;Y&&q.push(`--config`,Os(Y)),q.push(...C);let X=await runOxlint(q,{cwd:S,verbose:N});setOxcExitCode(W||X)}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}});function createInterface(n,S){return typeof n==`object`&&n&&!(`read`in n&&typeof n.read==`function`)?new Interface(n):new Interface({input:n,output:S})}var Interface,wV=__esmMin(()=>{Ml(),Interface=class extends Interface$1{question(n,S){return new Promise(S=>{super.question(n,S)})}}});function semverGt(n,S){try{return compare(n,S)===1}catch{return!1}}function groupByDependency(n){let S=new Map;for(let C of n){let n=S.get(C.name);n||(n={name:C.name,occurrences:[],declaredRanges:new Set,dominantRange:C.currentRange,highestVersion:C.currentVersion},S.set(C.name,n)),n.occurrences.push(C),n.declaredRanges.add(C.currentRange),C.currentVersion&&(!n.highestVersion||semverGt(C.currentVersion,n.highestVersion))&&(n.highestVersion=C.currentVersion)}for(let n of S.values()){let S=new Map;for(let C of n.occurrences)S.set(C.currentRange,(S.get(C.currentRange)??0)+1);let C=n.occurrences[0].currentRange,N=-1,F=null;for(let[n,I]of S.entries()){let S=parse(n.replace(/^[\^~>=<]+/,``))?.version??null;(I>N||I===N&&S&&F&&semverGt(S,F)||I===N&&n<C)&&(C=n,N=I,F=S)}n.dominantRange=C}return[...S.values()].sort((n,S)=>n.name.localeCompare(S.name))}function isInconsistent(n){return n.declaredRanges.size>1}function findInconsistencies(n){return n.filter(isInconsistent)}var TV=__esmMin(()=>{RP()});function discoverContext(n){let S=findWorkspaceRoot(n);if(S)return{root:S,workspaces:discoverWorkspaces(S,{includeRoot:!0}),isMonorepo:!0};let C=js(n,`package.json`);if(!existsSync(C))throw Error(`[gjsify upgrade] no package.json at ${C}`);let N=JSON.parse(readFileSync(C,`utf-8`));return{root:n,workspaces:[{name:N.name??`<root>`,location:n,relativeLocation:`.`,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(n,S,C){let N=S?.split(`,`).map(n=>n.trim()).filter(Boolean),F=C?.split(`,`).map(n=>n.trim()).filter(Boolean);return(!N||N.length===0)&&(!F||F.length===0)?n:filterWorkspaces(n,{include:N,exclude:F})}function parseFilterList(n){return n?n.split(`,`).map(n=>n.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(n,S){let C=[];for(let N of n)for(let n of collectFromWorkspace(N,S))C.push(n);return C}function collectFromWorkspace(n,S){let C=[],N=n.manifest;for(let F of DV){let I=N[F];if(!(!I||typeof I!=`object`))for(let[N,H]of Object.entries(I)){if(typeof H!=`string`||S.length&&!S.some(n=>N.toLowerCase().includes(n))||H.startsWith(`workspace:`)||H.startsWith(`file:`)||H.startsWith(`link:`)||H.startsWith(`git+`)||H.startsWith(`git:`)||H.startsWith(`http:`)||H.startsWith(`https:`)||H.startsWith(`npm:`)||H.startsWith(`portal:`))continue;let{prefix:I,version:W}=splitRange(H);C.push({workspace:n.name,workspaceLocation:n.location,name:N,field:F,currentRange:H,currentVersion:W,prefix:I})}}return C}function splitRange(n){let S=n.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!S)return{prefix:``,version:null};let C=S[1]??``,N=S[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:C,version:(N?parse(N):null)?.version??null}}function reportInexactRanges(n){let S=n.map(n=>({name:n.name,loose:n.occurrences.filter(n=>n.prefix!==``)})).filter(n=>n.loose.length>0);if(S.length===0)return 0;let C=S.reduce((n,S)=>n+S.loose.length,0);ve.error(`gjsify upgrade --check --exact: FAIL. ${C} declaration(s) across ${S.length} dep(s) carry a range operator:\n`);for(let n of S){let S=new Map;for(let C of n.loose){let n=S.get(C.currentRange)??[];n.push(C.workspace),S.set(C.currentRange,n)}ve.error(` ${OV.bold}${n.name}${OV.reset}`);for(let[n,C]of S.entries()){let S=C.length>6?`${C.slice(0,6).join(`, `)} … +${C.length-6}`:C.join(`, `);ve.error(` ${n.padEnd(16)} — ${S}`)}}return C}function runCheckMode(n,S=!1){let C=S?reportInexactRanges(n):0,N=findInconsistencies(n);if(N.length===0&&C>0)return ve.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ve.log(`gjsify upgrade --check: OK. ${n.length} dep(s) consistently declared across workspaces`+(S?`, every declaration pinned exactly.`:`.`));return}ve.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let n of N){let S=new Map;for(let C of n.occurrences){let n=S.get(C.currentRange)??[];n.push(C.workspace),S.set(C.currentRange,n)}ve.error(` ${OV.bold}${n.name}${OV.reset}`);for(let[n,C]of S.entries())ve.error(` ${n.padEnd(16)} — ${C.join(`, `)}`)}ve.error("\nFix: run `gjsify upgrade --align` (offline; aligns each dep to its highest declared range)."),process.exit(1)}function runAlignMode(n,S){let C=findInconsistencies(n);if(C.length===0){ve.log(`gjsify upgrade --align: nothing to do. ${n.length} dep(s) already consistent.`);return}let N=[];for(let n of C){if(!n.highestVersion)continue;let S=n.occurrences.find(S=>S.currentRange===n.dominantRange)?.prefix||`^`;N.push({...n,latestVersion:n.highestVersion,diff:`none`,occurrences:n.occurrences.map(n=>({...n,prefix:S}))})}if(N.length===0){ve.log(`gjsify upgrade --align: inconsistencies present but no parseable target version. No-op.`);return}ve.log(`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let n of N){let C=n.occurrences[0]?.prefix??`^`;ve.log(` ${n.name.padEnd(28)} ranges: ${[...n.declaredRanges].join(`, `)} → ${targetRange(C,n.latestVersion,S.exact??!1)}`)}if(S.dryRun){ve.log(`
|
|
1674
|
+
[gjsify upgrade --align] --dry-run: no files changed.`);return}let F=applyToFiles(N,S.exact);ve.log(`\n✏️ updated ${N.length} dep(s) across ${F} package.json file(s).`)}async function resolveCandidateGroups(n,S,C,N){let F=[],I=0;async function worker(){for(;;){let H=I++;if(H>=n.length)return;let W=n[H];try{let n=(await fetchPackument(W.name,{npmrc:S}))[`dist-tags`]?.latest;if(!n){C&&ve.warn(` ${W.name}: no dist-tags.latest, skipping`);continue}let I=W.highestVersion;if(!I){C&&ve.warn(` ${W.name}: unable to parse any current range`);continue}let H=classifyDiff(I,n);if(H===`none`||N===`minor`&&H===`major`||N===`patch`&&(H===`major`||H===`minor`))continue;F.push({...W,latestVersion:n,diff:H})}catch(n){C&&ve.warn(` ${W.name}: fetch failed (${n.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),F.sort((n,S)=>n.name.localeCompare(S.name)),F}function classifyDiff(n,S){let C=parse(n),N=parse(S);return!C||!N?`none`:C.major===N.major?C.minor===N.minor?C.patch===N.patch?(C.prerelease??[]).join(`.`)===(N.prerelease??[]).join(`.`)?`none`:`prerelease`:N.patch>C.patch?`patch`:`none`:N.minor>C.minor?`minor`:`none`:N.major>C.major?`major`:`none`}function colorForDiff(n){switch(n){case`major`:return OV.red;case`minor`:return OV.yellow;case`patch`:return OV.green;case`prerelease`:return OV.cyan;default:return``}}function printTable(n){let S=Math.max(...n.map(n=>n.name.length),4),C=Math.max(...n.map(n=>`${n.occurrences.length}`.length+2),3),N=Math.max(...n.map(n=>declaredCellWidth(n)),7),F=Math.max(...n.map(n=>n.latestVersion.length),6),I=String(n.length).length+2,H=` `.repeat(I+2)+OV.bold+`name`.padEnd(S)+` `+`fan`.padEnd(C)+` `+`declared`.padEnd(N)+` `+`latest`.padEnd(F)+` kind`+OV.reset;ve.log(H),ve.log(` `.repeat(I+2)+OV.dim+`─`.repeat(S+C+N+F+16)+OV.reset);for(let H=0;H<n.length;H++){let W=n[H],q=`${H+1}.`.padEnd(I),Y=W.declaredRanges.size>1?`${OV.magenta}⚠ ${OV.reset}`:` `,X=colorForDiff(W.diff);ve.log(q+Y+W.name.padEnd(S)+` `+OV.dim+`${W.occurrences.length}`.padEnd(C)+OV.reset+` `+OV.dim+renderDeclaredCell(W).padEnd(N)+OV.reset+` `+X+W.latestVersion.padEnd(F)+OV.reset+` `+X+W.diff+OV.reset)}let W=n.filter(n=>n.declaredRanges.size>1).length;W>0&&ve.log(`\n${OV.magenta}⚠${OV.reset} ${W} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(n){return renderDeclaredCell(n).length}function renderDeclaredCell(n){if(n.declaredRanges.size===1)return[...n.declaredRanges][0];let S=[...n.declaredRanges].sort().join(`, `);return S.length<=32?S:S.slice(0,29)+`…`}function printChangePlan(n,S=!1){for(let C of n)for(let n of C.occurrences)ve.log(` ${n.workspace.padEnd(38)} ${C.name.padEnd(28)} ${n.currentRange.padEnd(12)} → ${targetRange(n.prefix,C.latestVersion,S)}`)}async function promptSelection(n){if(!process.stdin.isTTY)return ve.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let S=createInterface({input:process.stdin,output:process.stdout});try{ve.log(`
|
|
1675
|
+
Select upgrades: comma- or space-separated indices, `+OV.bold+`a`+OV.reset+` for all, ranges like `+OV.bold+`1-3`+OV.reset+`, or `+OV.bold+`ENTER`+OV.reset+` to skip:`);let C=(await S.question(`> `)).trim();if(!C)return[];if(C.toLowerCase()===`a`||C.toLowerCase()===`all`)return[...n];let N=new Set;for(let n of C.split(/[\s,]+/).filter(Boolean)){let S=n.match(/^(\d+)-(\d+)$/);if(S){let n=Number(S[1]),C=Number(S[2]);for(let S=Math.min(n,C);S<=Math.max(n,C);S++)N.add(S-1)}else/^\d+$/.test(n)&&N.add(Number(n)-1)}return[...N].filter(S=>S>=0&&S<n.length).map(S=>n[S])}finally{S.close()}}function targetRange(n,S,C){return C?S:`${n}${S}`}function applyToFiles(n,S=!1){let C=new Map;for(let S of n)for(let n of S.occurrences){let N=C.get(n.workspaceLocation)??[];N.push({...S,occurrences:[n]}),C.set(n.workspaceLocation,N)}let N=0;for(let[n,F]of C.entries()){let C=js(n,`package.json`),I=readFileSync(C,`utf-8`),H=JSON.parse(I),W=!1,q=[];for(let n of F){let C=n.occurrences[0],N=H[C.field];if(!N)continue;let F=targetRange(C.prefix,n.latestVersion,S);N[n.name]!==F&&(N[n.name]=F,W=!0,q.push(n.name))}if(W){let n=detectIndent(I);writeFileSync(C,keepUntouchedLines(I,JSON.stringify(H,null,n)+(I.endsWith(`
|
|
1675
1676
|
`)?`
|
|
1676
1677
|
`:``),q),`utf-8`),N++}}return N}function keepUntouchedLines(n,S,C){let N=n.split(`
|
|
1677
1678
|
`),F=S.split(`
|
|
1678
1679
|
`);return N.length===F.length?F.map((n,S)=>C.some(S=>n.includes(`"${S}"`))?n:N[S]).join(`
|
|
1679
|
-
`):S}function uniqueLocations(n){let S=new Set;for(let C of n)for(let n of C.occurrences)S.add(n.workspaceLocation);return[...S]}function detectIndent(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}async function loadNpmrcLight(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}};for(let C of[js(homedir(),`.npmrc`),js(n,`.npmrc`)])if(existsSync(C))try{let n=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...n,scopes:{...S.scopes,...n.scopes}}}catch{}return process.env.npm_config_registry&&(S.registry=process.env.npm_config_registry),S}var
|
|
1680
|
+
`):S}function uniqueLocations(n){let S=new Set;for(let C of n)for(let n of C.occurrences)S.add(n.workspaceLocation);return[...S]}function detectIndent(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}async function loadNpmrcLight(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}};for(let C of[js(homedir(),`.npmrc`),js(n,`.npmrc`)])if(existsSync(C))try{let n=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...n,scopes:{...S.scopes,...n.scopes}}}catch{}return process.env.npm_config_registry&&(S.registry=process.env.npm_config_registry),S}var EV,DV,OV,kV=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),wV(),RP(),ep(),GM(),qM(),TV(),EV={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:n=>n.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 consistency mode: find deps declared at multiple ranges across the workspace and align them to the highest. 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. Pair with `--filter` — a repository-wide exactness check fails on 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 n=>{let S=discoverContext(Os(n.cwd??process.cwd())),C=applyWorkspaceFilter(S.workspaces,n.workspace,n.excludeWorkspace);if(C.length===0){ve.log(`[gjsify upgrade] no matching workspaces.`);return}let N=collectAllDeclarations(C,parseFilterList(n.filter));if(N.length===0){ve.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let F=groupByDependency(N);if(n.check)return runCheckMode(F,n.exact);if(n.align)return runAlignMode(F,n);let I=await loadNpmrcLight(S.root),H=n.latest?`latest`:n.minor?`minor`:n.patch?`patch`:`interactive`;ve.log(`[gjsify upgrade] checking ${F.length} unique deps across ${C.length} workspace(s) against ${I.registry}…`);let W=await resolveCandidateGroups(F,I,n.verbose??!1,H);if(W.length===0){ve.log(`✅ all dependencies are up to date`);let n=findInconsistencies(F);n.length>0&&ve.log(`\n⚠ ${n.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(W);let q;if(H===`interactive`&&!n.yes?q=await promptSelection(W):(n.yes&&H===`interactive`&&ve.log(`[gjsify upgrade] -y / --yes: selecting all`),q=W),q.length===0){ve.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(n.dryRun){let S=uniqueLocations(q).length;ve.log(`[gjsify upgrade] --dry-run: would update ${q.length} deps across ${S} package.json file(s).`),printChangePlan(q,n.exact);return}let Y=applyToFiles(q,n.exact);ve.log(`✏️ updated ${q.length} dep(s) across ${Y} package.json file(s). Run \`gjsify install\` to apply.`)}},DV=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],OV={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 generateBarrels(n){let S=n.singleQuotes?`'`:`"`,C=n.noSemicolon?``:`;`,N=n.extension===`none`?``:`.${n.extension}`,F=0;for(let I of n.paths){let H=Os(n.baseDir,I),W=Fs(H)===`types`,q;try{q=(await readdir$1(H,{withFileTypes:!0})).filter(n=>n.isFile()).filter(n=>jV.test(n.name)).filter(n=>n.name!==`index.ts`).filter(S=>!n.exclude.some(n=>n.test(S.name))).sort((n,S)=>n.name.localeCompare(S.name))}catch(S){n.verbose&&ve.error(`[gjsify barrels] skip ${H}: ${S.message}`);continue}let Y=q.map(n=>{let F=Fs(n.name,Is(n.name));return`${W?`export type *`:`export *`} from ${S}./${F}${N}${S}${C}`}),X=Y.length?`${Y.join(`
|
|
1680
1681
|
`)}\n`:`export {};
|
|
1681
|
-
`,Z=`${n.header}\n\n${X}`,te=js(H,`index.ts`);if(await readFile$1(te,`utf-8`).catch(()=>``)===Z){n.verbose&&ve.log(`[gjsify barrels] up-to-date: ${te}`);continue}n.check?(ve.error(`[gjsify barrels] drift: ${te}`),F++):(await writeFile$1(te,Z,`utf-8`),n.verbose&&ve.log(`[gjsify barrels] wrote: ${te}`))}return F}var
|
|
1682
|
-
`).map(n=>n.trim()).filter(Boolean)}var
|
|
1682
|
+
`,Z=`${n.header}\n\n${X}`,te=js(H,`index.ts`);if(await readFile$1(te,`utf-8`).catch(()=>``)===Z){n.verbose&&ve.log(`[gjsify barrels] up-to-date: ${te}`);continue}n.check?(ve.error(`[gjsify barrels] drift: ${te}`),F++):(await writeFile$1(te,Z,`utf-8`),n.verbose&&ve.log(`[gjsify barrels] wrote: ${te}`))}return F}var AV,jV,MV=__esmMin(()=>{ye(),Cl(),Hs(),AV=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],jV=/\.(ts|tsx|mts|cts)$/}),NV,PV=__esmMin(()=>{ye(),MV(),NV={command:`barrels [paths..]`,description:"Regenerate `index.ts` barrel files for the given directories. Drop-in replacement for `barrelsby`.",builder:n=>n.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 n=>{let S=Array.from(new Set((n.paths??[]).filter(Boolean)));if(S.length===0){ve.error(`[gjsify barrels] no paths provided. Pass directories as positional arguments or via --paths.`),process.exitCode=1;return}let C=n.exclude?.length?n.exclude:[...AV],N=await generateBarrels({paths:S,extension:n.ext??`none`,baseDir:n.baseDir??process.cwd(),exclude:C.map(n=>new RegExp(n)),header:n.header??"// Auto-generated by `gjsify barrels` — do not edit by hand.",noSemicolon:n.semicolon===!1||n.semicolon===void 0,singleQuotes:n.singleQuotes!==!1,check:n.check??!1,verbose:n.verbose??!1});n.check&&N>0&&(ve.error(`[gjsify barrels] ${N} barrel file(s) drifted. Run without --check to fix.`),process.exitCode=1)}}}),FV,IV=__esmMin(()=>{ye(),gs(),Hs(),gn(),gN(),dN(),Vl(),$z(),xP(),qM(),_P(),FV={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:n=>n.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 n=>{let S=(n._??[]).slice(1).map(String),C=n.tscArgs??[],N=S.length>0?S:C,F=process.cwd(),I=[pathToFileURL(`${findWorkspaceRoot(F)??F}/__gjsify_tsc__.js`).href,import.meta.url],H;for(let n of I)try{H=createRequire(n).resolve(`@gjsify/tsc/bundle`);break}catch{}let W;for(let n of I)try{W=js(Ps(createRequire(n).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!H&&!W)return ve.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ve.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let q=buildNativeEnv(detectNativePackages(F)),Y={...process.env,...q},runNodeTsc=async()=>{let n=nodeBinary();if(!(n.includes(`/`)||n.includes(`\\`)?existsSync(n):isOnPath(n)))return ve.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${n}\` cannot be run, so upstream \`typescript\` cannot run either.`),ve.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ve.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((S,C)=>{spawnToCompletion(n,[W,...N],{completion:`exit`,env:Y,onSpawn:n=>{let S=!1;n.on(`error`,()=>{S=!0}),n.on(`close`,n=>{S||forceExit(n??1)})}}).catch(C)})}catch(n){let S=n;return S.code===`ENOENT`?(ve.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ve.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ve.error(`gjsify tsc (node typescript): ${S.message}`),forceExit(1)}};if(H)try{await new Promise((n,S)=>{spawnToCompletion(`gjs`,[`-m`,H,...N],{completion:`exit`,env:Y,onSpawn:n=>{let S=!1;n.on(`error`,()=>{S=!0}),n.on(`close`,n=>{S||forceExit(n??1)})}}).catch(S)})}catch(n){let S=n;return S.code===`ENOENT`&&W?await runNodeTsc():(S.code===`ENOENT`?(ve.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ve.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ve.error(`gjsify tsc: ${S.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(n){return n.split(`
|
|
1683
|
+
`).map(n=>n.trim()).filter(Boolean)}var LV=__esmMin(()=>{Vl()});function classifyAndExpand(n,S){let C=S.map(n=>n.replace(/\\/g,`/`)).filter(n=>n.length>0);if(C.length===0)return{global:!1,reason:`empty-diff`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};let N=[];for(let n of C)zV.some(S=>S.test(n))||N.push(n);if(N.length===0)return{global:!1,reason:`ignored-only`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};for(let S of N)for(let C of RV)if(C.test(S))return{global:!0,reason:`global-trigger ${C.source} matched ${S}`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};let{matched:F,unmatched:I}=workspacesForChangedFiles(n,N),H=new Set(n.map(n=>n.name)),W=new Set,q=new Set,Y=!1;for(let S of VV){let C=N.filter(n=>S.match.test(n));if(C.length!==0){for(let n of C)q.add(n);for(let C of S.seeds){if(!H.has(C))return{global:!0,reason:`script-coupling seed ${C} is not a workspace (${S.match.source} → ${S.why}); SCRIPT_COUPLINGS in commands/affected.ts is stale`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};W.add(C)}S.runE2E&&(Y=!0)}}let X=I.filter(n=>!q.has(n));if(X.length>0)return{global:!0,reason:`unmatched files (${X.length}): ${X.slice(0,3).join(`, `)}${X.length>3?`…`:``}`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};for(let n of W)F.add(n);if(W.size===0&&N.every(n=>BV.some(S=>S.test(n)))&&F.size===1){let n=[...F][0],S=N.some(n=>n.startsWith(`tests/e2e/`)),C=N.some(n=>n.startsWith(`tests/integration/`));return{global:!1,reason:`test-only (${N.length} file(s) in ${n})`,workspaces:[n],runE2E:S,runIntegration:C||isIntegrationWorkspace(n),skipAll:!1}}let Z=affectedClosure(buildReverseDependencyGraph(n,{includeDev:!1}),[...F]),te=buildDependencyGraph(n,{includeDev:!0}),ne=!1;for(let[n,S]of te.edges)if(isIntegrationWorkspace(n)){for(let C of S)if(Z.has(C)){Z.add(n),ne=!0;break}}let re=N.some(n=>n.startsWith(`tests/e2e/`))||Y;return{global:!1,reason:`closure (${Z.size} ws from ${F.size} seed(s))`+(W.size>0?`, ${W.size} via script-coupling`:``),workspaces:[...Z].sort(),runE2E:re,runIntegration:ne,skipAll:!1}}function isIntegrationWorkspace(n){return n.startsWith(`@gjsify/integration-`)}var RV,zV,BV,VV,HV=__esmMin(()=>{GM(),RV=[/^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$/],zV=[/\.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)\.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$/],BV=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],VV=[{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/`}]});function runGitDiff(n,S,C){let N=spawnSync(`git`,[`diff`,`--name-only`,`${S}...${C}`],{cwd:n,encoding:`utf8`});if(N.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${N.status}): ${N.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${N.status})`);return N.stdout.split(`
|
|
1683
1684
|
`).filter(Boolean)}function emit(n,S){if(n===`json`){process.stdout.write(JSON.stringify(S)+`
|
|
1684
1685
|
`);return}if(n===`globs`){for(let n of S.workspaces)process.stdout.write(`${n}\n`);return}if(n===`github-actions`){let n=S.global?``:S.workspaces.map(n=>`--include ${assertShellSafeWorkspaceName(n)}`).join(` `),C=process.env.GITHUB_OUTPUT,N=[`skip-all=${S.skipAll}`,`global=${S.global}`,`include-args=${n}`,`run-integration=${S.runIntegration}`,`run-e2e=${S.runE2E}`,`reason=${S.reason}`];if(C)for(let n of N)appendFileSync(C,`${n}\n`);else for(let n of N)process.stdout.write(`${n}\n`);return}process.stdout.write(`affected:
|
|
1685
|
-
`),process.stdout.write(` reason: ${S.reason}\n`),process.stdout.write(` global: ${S.global}\n`),process.stdout.write(` skip-all: ${S.skipAll}\n`),process.stdout.write(` run-integration: ${S.runIntegration}\n`),process.stdout.write(` run-e2e: ${S.runE2E}\n`),process.stdout.write(` workspaces (${S.workspaces.length}):\n`);for(let n of S.workspaces)process.stdout.write(` - ${n}\n`)}function assertShellSafeWorkspaceName(n){if(
|
|
1686
|
+
`),process.stdout.write(` reason: ${S.reason}\n`),process.stdout.write(` global: ${S.global}\n`),process.stdout.write(` skip-all: ${S.skipAll}\n`),process.stdout.write(` run-integration: ${S.runIntegration}\n`),process.stdout.write(` run-e2e: ${S.runE2E}\n`),process.stdout.write(` workspaces (${S.workspaces.length}):\n`);for(let n of S.workspaces)process.stdout.write(` - ${n}\n`)}function assertShellSafeWorkspaceName(n){if(WV.test(n))return n;throw process.stderr.write(`gjsify affected: workspace name ${JSON.stringify(n)} 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 ${n}`)}var UV,WV,GV=__esmMin(()=>{Dh(),Vl(),LV(),GM(),HV(),qM(),UV={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:n=>n.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 n=>{let S=n.cwd??findWorkspaceRoot(process.cwd())??process.cwd(),C=classifyAndExpand(discoverWorkspaces(S,{includeRoot:!0}),n[`changed-from-stdin`]?readStdinLines():runGitDiff(S,n.base??`origin/main`,n.head??`HEAD`));emit(n.format,C)}},WV=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),KV=__exportAll$4({isSelfWrite:()=>isSelfWrite,runWatchLoop:()=>runWatchLoop,spawnBundleSupervised:()=>spawnBundleSupervised,spawnSupervised:()=>spawnSupervised});function spawnSupervised(n,S,C){return new Promise((N,F)=>{spawnToCompletion(n,S,{completion:`daemon`,env:C,onSpawn:N}).catch(F)})}async function spawnBundleSupervised(n,S,C,N){if(n!==`gjs`){let{bundleRequiresNodeGi:F,resolveNodeGiForBundle:I}=await Promise.resolve().then(()=>(xP(),bP));if(F(S)&&!I(S,C))throw Error(`Cannot run ${N} on ${n}: \`@gjsify/node-gi\` is not installed. Add @gjsify/node-gi as a dependency to run ${N} on ${n}.`)}let{computeNativeEnvForBundle:F}=await Promise.resolve().then(()=>(yP(),vP)),{env:I}=F(S,C),H={...process.env,...I};if(n===`gjs`)return spawnSupervised(`gjs`,[`-m`,S],H);if(n===`node`){let{nodeBinary:n}=await Promise.resolve().then(()=>(xP(),bP));return spawnSupervised(n(),[S],H)}let[W,q]=kh[n].launch(S);return spawnSupervised(W,q,H)}function isSelfWrite(n,S,C){if(S===void 0||C===null)return!1;let N=Os(n,C),F=Os(n,S);if(N===F||N.startsWith(`${F}.`))return!0;let I=Ps(F);return I===Os(n)?!1:N===I||N.startsWith(`${I}${zs}`)}async function runWatchLoop(n){let{dir:S,label:C,prepare:N,build:F,spawnChild:I,output:H,debounceMs:W=200}=n;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{N&&await N(),q&&=(q.kill(),null),await F(),I&&(q=await I())}catch(n){ve.error(`[${C}] rebuild failed: ${n.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=watch(S,{recursive:!0},(n,C)=>{isSelfWrite(S,H,typeof C==`string`?C:null)||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))});holdMainLoop();let ne=!1,shutdown=()=>{ne||(ne=!0,Z&&clearTimeout(Z),q?.kill(),te.close(),process.exit(0))};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ve.log(`[${C}] watching ${n.dirLabel??S} — press Ctrl+C to stop`)}var qV=__esmMin(()=>{ye(),Vl(),Hs(),Ie(),AF(),_P(),Ah()});function readPackage$3(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(n){return n?`org.gjsify.storybook.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(n){let S=[];if(!existsSync(n))return S;for(let C of readdirSync(n,{withFileTypes:!0})){if(C.name===`node_modules`||C.name.startsWith(`.`))continue;let N=js(n,C.name);C.isDirectory()?S.push(...findStoryFiles(N)):/\.story\.(ts|js|mts|mjs)$/.test(C.name)&&S.push(N)}return S}function generateEntry$2(n,S,C){let N=n.map((n,S)=>`import * as m${S} from ${JSON.stringify(n)};`).join(`
|
|
1686
1687
|
`),F=n.map((n,S)=>`m${S}`).join(`, `),I=C?`\n title: ${JSON.stringify(C)},`:``;return`// Auto-generated by \`gjsify storybook\` — do not edit by hand.
|
|
1687
1688
|
import { collectStoryModules, runStorybook } from '@gjsify/storybook';
|
|
1688
1689
|
${N}
|
|
@@ -1691,7 +1692,7 @@ await runStorybook({
|
|
|
1691
1692
|
applicationId: ${JSON.stringify(S)},${I}
|
|
1692
1693
|
stories: collectStoryModules([${F}]),
|
|
1693
1694
|
});
|
|
1694
|
-
`}var
|
|
1695
|
+
`}var JV,YV=__esmMin(()=>{ye(),Vl(),Hs(),th(),__name$1(readPackage$3,`readPackage`),__name$1(generateEntry$2,`generateEntry`),JV={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:n=>n.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 n=>{let S=process.cwd(),C=readPackage$3(S),N=C.gjsify?.storybook??{},F=Os(S,n.stories??N.stories??`src`),I=n.appId??N.applicationId??deriveAppId(C.name),H=n.title??N.title,W=n.globals??N.globals??`auto`,q=n.runtime??N.runtime??hostRuntime$1(),Y=q===`gjs`?`gjs`:`node`,X=js(S,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(X,{recursive:!0});let Z=js(X,`entry.ts`),te=n.out?Os(S,n.out):js(X,`storybook.${Y}.mjs`),writeEntry=()=>{let n=findStoryFiles(F).sort();return writeFileSync(Z,generateEntry$2(n,I,H)),n.length},ne=writeEntry();if(ne===0)return ve.error(`No *.story.ts files found under ${Ms(S,F)||F}\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);ve.log(`Found ${ne} story file(s) under ${Ms(S,F)||`.`} (runtime: ${q})`);let{runCli:re}=await Promise.resolve().then(()=>(aH(),iH)),buildBundle=()=>re([`build`,Z,`--app`,Y,`--globals`,W,`--outfile`,te]),launch=async()=>{if(q===`gjs`){let{runGjsBundle:n}=await Promise.resolve().then(()=>(yP(),vP));await n(te,[],{completion:`exit`,exitOnSuccess:!0})}else if(q===`node`){let{runNodeBundle:n}=await Promise.resolve().then(()=>(xP(),bP));await n(te,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:n}=await Promise.resolve().then(()=>(xP(),bP));await n(q,te,[],{completion:`exit`,exitOnSuccess:!0})}};if(!n.watch){if(await buildBundle(),n.buildOnly)return;await launch();return}let{runWatchLoop:ie,spawnBundleSupervised:ae}=await Promise.resolve().then(()=>(qV(),KV));await ie({dir:F,dirLabel:Ms(S,F)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:n.buildOnly?null:()=>ae(q,te,S,`the storybook`),output:te})}}});function readFlag(n,S){let C=`--${S}`;for(let S=0;S<n.length;S++){let N=n[S];if(N===C)return n[S+1];if(N.startsWith(`${C}=`))return N.slice(C.length+1)}}function withFlag(n,S,C){let N=`--${S}`,F=[...n];for(let n=0;n<F.length;n++){let S=F[n];if(S===N)return F[n+1]=C,F;if(S.startsWith(`${N}=`))return F[n]=`${N}=${C}`,F}return F.push(N,C),F}function buildEntryPoint(n){let S=n[1];if(!(S===void 0||S.startsWith(`-`)))return S}function noEntryError(n,S){let C=S?`\`${n}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${n}\` script`;return Error(`gjsify dev: nothing to build — ${C}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(n){let S=n.scripts[n.scriptName],C=typeof S==`string`?gjsifyCommandArgv(S):null,N=C&&C[0]===`build`?C:null,F=n.entry??(N?buildEntryPoint(N):void 0);if(F===void 0)throw noEntryError(n.scriptName,typeof S==`string`);let I;return N?(I=[...N],buildEntryPoint(N)===void 0?I.splice(1,0,F):I[1]=F):I=[`build`,F],I=withFlag(I,`app`,n.app),n.globals!==void 0&&(I=withFlag(I,`globals`,n.globals)),n.outfile!==void 0&&(I=withFlag(I,`outfile`,n.outfile)),{buildArgv:I,bundle:readFlag(I,`outfile`)??n.declaredBundle,watchDir:n.watchDir??Ps(F)}}function noBundleError(n,S){return Error(`gjsify dev: nothing to launch — neither \`${n}\` nor --outfile names an output file, and this package declares no ${S===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${S}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var XV=__esmMin(()=>{Hs(),OF()});function readPackage$2(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}var ZV,QV=__esmMin(()=>{ye(),Vl(),Hs(),XV(),Ah(),th(),__name$1(readPackage$2,`readPackage`),ZV={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:n=>n.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:Oh,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 n=>{let S=process.cwd(),C=readPackage$2(S),N=n.runtime??hostRuntime$1(),F=buildAppForRuntime(N),I=n.script??(F===`gjs`?`build:gjs`:`build:node`),H;try{H=planDev({scripts:C.scripts??{},scriptName:I,app:F,declaredBundle:F===`gjs`?C.gjsify?.main:C.gjsify?.example?.node,entry:n.entry,globals:n.globals,outfile:n.outfile,watchDir:n.watchDir})}catch(n){return ve.error(n.message),process.exit(1)}let W=H.bundle===void 0?void 0:Os(S,H.bundle);if(W===void 0&&!n.buildOnly)return ve.error(noBundleError(I,F).message),process.exit(1);let q=Os(S,H.watchDir);if(!existsSync(q))return ve.error(`gjsify dev: nothing to watch — ${Ms(S,q)||q} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let Y=W===void 0?`\`${I}\` output`:Ms(S,W);ve.log(`Watching ${Ms(S,q)||`.`} → ${Y} (runtime: ${N})`);let{runCli:X}=await Promise.resolve().then(()=>(aH(),iH)),{runWatchLoop:Z,spawnBundleSupervised:te}=await Promise.resolve().then(()=>(qV(),KV));await Z({dir:q,dirLabel:Ms(S,q)||`.`,label:`dev`,build:()=>X(H.buildArgv),spawnChild:n.buildOnly||W===void 0?null:()=>te(N,W,S,`this project`),output:W,debounceMs:n.debounce})}}});function readPackage$1(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(n){return n?`org.gjsify.storybook.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(n){return n?`org.gjsify.browser.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(n,S){return!!(n.dependencies?.[S]||n.devDependencies?.[S])}function generateEntry$1(n,S,C,N,F){let I=JSON.stringify(S),H=F?`, { address: ${JSON.stringify(F)} }`:``;return n===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
|
|
1695
1696
|
import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
|
|
1696
1697
|
|
|
1697
1698
|
await runDevtoolsMcp(storybookProfile(${I}${H}));
|
|
@@ -1711,10 +1712,10 @@ await runDevtoolsMcp({
|
|
|
1711
1712
|
version: ${JSON.stringify(N)},
|
|
1712
1713
|
busNameBase: ${I},${F?`\n address: ${JSON.stringify(F)},`:``}
|
|
1713
1714
|
});
|
|
1714
|
-
`}var
|
|
1715
|
+
`}var $V,eH=__esmMin(()=>{ye(),Vl(),Hs(),__name$1(readPackage$1,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$1,`generateEntry`),$V={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:n=>n.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 n=>{let S=process.cwd(),C=readPackage$1(S),N=C.gjsify?.devtools??{},F=n.profile??N.profile??(hasDep(C,`@gjsify/storybook`)?`storybook`:hasDep(C,`@gjsify/devtools-browser`)?`browser`:hasDep(C,`@gjsify/devtools-cdp`)?`cdp`:`generic`),I=n.busName??N.busNameBase??(F===`storybook`?C.gjsify?.storybook?.applicationId??deriveStorybookAppId(C.name):F===`browser`||F===`cdp`?C.gjsify?.browse?.applicationId??deriveBrowserAppId$1(C.name):void 0);if(!I)return ve.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let H=n.globals??N.globals??`auto`,W=C.name?`${C.name}-devtools`:`gjsify-devtools`,q=js(S,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(q,{recursive:!0});let Y=js(q,`entry.ts`),X=n.out?Os(S,n.out):js(q,`bridge.gjs.mjs`),Z=n.address??N.address;writeFileSync(Y,generateEntry$1(F,I,W,`0.8.0`,Z)),ve.error(`[gjsify debug] profile=${F} bus=${I}${Z?` address=${Z}`:``}`);let{runCli:te}=await Promise.resolve().then(()=>(aH(),iH));if(await te([`build`,Y,`--app`,`gjs`,`--shebang`,`--globals`,H,`--outfile`,X]),n.buildOnly){ve.error(`[gjsify debug] built ${X}`);return}let{runGjsBundle:ne}=await Promise.resolve().then(()=>(yP(),vP));await ne(X,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(n){return n?`org.gjsify.browser.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(n,S,C,N,F){let I=C?`\n title: ${JSON.stringify(C)},`:``,H=S?`\n homeUrl: ${JSON.stringify(S)},`:``,W=N===void 0?``:`\n inspectorPort: ${N},`,q=F?`\n screenshot: ${JSON.stringify(F)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
|
|
1715
1716
|
import { runBrowserDevtools } from '@gjsify/devtools-browser';
|
|
1716
1717
|
|
|
1717
1718
|
await runBrowserDevtools({
|
|
1718
1719
|
applicationId: ${JSON.stringify(n)},${I}${H}${W}${q}
|
|
1719
1720
|
});
|
|
1720
|
-
`}var
|
|
1721
|
+
`}var tH,nH=__esmMin(()=>{ye(),Vl(),Hs(),tH={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:n=>n.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 n=>{let S=process.cwd(),C=readPackage(S),N=C.gjsify?.browse??{},F=n.appId??N.applicationId??deriveBrowserAppId(C.name),I=n.title??N.title,H=n.globals??N.globals??`auto,dom`,W=n.url,q=n.inspectorPort??N.inspectorPort,Y=n.devtools||q!==void 0,X=js(S,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(X,{recursive:!0});let Z=js(X,`entry.ts`),te=n.out?Os(S,n.out):js(X,`browse.gjs.mjs`);writeFileSync(Z,generateEntry(F,W,I,q,n.screenshot?Os(S,n.screenshot):void 0)),ve.log(`[gjsify browse] app=${F}${W?` url=${W}`:``}${Y?` devtools=1`:``}${q===void 0?``:` inspector-port=${q}`}`);let{runCli:ne}=await Promise.resolve().then(()=>(aH(),iH));if(await ne([`build`,Z,`--app`,`gjs`,`--globals`,H,`--outfile`,te]),n.buildOnly){ve.log(`[gjsify browse] built ${te}`);return}Y&&(process.env.GJSIFY_DEVTOOLS=`1`),q!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${q}`);let{runGjsBundle:re}=await Promise.resolve().then(()=>(yP(),vP));await re(te,[],{completion:`exit`,exitOnSuccess:!0})}}}),rH=__esmMin(()=>{iP(),sP(),uP(),CP(),MF(),PF(),IF(),YF(),cI(),EI(),kI(),NI(),II(),yL(),Qz(),iI(),oB(),dB(),qF(),gB(),RB(),BB(),UB(),GB(),ZB(),rV(),uV(),pV(),hV(),_V(),yV(),xV(),CV(),kV(),PV(),IV(),GV(),YV(),QV(),eH(),nH()}),iH=__exportAll$4({runCli:()=>runCli});function runtimeLabel(){let n=gjsSystemVersion();if(n!==void 0){let S=Number(n);return`GJS ${Math.floor(S/1e4)}.${Math.floor(S%1e4/100)}.${S%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(n){ensureGjsifyShimOnPath();let S=Hf(n);await S.scriptName(rp).version(cliVersion()).strict().fail((n,C)=>{let N=classifyCliFailure(n,C);if(N.kind===`usage`)throw S.showHelp(`error`),Error(N.message,{cause:C})}).wrap(S.terminalWidth()).command(TI.command,TI.description,TI.builder,TI.handler).command(iB.command,iB.description,iB.builder,iB.handler).command(rP.command,rP.description,rP.builder,rP.handler).command(oP.command,oP.description,oP.builder,oP.handler).command(lP.command,lP.description,lP.builder,lP.handler).command(SP.command,SP.description,SP.builder,SP.handler).command(jF.command,jF.description,jF.builder,jF.handler).command(rI.command,rI.description,rI.builder,rI.handler).command(NF.command,NF.description,NF.builder,NF.handler).command(FF.command,FF.description,FF.builder,FF.handler).command(JF.command,JF.description,JF.builder,JF.handler).command(sI.command,sI.description,sI.builder,sI.handler).command(OI.command,OI.description,OI.builder,OI.handler).command(MI.command,MI.description,MI.builder,MI.handler).command(FI.command,FI.description,FI.builder,FI.handler).command(vL.command,vL.description,vL.builder,vL.handler).command(Zz.command,Zz.description,Zz.builder,Zz.handler).command(uB.command,uB.description,uB.builder,uB.handler).command(KF.command,KF.description,KF.builder,KF.handler).command(pB.command,pB.description,pB.builder,pB.handler).command(LB.command,LB.description,LB.builder,LB.handler).command(zB.command,zB.description,zB.builder,zB.handler).command(HB.command,HB.description,HB.builder,HB.handler).command(WB.command,WB.description,WB.builder,WB.handler).command(XB.command,XB.description,XB.builder,XB.handler).command(nV.command,nV.description,nV.builder,nV.handler).command(cV.command,cV.description,cV.builder,cV.handler).command(fV.command,fV.description,fV.builder,fV.handler).command(gV.command,gV.description,gV.builder,gV.handler).command(mV.command,mV.description,mV.builder,mV.handler).command(EV.command,EV.description,EV.builder,EV.handler).command(vV.command,vV.description,vV.builder,vV.handler).command(bV.command,bV.description,bV.builder,bV.handler).command(SV.command,SV.description,SV.builder,SV.handler).command(NV.command,NV.description,NV.builder,NV.handler).command(FV.command,FV.description,FV.builder,FV.handler).command(UV.command,UV.description,UV.builder,UV.handler).command(JV.command,JV.description,JV.builder,JV.handler).command(ZV.command,ZV.description,ZV.builder,ZV.handler).command($V.command,$V.description,$V.builder,$V.handler).command(tH.command,tH.description,tH.builder,tH.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var aH=__esmMin(()=>{Uf(),Wf(),np(),rH(),ip(),th(),DF()});ye(),aH(),th();try{await runCli(hideBin(process.argv))}catch(n){let S=typeof n==`object`&&n&&typeof n.code==`string`?n.code:``,C=n instanceof Error?n.message:String(n);ve.error(S&&!C.includes(S)?`${S}: ${C}`:C),process.env.GJSIFY_DEBUG&&n instanceof Error&&n.stack&&ve.error(n.stack),process.exitCode=1,gjsExit(1)}
|