@alexgorbatchev/dotfiles 0.0.5 → 0.0.10

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/cli.js CHANGED
@@ -1,41 +1,41 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{i as vG}from"./cli-fj2hdbnx.js";function s($,M){if(M.startsWith($)){let J=M.slice($.length);return J.startsWith("/")||J===""?`~${J}`:M}return M}function c($){let M=$.split(`
4
- `),J=M.filter((Y)=>Y.trim().length>0);if(J.length===0)return $;let Q=Math.min(...J.map((Y)=>Y.match(/^ */)?.[0].length??0));return M.map((Y)=>Y.slice(Q)).join(`
5
- `).trim()}function L7($,M,J){let Q=M[1];if(Q&&Q in J){let Y=J[Q];if(Y!==void 0){let G=$.match(/^(\s*)/)?.[1]??"";return Y.split(`
6
- `).map((Z)=>G+Z)}}return[$]}function x7($,M){let J=$,Q=/{(\w+)}/g,Y;Y=Q.exec(J);while(Y!==null){let G=Y[0],X=Y[1];if(X&&X in M){let Z=M[X];if(Z!==void 0)J=J.replace(G,Z),Q.lastIndex=0}Y=Q.exec(J)}return J}function oJ($,M){let Q=c($).split(`
7
- `),Y=[];for(let G of Q){let Z=G.trim().match(/^{(\w+)}$/);if(Z){let q=L7(G,Z,M);Y.push(...q)}else{let q=x7(G,M);Y.push(q)}}return Y.join(`
8
- `)}function j$($){if(!$)return $;return $.replace(/[/\\]/g,"-").replace(/[:]/g,"-").replace(/[<>"|?*]/g,"_").trim()}async function A$($){let{binaryPath:M,args:J=["--version"],regex:Q,env:Y,shellExecutor:G}=$;try{let X=await G`${M} ${J}`.env({...process.env,...Y}).quiet().noThrow(),Z=(X.stdout.toString()+X.stderr.toString()).trim();if(Q){let U=typeof Q==="string"?new RegExp(Q):Q,K=Z.match(U);if(K?.[1])return j$(K[1]);throw Error(`Version detection failed: regex ${U} did not match output: ${Z}`)}let q=/v?(\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?)/i,I=Z.match(q);if(I?.[1])return j$(I[1]);return}catch(X){if(X instanceof Error&&X.message.startsWith("Version detection failed"))throw X;return}}var x={SUCCESS:0,ERROR:1};function N($){throw process.exit($),Error(`MOCK_EXIT_CLI_CALLED_WITH_${$}`)}function n($,M){if(M==="~"||M.startsWith("~/")||M.startsWith("~\\"))return M.replace(/^~(?=$|\/|\\)/,$);return M}import f0 from"path";function RM($,M,J,Q){let Y=T7(M,J);if(Y=n(J.paths.homeDir,Y),!f0.isAbsolute(Y))if($){let G=f0.dirname($);Y=f0.resolve(G,Y)}else Y=f0.resolve(J.paths.dotfilesDir,Y);return Y}function T7($,M){return $.replace(/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,(J,Q)=>{if(Q.includes(".")){let Y=Q.split("."),G=M;for(let X of Y)if(G&&typeof G==="object"&&X in G)G=G[X];else return J;return typeof G==="string"?G:J}return J})}function H0($){let J=(typeof $==="string"?parseInt($,8):$)&511,Q=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"],Y=Q[J>>6&7]??"---",G=Q[J>>3&7]??"---",X=Q[J&7]??"---";return Y+G+X}function i6($=new Date){let M=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0"),Y=String($.getHours()).padStart(2,"0"),G=String($.getMinutes()).padStart(2,"0"),X=String($.getSeconds()).padStart(2,"0");return`${M}-${J}-${Q}-${Y}-${G}-${X}`}import k7 from"path";function p0($){let M=$?.DOTFILES_BUILT_PACKAGE_NAME??"@alexgorbatchev/dotfiles";if(M!==void 0){let J=M.trim();if(J!=="")return J}return"@alexgorbatchev/dotfiles"}var S7=`/**
3
+ import{i as C1}from"./cli-fj2hdbnx.js";function r($,I){if(I.startsWith($)){let M=I.slice($.length);return M.startsWith("/")||M===""?`~${M}`:I}return I}function c($){let I=$.split(`
4
+ `),M=I.filter((J)=>J.trim().length>0);if(M.length===0)return $;let G=Math.min(...M.map((J)=>J.match(/^ */)?.[0].length??0));return I.map((J)=>J.slice(G)).join(`
5
+ `).trim()}function NY($,I,M){let G=I[1];if(G&&G in M){let J=M[G];if(J!==void 0){let Q=$.match(/^(\s*)/)?.[1]??"";return J.split(`
6
+ `).map((X)=>Q+X)}}return[$]}function yY($,I){let M=$,G=/{(\w+)}/g,J;J=G.exec(M);while(J!==null){let Q=J[0],Y=J[1];if(Y&&Y in I){let X=I[Y];if(X!==void 0)M=M.replace(Q,X),G.lastIndex=0}J=G.exec(M)}return M}function e0($,I){let G=c($).split(`
7
+ `),J=[];for(let Q of G){let X=Q.trim().match(/^{(\w+)}$/);if(X){let R=NY(Q,X,I);J.push(...R)}else{let R=yY(Q,I);J.push(R)}}return J.join(`
8
+ `)}function j$($){if(!$)return $;return $.replace(/[/\\]/g,"-").replace(/[:]/g,"-").replace(/[<>"|?*]/g,"_").trim()}async function D$($){let{binaryPath:I,args:M=["--version"],regex:G,env:J,shellExecutor:Q}=$;try{let Y=await Q`${I} ${M}`.env({...process.env,...J}).quiet().noThrow(),X=(Y.stdout.toString()+Y.stderr.toString()).trim();if(G){let q=typeof G==="string"?new RegExp(G):G,U=X.match(q);if(U?.[1])return j$(U[1]);throw Error(`Version detection failed: regex ${q} did not match output: ${X}`)}let R=/v?(\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?)/i,W=X.match(R);if(W?.[1])return j$(W[1]);return}catch(Y){if(Y instanceof Error&&Y.message.startsWith("Version detection failed"))throw Y;return}}var E={SUCCESS:0,ERROR:1};function y($){throw process.exit($),Error(`MOCK_EXIT_CLI_CALLED_WITH_${$}`)}function n($,I){if(I==="~"||I.startsWith("~/")||I.startsWith("~\\"))return I.replace(/^~(?=$|\/|\\)/,$);return I}import mM from"path";function w$($,I,M,G){let J=vY(I,M);if(J=n(M.paths.homeDir,J),!mM.isAbsolute(J))if($){let Q=mM.dirname($);J=mM.resolve(Q,J)}else J=mM.resolve(M.paths.dotfilesDir,J);return J}function vY($,I){return $.replace(/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,(M,G)=>{if(G.includes(".")){let J=G.split("."),Q=I;for(let Y of J)if(Q&&typeof Q==="object"&&Y in Q)Q=Q[Y];else return M;return typeof Q==="string"?Q:M}return M})}function jM($){let M=(typeof $==="string"?parseInt($,8):$)&511,G=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"],J=G[M>>6&7]??"---",Q=G[M>>3&7]??"---",Y=G[M&7]??"---";return J+Q+Y}function a6($=new Date){let I=$.getFullYear(),M=String($.getMonth()+1).padStart(2,"0"),G=String($.getDate()).padStart(2,"0"),J=String($.getHours()).padStart(2,"0"),Q=String($.getMinutes()).padStart(2,"0"),Y=String($.getSeconds()).padStart(2,"0");return`${I}-${M}-${G}-${J}-${Q}-${Y}`}import PY from"path";function gM($){let I=$?.DOTFILES_BUILT_PACKAGE_NAME??"@alexgorbatchev/dotfiles";if(I!==void 0){let M=I.trim();if(M!=="")return M}return"@alexgorbatchev/dotfiles"}var CY=`/**
9
9
  * Type-safe binary names for tool dependencies.
10
10
  *
11
11
  * This file is automatically generated by the build system and the \`generate\` command.
12
12
  * It extracts binary names from loaded tool configurations to provide autocomplete
13
13
  * for the \`dependsOn()\` method.
14
- */`;function w7($){let M=new Set;for(let[J,Q]of Object.entries($))if(Q.binaries&&Q.binaries.length>0)for(let Y of Q.binaries)if(typeof Y==="string")M.add(Y);else{let G=Y;M.add(G.name)}else M.add(J);return M}function b7($){if($.size===0)return"string";return Array.from($).toSorted().map((Q)=>`'${Q}'`).join(" | ")}function N7($,M){let J=w7($),G=(b7(J)==="string"?[]:Array.from(J).toSorted()).map((H)=>` '${H}': never;`).join(`
15
- `),Z=G.length>0?` interface IKnownBinNameRegistry {
16
- ${G}
17
- }`:" interface IKnownBinNameRegistry {}",I=`declare module '${M??p0()}' {
18
- ${Z}
19
- }`;return[S7,I,"export {};",""].join(`
14
+ */`;function dY($){let I=new Set;for(let[M,G]of Object.entries($))if(G.binaries&&G.binaries.length>0)for(let J of G.binaries)if(typeof J==="string")I.add(J);else{let Q=J;I.add(Q.name)}else I.add(M);return I}function uY($){if($.size===0)return"string";return Array.from($).toSorted().map((G)=>`'${G}'`).join(" | ")}function fY($,I){let M=dY($),Q=(uY(M)==="string"?[]:Array.from(M).toSorted()).map((H)=>` '${H}': never;`).join(`
15
+ `),X=Q.length>0?` interface IKnownBinNameRegistry {
16
+ ${Q}
17
+ }`:" interface IKnownBinNameRegistry {}",W=`declare module '${I??gM()}' {
18
+ ${X}
19
+ }`;return[CY,W,"export {};",""].join(`
20
20
 
21
- `)}async function l6($,M,J,Q){let Y=N7($,Q);await J.ensureDir(k7.dirname(M)),await J.writeFile(M,Y,"utf8")}import a6 from"path";async function wM($,M,J){let Q=[],Y=J!==void 0,G=J??M,X=await $.readdir(M);for(let Z of X){let q=a6.join(M,Z);if((await $.stat(q)).isDirectory()){let U=await wM($,q,Y?G:void 0);Q.push(...U)}else{let U=Y?a6.relative(G,q):q;Q.push(U)}}return Q}function sM(){if(typeof CLI_BIN_PATH>"u")return process.argv.slice(0,2).join(" ");return CLI_BIN_PATH}async function s6($,M,J){let Q=$ instanceof Request?$.url:$.toString(),Y=J?.enabled?`http://localhost:${J.port}/${Q}`:Q;if($ instanceof Request)return fetch(Y,{method:$.method,headers:$.headers,body:$.body,mode:$.mode,credentials:$.credentials,cache:$.cache,redirect:$.redirect,referrer:$.referrer,integrity:$.integrity,...M});return fetch(Y,M)}async function t$($,M){if(typeof M==="function")return await M($);return M}async function c0($,M,J,Q,Y){let G=Y?.mode??"file",X=v7(J),Z=await $.readFile(M,"utf8"),q=G==="line"?await y7(Z,X,Q):await r6(Z,X,Q),I=q!==Z;if(I)await $.writeFile(M,q,"utf8");return I}function v7($){if(typeof $==="string"){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(Q,"g")}let M=$.flags.includes("g")?$.flags:`${$.flags}g`;return new RegExp($.source,M)}async function r6($,M,J){let Q=Array.from($.matchAll(M)),Y=$,G=0;for(let X of Q){let Z=X[0]??"",q=X.index??0,I=X.slice(1),U=X.groups,H=await t$({substring:Z,captures:I,offset:q,input:$,groups:U},J),_=q+G,O=_+Z.length;Y=Y.slice(0,_)+H+Y.slice(O),G+=H.length-Z.length}return Y}async function y7($,M,J){let Q=$.split(/(\r\n|\n)/),Y="";for(let G=0;G<Q.length;G+=2){let X=Q[G]??"",Z=Q[G+1]??"",q=await r6(X,M,J);Y+=q+Z}return Y}import{z as t6}from"zod";var E$;((X)=>{X[X.None=0]="None";X[X.Linux=1]="Linux";X[X.MacOS=2]="MacOS";X[X.Windows=4]="Windows";X[X.Unix=3]="Unix";X[X.All=7]="All"})(E$||={});var OM;((Y)=>{Y[Y.None=0]="None";Y[Y.X86_64=1]="X86_64";Y[Y.Arm64=2]="Arm64";Y[Y.All=3]="All"})(OM||={});var o6=t6.number().int().min(0).max(7).refine(($)=>{return($&-8)===0},{message:"Must be a valid Platform value. Use `Platform.None`, `Platform.Linux`, `Platform.MacOS`, `Platform.Windows`, `Platform.Unix`, or `Platform.All`. You can combine values with a bitwise OR (e.g., `Platform.Linux | Platform.MacOS`)."}),e6=t6.number().int().min(0).max(3).refine(($)=>{return($&-4)===0},{message:"Must be a valid Architecture value. Use `Architecture.None`, `Architecture.X86_64`, `Architecture.Arm64`, or `Architecture.All`. You can combine values with a bitwise OR (e.g., `Architecture.X86_64 | Architecture.Arm64`)."});function rM($,M){if(M===0)return $===0;return($&M)===M}function tM($,M){if(M===0)return $===0;return($&M)===M}function $Y($){switch($){case"darwin":return 2;case"linux":return 1;case"win32":return 4;default:return 0}}function MY($){switch($){case"x64":return 1;case"arm64":return 2;default:return 0}}function o$($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";case 0:return"none";default:return"unknown"}}function e$($){switch($){case 1:return"x86_64";case 2:return"arm64";case 0:return"none";default:return"unknown"}}import{z as F}from"zod";function P7($){let M=$?.enabled??!0,J=$?.ttl??86400000;return F.object({enabled:F.boolean().default(M),ttl:F.number().default(J)}).strict()}var h0=P7();function n0($){let{defaultHost:M,includeToken:J,includeUserAgent:Q,defaultUserAgent:Y="dotfiles-generator",tokenDefault:G=""}=$;return F.object({host:F.string().default(M),cache:h0.default(h0.parse({})),token:F.string().default(J?G:""),userAgent:F.string().default(Q?Y:"dotfiles-generator")}).strict()}var eJ=F.object({homeDir:F.string().default("{HOME}"),dotfilesDir:F.string().default("{configFileDir}"),targetDir:F.string().default("{paths.generatedDir}/bin-default"),generatedDir:F.string().default("{paths.dotfilesDir}/.generated"),toolConfigsDir:F.string().default("{paths.dotfilesDir}/tools"),shellScriptsDir:F.string().default("{paths.generatedDir}/shell-scripts"),binariesDir:F.string().default("{paths.generatedDir}/binaries")}).strict(),$Q=F.object({sudoPrompt:F.string().default("Please enter your password to continue:")}).strict(),MQ=F.object({debug:F.string().default("")}).strict(),JQ=F.object({checkOnRun:F.boolean().default(!0),checkInterval:F.number().default(86400)}).strict(),QQ=n0({defaultHost:"https://api.github.com",includeToken:!0,includeUserAgent:!0}),JY=n0({defaultHost:"https://crates.io"}),QY=n0({defaultHost:"https://raw.githubusercontent.com"}),YY=n0({defaultHost:"https://github.com"}),YQ=F.object({cratesIo:JY.default(JY.parse({})),githubRaw:QY.default(QY.parse({})),githubRelease:YY.default(YY.parse({})),userAgent:F.string().default("dotfiles-generator")}).strict(),GQ=F.object({timeout:F.number().default(300000),retryCount:F.number().default(3),retryDelay:F.number().default(1000),cache:h0.default(h0.parse({}))}).strict(),XQ=F.object({catalog:F.object({generate:F.boolean().default(!0),filePath:F.string().default("{paths.dotfilesDir}/CATALOG.md")}).strict().default({generate:!0,filePath:"{paths.dotfilesDir}/CATALOG.md"}),shellInstall:F.object({zsh:F.string().optional(),bash:F.string().optional(),powershell:F.string().optional()}).strict().optional()}).strict(),m0=["macos","linux","windows"],g0=["x86_64","arm64"],C7=F.union([F.object({os:F.enum(m0),arch:F.enum(g0).optional()}).strict(),F.object({os:F.enum(m0).optional(),arch:F.enum(g0)}).strict()]),d7=F.object({paths:eJ.required().default(eJ.parse({})),system:$Q.required().default($Q.parse({})),logging:MQ.required().default(MQ.parse({})),updates:JQ.required().default(JQ.parse({})),github:QQ.required().default(QQ.parse({})),cargo:YQ.required().default(YQ.parse({})),downloader:GQ.required().default(GQ.parse({})),features:XQ.default(XQ.parse({}))}).strict(),u7=F.object({paths:eJ.partial().optional(),system:$Q.partial().optional(),logging:MQ.partial().optional(),updates:JQ.partial().optional(),github:QQ.partial().optional(),cargo:YQ.partial().optional(),downloader:GQ.partial().optional(),features:XQ.partial().optional()}).strict(),f7=F.object({match:F.array(C7).nonempty(),get config(){return u7.partial()}}).strict(),ZQ=d7.extend({platform:F.array(f7).optional()}).strict(),GY=F.object({configFilePath:F.string(),configFileDir:F.string()});var{Glob:i7}=globalThis.Bun;import VM from"path";function W($){return $}var jM={VERBOSE:1,DEFAULT:3,QUIET:5},WQ=["verbose","default","quiet"],XY={verbose:jM.VERBOSE,default:jM.DEFAULT,quiet:jM.QUIET};function ZY($){let M=$.toLowerCase();if(!(M in XY))throw Error(`Invalid log level: ${$}. Valid levels are: ${WQ.join(", ")}`);return XY[M]}import{Logger as n7}from"tslog";var p7=/\.tool\.(ts|js)/,c7=/([^/\\]+\.tool\.(?:ts|js)):(\d+)/;function h7($){return p7.test($)}function m7($){let M=c7.exec($);if(!M)return null;return`${M[1]}:${M[2]}`}function g7($){if(!$)return[];let M=$.split(`
22
- `),J=[];for(let Q of M)if(h7(Q)){let Y=m7(Q);if(Y)J.push(Y)}return J}function WY($){let M=typeof $.stack==="string"?$.stack:void 0,J=g7(M);if(J.length===0)return null;return`(${J.join(", ")})`}function qY($){return $ instanceof Error}function IY($){let M=[],J=[...$.issues].toSorted((Q,Y)=>(Q.path??[]).length-(Y.path??[]).length);for(let Q of J)if(M.push(`\u2716 ${Q.message}`),Q.path?.length){let Y=Q.path.map(String).join(".");M.push(` \u2192 at ${Y}`)}return M}function UY($){return`[${$}]`}class _0 extends n7{_trace;constructor($){let J=($?.prefix??[]).map((Q)=>String(Q));if($?.context)J.push(UY($.context));super({...$,prefix:J});this._trace=$?.trace===!0}isTracingEnabled(){return this._trace}filterErrorArgs($){if(this.isTracingEnabled())return $;let M=[];for(let J of $)if(qY(J)){let Q=WY(J);if(Q)M.push(Q)}else M.push(J);return M}trace($,...M){return super.trace($,...M)}debug($,...M){return super.debug($,...M)}info($,...M){let J=this.filterErrorArgs(M);return super.info($,...J)}warn($,...M){let J=this.filterErrorArgs(M);return super.warn($,...J)}error($,...M){let J=this.filterErrorArgs(M);return super.error($,...J)}fatal($,...M){let J=this.filterErrorArgs(M);return super.fatal($,...J)}getSubLogger($){let M=[...this.settings.parentNames??[]];if(this.settings.name&&$?.name)M.push(this.settings.name);return new _0({...this.settings,...$,parentNames:M})}zodErrors($){let M=IY($);for(let J of M)this.error(J)}setPrefix($){return this.settings.prefix=[UY($)],this}}function qQ($){let M={};if(typeof $==="string")M.name=$;else M={...$};M.level=M.level??jM.DEFAULT;let J=M.trace?"{{logLevelName}}\t{{filePathWithLine}} - ":"{{logLevelName}}\t",Q=process.env.NO_COLOR==="1"||process.env.TERM==="dumb";return new _0({name:M.name,minLevel:M.level,trace:M.trace,prettyLogTemplate:J,stylePrettyLogs:!Q,hideLogPositionForProduction:!1,prettyErrorTemplate:`
21
+ `)}async function r6($,I,M,G){let J=fY($,G);await M.ensureDir(PY.dirname(I)),await M.writeFile(I,J,"utf8")}import s6 from"path";async function yI($,I,M){let G=[],J=M!==void 0,Q=M??I,Y=await $.readdir(I);for(let X of Y){let R=s6.join(I,X);if((await $.stat(R)).isDirectory()){let q=await yI($,R,J?Q:void 0);G.push(...q)}else{let q=J?s6.relative(Q,R):R;G.push(q)}}return G}function tI(){if(typeof CLI_BIN_PATH>"u")return process.argv.slice(0,2).join(" ");return CLI_BIN_PATH}async function t6($,I,M){let G=$ instanceof Request?$.url:$.toString(),J=M?.enabled?`http://localhost:${M.port}/${G}`:G;if($ instanceof Request)return fetch(J,{method:$.method,headers:$.headers,body:$.body,mode:$.mode,credentials:$.credentials,cache:$.cache,redirect:$.redirect,referrer:$.referrer,integrity:$.integrity,...I});return fetch(J,I)}function pY($){return typeof $==="function"}async function $I($,I){if(pY(I))return await I($);return I}async function nM($,I,M,G,J){let Q=J?.mode??"file",Y=cY(M),X=await $.readFile(I,"utf8"),R=Q==="line"?await hY(X,Y,G):await o6(X,Y,G),W=R!==X;if(W)await $.writeFile(I,R,"utf8");return W}function cY($){if(typeof $==="string"){let G=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(G,"g")}let I=$.flags.includes("g")?$.flags:`${$.flags}g`;return new RegExp($.source,I)}async function o6($,I,M){let G=Array.from($.matchAll(I)),J=$,Q=0;for(let Y of G){let X=Y[0]??"",R=Y.index??0,W=Y.slice(1),q=Y.groups,H=await $I({substring:X,captures:W,offset:R,input:$,groups:q},M),K=R+Q,O=K+X.length;J=J.slice(0,K)+H+J.slice(O),Q+=H.length-X.length}return J}async function hY($,I,M){let G=$.split(/(\r\n|\n)/),J="";for(let Q=0;Q<G.length;Q+=2){let Y=G[Q]??"",X=G[Q+1]??"",R=await o6(Y,I,M);J+=R+X}return J}import{z as e6}from"zod";var A$;((Y)=>{Y[Y.None=0]="None";Y[Y.Linux=1]="Linux";Y[Y.MacOS=2]="MacOS";Y[Y.Windows=4]="Windows";Y[Y.Unix=3]="Unix";Y[Y.All=7]="All"})(A$||={});var OI;((J)=>{J[J.None=0]="None";J[J.X86_64=1]="X86_64";J[J.Arm64=2]="Arm64";J[J.All=3]="All"})(OI||={});var $J=e6.number().int().min(0).max(7).refine(($)=>{return($&-8)===0},{message:"Must be a valid Platform value. Use `Platform.None`, `Platform.Linux`, `Platform.MacOS`, `Platform.Windows`, `Platform.Unix`, or `Platform.All`. You can combine values with a bitwise OR (e.g., `Platform.Linux | Platform.MacOS`)."}),IJ=e6.number().int().min(0).max(3).refine(($)=>{return($&-4)===0},{message:"Must be a valid Architecture value. Use `Architecture.None`, `Architecture.X86_64`, `Architecture.Arm64`, or `Architecture.All`. You can combine values with a bitwise OR (e.g., `Architecture.X86_64 | Architecture.Arm64`)."});function oI($,I){if(I===0)return $===0;return($&I)===I}function eI($,I){if(I===0)return $===0;return($&I)===I}function MJ($){switch($){case"darwin":return 2;case"linux":return 1;case"win32":return 4;default:return 0}}function GJ($){switch($){case"x64":return 1;case"arm64":return 2;default:return 0}}function II($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";case 0:return"none";default:return"unknown"}}function MI($){switch($){case 1:return"x86_64";case 2:return"arm64";case 0:return"none";default:return"unknown"}}import{z as L}from"zod";function mY($){let I=$?.enabled??!0,M=$?.ttl??86400000;return L.object({enabled:L.boolean().default(I),ttl:L.number().default(M)}).strict()}var iM=mY();function rM($){let{defaultHost:I,includeToken:M,includeUserAgent:G,defaultUserAgent:J="dotfiles-generator",tokenDefault:Q=""}=$;return L.object({host:L.string().default(I),cache:iM.default(iM.parse({})),token:L.string().default(M?Q:""),userAgent:L.string().default(G?J:"dotfiles-generator")}).strict()}var $G=L.object({homeDir:L.string().default("{HOME}"),dotfilesDir:L.string().default("{configFileDir}"),targetDir:L.string().default("{paths.generatedDir}/bin-default"),generatedDir:L.string().default("{paths.dotfilesDir}/.generated"),toolConfigsDir:L.string().default("{paths.dotfilesDir}/tools"),shellScriptsDir:L.string().default("{paths.generatedDir}/shell-scripts"),binariesDir:L.string().default("{paths.generatedDir}/binaries")}).strict(),IG=L.object({sudoPrompt:L.string().default("Please enter your password to continue:")}).strict(),MG=L.object({debug:L.string().default("")}).strict(),GG=L.object({checkOnRun:L.boolean().default(!0),checkInterval:L.number().default(86400)}).strict(),JG=rM({defaultHost:"https://api.github.com",includeToken:!0,includeUserAgent:!0}),JJ=rM({defaultHost:"https://crates.io"}),QJ=rM({defaultHost:"https://raw.githubusercontent.com"}),YJ=rM({defaultHost:"https://github.com"}),QG=L.object({cratesIo:JJ.default(JJ.parse({})),githubRaw:QJ.default(QJ.parse({})),githubRelease:YJ.default(YJ.parse({})),userAgent:L.string().default("dotfiles-generator")}).strict(),YG=L.object({timeout:L.number().default(300000),retryCount:L.number().default(3),retryDelay:L.number().default(1000),cache:iM.default(iM.parse({}))}).strict(),XG=L.object({catalog:L.object({generate:L.boolean().default(!0),filePath:L.string().default("{paths.dotfilesDir}/CATALOG.md")}).strict().default({generate:!0,filePath:"{paths.dotfilesDir}/CATALOG.md"}),shellInstall:L.object({zsh:L.string().optional(),bash:L.string().optional(),powershell:L.string().optional()}).strict().optional()}).strict(),lM=["macos","linux","windows"],aM=["x86_64","arm64"],gY=L.union([L.object({os:L.enum(lM),arch:L.enum(aM).optional()}).strict(),L.object({os:L.enum(lM).optional(),arch:L.enum(aM)}).strict()]),nY=L.object({paths:$G.required().default($G.parse({})),system:IG.required().default(IG.parse({})),logging:MG.required().default(MG.parse({})),updates:GG.required().default(GG.parse({})),github:JG.required().default(JG.parse({})),cargo:QG.required().default(QG.parse({})),downloader:YG.required().default(YG.parse({})),features:XG.default(XG.parse({}))}).strict(),iY=L.object({paths:$G.partial().optional(),system:IG.partial().optional(),logging:MG.partial().optional(),updates:GG.partial().optional(),github:JG.partial().optional(),cargo:QG.partial().optional(),downloader:YG.partial().optional(),features:XG.partial().optional()}).strict(),lY=L.object({match:L.array(gY).nonempty(),get config(){return iY.partial()}}).strict(),ZG=nY.extend({platform:L.array(lY).optional()}).strict(),XJ=L.object({configFilePath:L.string(),configFileDir:L.string()});var{Glob:$4}=globalThis.Bun;import VI from"path";function Z($){return $}var jI={VERBOSE:1,DEFAULT:3,QUIET:5},RG=["verbose","default","quiet"],ZJ={verbose:jI.VERBOSE,default:jI.DEFAULT,quiet:jI.QUIET};function RJ($){let I=$.toLowerCase();if(!(I in ZJ))throw Error(`Invalid log level: ${$}. Valid levels are: ${RG.join(", ")}`);return ZJ[I]}import{Logger as eY}from"tslog";var aY=/\.tool\.(ts|js)/,rY=/([^/\\]+\.tool\.(?:ts|js)):(\d+)/;function sY($){return aY.test($)}function tY($){let I=rY.exec($);if(!I)return null;return`${I[1]}:${I[2]}`}function oY($){if(!$)return[];let I=$.split(`
22
+ `),M=[];for(let G of I)if(sY(G)){let J=tY(G);if(J)M.push(J)}return M}function WJ($){let I=typeof $.stack==="string"?$.stack:void 0,M=oY(I);if(M.length===0)return null;return`(${M.join(", ")})`}function qJ($){return $ instanceof Error}function UJ($){let I=[],M=[...$.issues].toSorted((G,J)=>(G.path??[]).length-(J.path??[]).length);for(let G of M)if(I.push(`\u2716 ${G.message}`),G.path?.length){let J=G.path.map(String).join(".");I.push(` \u2192 at ${J}`)}return I}function HJ($){return`[${$}]`}class VM extends eY{_trace;constructor($){let M=($?.prefix??[]).map((G)=>String(G));if($?.context)M.push(HJ($.context));super({...$,prefix:M});this._trace=$?.trace===!0}isTracingEnabled(){return this._trace}filterErrorArgs($){if(this.isTracingEnabled())return $;let I=[];for(let M of $)if(qJ(M)){let G=WJ(M);if(G)I.push(G)}else I.push(M);return I}trace($,...I){return super.trace($,...I)}debug($,...I){return super.debug($,...I)}info($,...I){let M=this.filterErrorArgs(I);return super.info($,...M)}warn($,...I){let M=this.filterErrorArgs(I);return super.warn($,...M)}error($,...I){let M=this.filterErrorArgs(I);return super.error($,...M)}fatal($,...I){let M=this.filterErrorArgs(I);return super.fatal($,...M)}getSubLogger($){let I=[...this.settings.parentNames??[]];if(this.settings.name&&$?.name)I.push(this.settings.name);return new VM({...this.settings,...$,parentNames:I})}zodErrors($){let I=UJ($);for(let M of I)this.error(M)}setPrefix($){return this.settings.prefix=[HJ($)],this}}function WG($){let I=typeof $==="string"?{name:$}:{...$};I.level=I.level??jI.DEFAULT;let M=I.trace?"{{logLevelName}}\t{{filePathWithLine}} - ":"{{logLevelName}}\t",G=process.env.NO_COLOR==="1"||process.env.TERM==="dumb";return new VM({name:I.name,minLevel:I.level,trace:I.trace,prettyLogTemplate:M,stylePrettyLogs:!G,hideLogPositionForProduction:!1,prettyErrorTemplate:`
23
23
  {{errorName}} {{errorMessage}}
24
24
  error stack:
25
- {{errorStack}}`,prettyLogStyles:{logLevelName:{FATAL:["bold","red"],ERROR:["bold","red"],WARN:["bold","yellow"],INFO:["bold","blue"],DEBUG:["bold","white"],TRACE:["bold","white"]}},prettyInspectOptions:{breakLength:1/0,compact:!0}})}function KY($,M,J){if(M)return jM.QUIET;if(J)return jM.VERBOSE;return ZY($)}var M$={pluginAlreadyRegistered:($)=>W(`Plugin ${$} is already registered, replacing...`),pluginRegistered:($,M,J)=>W(`Registered installer plugin: ${$} (${M} v${J})`),pluginRegistrationFailed:($)=>W(`Failed to register plugin ${$}`),schemasComposed:($,M)=>W(`Composed schemas from ${$} plugins: ${M}`),noPluginForMethod:($,M)=>W(`No plugin registered for installation method: ${$}. Available methods: ${M}`),pluginValidationFailed:($)=>W(`Plugin validation failed: ${$}`),validationFailed:($,M)=>W(`Plugin validation failed for ${$}: ${M}`),validationWarning:($,M)=>W(`Validation warning for ${$}: ${M}`),delegatingToPlugin:($)=>W(`Delegating installation to plugin: ${$}`),validationCacheCleared:()=>W("Validation cache cleared"),cleaningUpPlugins:()=>W("Cleaning up plugins..."),pluginCleanedUp:($)=>W(`Cleaned up plugin: ${$}`),pluginCleanupFailed:($)=>W(`Failed to cleanup plugin ${$}`),pluginCleanupComplete:()=>W("Plugin cleanup complete"),replaceInFileNoMatch:($,M)=>W(`Could not find '${$}' in ${M}`),resolveNoMatches:($)=>W(`No matches found for pattern: ${$}`),resolveMultipleMatches:($,M,J)=>W(`Pattern '${$}' matched ${M} paths (expected exactly 1): ${J}`)};class i0 extends Error{constructor($){super($);this.name="ResolveError"}}function IQ($,M){let J=$.getSubLogger({context:M});return{trace:(Y)=>{J.trace(Y)},debug:(Y)=>{J.debug(Y)},info:(Y)=>{J.info(Y)},warn:(Y)=>{J.warn(Y)},error:(Y,G)=>{if(G!==void 0)J.error(Y,G);else J.error(Y)}}}function R0($,M,J,Q,Y,G){let X=VM.join($.paths.binariesDir,J,"current"),Z={platform:M.platform,arch:M.arch,homeDir:$.paths.homeDir,hostname:M.hostname},q=async(H,_,O,B)=>{let j=await c0(Y,H,_,O,B);if(!j&&B?.errorMessage){let V=_ instanceof RegExp?_.source:_;G.error(M$.replaceInFileNoMatch(V,H))}return j},I=(H)=>{let _=VM.isAbsolute(H),O,B;if(_){let A=VM.dirname(H),T=VM.basename(H);if(/[*?[\]{]/.test(A)){let w=H.split(VM.sep),u=[],i=[],E=!1;for(let g of w)if(!E&&!/[*?[\]{]/.test(g))u.push(g);else E=!0,i.push(g);O=u.join(VM.sep)||"/",B=i.join(VM.sep)}else O=A,B=T}else O=Q,B=H;let j=new i7(B),V=[];for(let A of j.scanSync({cwd:O,onlyFiles:!1}))V.push(VM.join(O,A));if(V.length===0)throw G.error(M$.resolveNoMatches(H)),new i0(`No matches found for pattern: ${H}`);if(V.length>1){let A=V.slice(0,5).join(", ")+(V.length>5?", ...":"");throw G.error(M$.resolveMultipleMatches(H,V.length,A)),new i0(`Pattern '${H}' matched ${V.length} paths (expected exactly 1)`)}let D=V[0];if(D===void 0)throw G.error(M$.resolveNoMatches(H)),new i0(`No matches found for pattern: ${H}`);return D},U=IQ(G,J);return{toolName:J,toolDir:Q,currentDir:X,projectConfig:$,systemInfo:Z,replaceInFile:q,resolve:I,log:U}}import{z as HY}from"zod";class UQ{plugins=new Map;validationCache=new Map;composedToolConfigSchema;composedInstallParamsSchema;logger;schemasComposed=!1;eventHandlers=[];constructor($){this.logger=$.getSubLogger({name:"InstallerPluginRegistry"})}onEvent($){this.eventHandlers.push($)}async emitEvent($){for(let M of this.eventHandlers)await M($)}async register($){let{method:M}=$;try{if(!M||typeof M!=="string")throw Error("Plugin must have a valid method name");if(this.schemasComposed)throw Error("Cannot register plugins after schemas have been composed");if(this.plugins.has(M))this.logger.warn(M$.pluginAlreadyRegistered(M));if($.initialize)await $.initialize();this.plugins.set(M,$),this.logger.debug(M$.pluginRegistered(M,$.displayName,$.version))}catch(J){throw this.logger.error(M$.pluginRegistrationFailed(M),J),Error(`Plugin registration failed: ${M}`,{cause:J})}}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getAll(){return Array.from(this.plugins.values())}getMethods(){return Array.from(this.plugins.keys())}getExternallyManagedMethods(){let $=new Set;for(let[M,J]of this.plugins)if(J.externallyManaged)$.add(M);return $}getMissingBinaryMessagesByMethod(){let $=new Map;for(let[M,J]of this.plugins)if(J.missingBinaryMessage)$.set(M,J.missingBinaryMessage);return $}composeSchemas(){let $=this.getAll();if($.length===0)throw Error("No plugins registered");let M=$.map((Q)=>Q.toolConfigSchema);if(M.length===1)this.composedToolConfigSchema=M[0];else{let[Q,...Y]=M;this.composedToolConfigSchema=HY.discriminatedUnion("installationMethod",[Q,...Y])}let J=$.map((Q)=>Q.paramsSchema);if(J.length===1)this.composedInstallParamsSchema=J[0];else{let[Q,Y,...G]=J;this.composedInstallParamsSchema=HY.union([Q,Y,...G])}this.schemasComposed=!0,this.logger.info(M$.schemasComposed($.length,this.getMethods().join(", ")))}getToolConfigSchema(){if(!this.composedToolConfigSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedToolConfigSchema}getInstallParamsSchema(){if(!this.composedInstallParamsSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedInstallParamsSchema}async validatePlugin($,M,J){if(!$.validate)return null;let Q=this.validationCache.get($.method);if(!Q){if(Q=await $.validate(M),$.staticValidation)this.validationCache.set($.method,Q)}if(!Q.valid){let Y=`Plugin validation failed: ${Q.errors?.join(", ")}`;return J.error(M$.validationFailed($.method,Q.errors?.join(", ")??"Unknown error")),{success:!1,error:Y}}if(Q.warnings&&Q.warnings.length>0)for(let Y of Q.warnings)J.warn(M$.validationWarning($.method,Y));return null}async install($,M,J,Q,Y,G){let X=$.getSubLogger({name:"InstallerPluginRegistry"}).getSubLogger({name:"install"}),Z=this.get(M);if(!Z){let I=`No plugin registered for installation method: ${M}. Available methods: ${this.getMethods().join(", ")}`;return X.error(M$.noPluginForMethod(M,this.getMethods().join(", "))),{success:!1,error:I}}let q=await this.validatePlugin(Z,Y,X);if(q)return q;return X.debug(M$.delegatingToPlugin(M)),await Z.install(J,Q,Y,G,X)}clearValidationCache(){this.validationCache.clear(),this.logger.debug(M$.validationCacheCleared())}async cleanup(){let $=this.logger.getSubLogger({name:"cleanup"});$.info(M$.cleaningUpPlugins());let M=this.getAll();for(let J of M)if(J.cleanup)try{await J.cleanup(),$.debug(M$.pluginCleanedUp(J.method))}catch(Q){$.error(M$.pluginCleanupFailed(J.method),Q)}$.info(M$.pluginCleanupComplete())}}import{z as AY}from"zod";import{z as zM}from"zod";import{z as l7}from"zod";var O0=l7.custom(($)=>typeof $==="function","Must be a function");var r=zM.object({auto:zM.boolean().optional(),env:zM.custom().optional(),hooks:zM.object({"before-install":zM.array(O0).optional(),"after-download":zM.array(O0).optional(),"after-extract":zM.array(O0).optional(),"after-install":zM.array(O0).optional()}).partial().optional()}).strict();import{z as jQ}from"zod";import{z as d$}from"zod";import{z as a7}from"zod";import{z as V$}from"zod";import{z as KQ}from"zod";var _Y=KQ.object({kind:KQ.enum(["once","always"]),value:KQ.string()});var l0=V$.object({scripts:V$.array(_Y).optional(),aliases:V$.record(V$.string(),V$.string()).optional(),env:V$.record(V$.string(),V$.string()).optional(),functions:V$.record(V$.string(),V$.string()).optional(),paths:V$.array(V$.unknown()).optional(),completions:V$.unknown().optional()}).strict();var RY=a7.object({zsh:l0.optional(),bash:l0.optional(),powershell:l0.optional()}).strict();import{z as HQ}from"zod";var OY=HQ.object({enabled:HQ.boolean().optional(),constraint:HQ.string().optional()}).strict();import{z as _Q}from"zod";var Z$=_Q.object({name:_Q.string().min(1),pattern:_Q.string().min(1)}).strict();import{z as RQ}from"zod";var jY=RQ.object({source:RQ.string().min(1),target:RQ.string().min(1)}).strict();import{z as OQ}from"zod";var VY=OQ.object({source:OQ.string().min(1),target:OQ.string().min(1)}).strict();var a0=d$.object({binaries:d$.array(d$.union([d$.string().min(1),Z$])).optional(),dependencies:d$.array(d$.string().min(1)).optional(),disabled:d$.boolean().optional(),hostname:d$.string().optional(),version:d$.string().optional(),shellConfigs:RY.optional(),symlinks:d$.array(VY).optional(),copies:d$.array(jY).optional(),updateCheck:OY.optional()}).strict();var zY=a0.extend({name:jQ.string().min(1),version:jQ.string(),configFilePath:jQ.string().optional()}).strict();import{z as s7}from"zod";import{z as BY}from"zod";var DY=BY.object({platforms:o6,architectures:e6.optional(),config:BY.unknown()}).strict();var t=zY.extend({platformConfigs:s7.array(DY).optional()});import{z as j0}from"zod";var fZ=j0.object({source:j0.string().min(1).optional(),url:j0.string().url().optional(),cmd:j0.string().min(1).optional(),bin:j0.string().optional()}).strict().refine(($)=>{let M=Boolean($.source),J=Boolean($.cmd),Q=Boolean($.url);if(J&&Q)return!1;if(J&&M)return!1;if(!M&&!J&&!Q)return!1;return!0},{message:"Invalid completion config: use 'source' alone, 'cmd' alone, 'url' alone, or 'url' with 'source'. Cannot combine 'cmd' with 'url' or 'source'."});var JW=a0.extend({installationMethod:AY.string().optional(),installParams:AY.unknown().optional()}).strict();var oM=Symbol("loggingShellBrand");function FY($,M){let J=(Q,...Y)=>{let G=Q[0]||"";for(let X=0;X<Y.length;X++){let Z=Y[X];if(Array.isArray(Z))G+=Z.map((q)=>EY(String(q))).join(" ");else G+=EY(String(Z));G+=Q[X+1]||""}return M.info(W(`$ ${G}`)),$(Q,...Y)};return Object.assign(J,$),Object.defineProperty(J,oM,{value:!0,enumerable:!1}),J}function EY($){if($===""||/[\s"'`$\\]/.test($))return`'${$.replace(/'/g,"'\\''")}'`;return $}class VQ extends Error{code;stdout;stderr;name="ShellError";constructor($,M,J,Q){super(`Exited with code: ${$}`);this.code=$;this.stdout=M;this.stderr=J;if(J)this.message+=`
26
- ${J}`}}function W$($={}){return(J,...Q)=>{let Y=typeof J==="string"?J:o7(J,Q);return r7(Y,$)}}function r7($,M){let J={...M},Q=!1,Y=null,G=async()=>{if(Y)return Y;return Q=!0,Y=t7($,J),Y},X={cwd(Z){if(Q)throw Error("Cannot modify command after execution");return J={...J,cwd:Z},X},env(Z){if(Q)throw Error("Cannot modify command after execution");return J={...J,env:{...J.env,...Z}},X},quiet(){if(Q)throw Error("Cannot modify command after execution");return J={...J,quiet:!0},X},noThrow(){if(Q)throw Error("Cannot modify command after execution");return J={...J,noThrow:!0},X},async text(){return(await G()).stdout.replace(/\r?\n$/,"")},async json(){let Z=await G();return JSON.parse(Z.stdout)},async lines(){return(await G()).stdout.replace(/\r?\n$/,"").split(`
27
- `)},async bytes(){let Z=await G();return new TextEncoder().encode(Z.stdout)},then(Z,q){return G().then(Z,q)}};return X}async function t7($,M){let{cwd:J,env:Q,logger:Y,noThrow:G,skipCommandLog:X}=M;if(Y&&!X)Y.info(W(`$ ${$}`));let Z={...process.env};if(Q)for(let[H,_]of Object.entries(Q))if(_===void 0)delete Z[H];else Z[H]=_;let q=Bun.spawn(["sh","-c",$],{cwd:J,env:Z,stdout:"pipe",stderr:"pipe"}),[I,U]=await Promise.all([LY(q.stdout,Y?(H)=>Y.info(W(`| ${H}`)):void 0),LY(q.stderr,Y?(H)=>Y.info(W(`| ${H}`)):void 0)]),K=await q.exited;if(K!==0&&!G)throw new VQ(K,I,U,$);return{code:K,stdout:I,stderr:U}}async function LY($,M){let J=$.getReader(),Q=new TextDecoder,Y=[],G="";while(!0){let{done:X,value:Z}=await J.read();if(X)break;let q=Q.decode(Z,{stream:!0});if(Y.push(q),M){G+=q;let I=G.split(`
28
- `);G=I.pop()??"";for(let U of I)if(U)M(U)}}if(M&&G)M(G);return Y.join("")}function o7($,M){let J=$[0]||"";for(let Q=0;Q<M.length;Q++){let Y=M[Q];if(Array.isArray(Y))J+=Y.map(xY).join(" ");else J+=xY(Y);J+=$[Q+1]||""}return J}function xY($){let M=String($);if(/^[a-zA-Z0-9_\-./=:@]+$/.test(M))return M;return`'${M.replace(/'/g,"'\\''")}'`}function s0($){return typeof $==="function"&&oM in $}function TY($){return{kind:"once",value:$}}function kY($){return{kind:"always",value:$}}function n$($){return{kind:"raw",value:$}}function r0($){return $.kind==="once"}function t0($){return $.kind==="always"}function o0($){return $.kind==="raw"}function e0($){return $.value}import{randomUUID as CX}from"crypto";import J0 from"path";import bX from"path";var l={directoryDeletionError:()=>W("Error tracking directory deletion %s: %s"),rmdirTracked:()=>W("Tracked rmdir operation: %s"),operationRecorded:()=>W("Recorded %s operation for %s: %s"),operationsRetrieved:()=>W("Retrieved %d operations with filter: %o"),fileStatesComputed:()=>W("Computed %d file states for tool: %s"),fileStateComputed:()=>W("Computed file state for %s: %s"),noOperationsFound:()=>W("No operations found for file: %s"),toolsFound:()=>W("Found %d registered tools"),operationsRemoved:()=>W("Removed %d operations for tool: %s"),compactionComplete:()=>W("Compaction complete: %d -> %d operations"),validationComplete:()=>W("Validation complete: %d issues found, %d repaired"),registryClosed:()=>W("Closed SQLite file registry"),schemaInitialized:()=>W("Schema initialization complete"),fileCreated:($)=>W(`write ${$}`),fileUpdated:($)=>W(`write ${$}`),fileRemoved:($)=>W(`rm ${$}`),fileMoved:($,M)=>W(`mv ${$} ${M}`),fileCopied:($,M)=>W(`cp ${$} ${M}`),symlinkCreated:($,M)=>W(`ln -s ${M} ${$}`),permissionsChanged:($,M)=>W(`chmod ${M} ${$}`),directoryCreated:($)=>W(`mkdir ${$}`)};class zQ{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"SqliteFileRegistry"}),this.db=M,this.initializeSchema()}async recordOperation($){let M=this.logger.getSubLogger({name:"recordOperation"}),J=this.db.prepare(`
25
+ {{errorStack}}`,prettyLogStyles:{logLevelName:{FATAL:["bold","red"],ERROR:["bold","red"],WARN:["bold","yellow"],INFO:["bold","blue"],DEBUG:["bold","white"],TRACE:["bold","white"]}},prettyInspectOptions:{breakLength:1/0,compact:!0}})}function KJ($,I,M){if(I)return jI.QUIET;if(M)return jI.VERBOSE;return RJ($)}var M$={pluginAlreadyRegistered:($)=>Z(`Plugin ${$} is already registered, replacing...`),pluginRegistered:($,I,M)=>Z(`Registered installer plugin: ${$} (${I} v${M})`),pluginRegistrationFailed:($)=>Z(`Failed to register plugin ${$}`),schemasComposed:($,I)=>Z(`Composed schemas from ${$} plugins: ${I}`),noPluginForMethod:($,I)=>Z(`No plugin registered for installation method: ${$}. Available methods: ${I}`),pluginValidationFailed:($)=>Z(`Plugin validation failed: ${$}`),validationFailed:($,I)=>Z(`Plugin validation failed for ${$}: ${I}`),validationWarning:($,I)=>Z(`Validation warning for ${$}: ${I}`),delegatingToPlugin:($)=>Z(`Delegating installation to plugin: ${$}`),validationCacheCleared:()=>Z("Validation cache cleared"),cleaningUpPlugins:()=>Z("Cleaning up plugins..."),pluginCleanedUp:($)=>Z(`Cleaned up plugin: ${$}`),pluginCleanupFailed:($)=>Z(`Failed to cleanup plugin ${$}`),pluginCleanupComplete:()=>Z("Plugin cleanup complete"),replaceInFileNoMatch:($,I)=>Z(`Could not find '${$}' in ${I}`),resolveNoMatches:($)=>Z(`No matches found for pattern: ${$}`),resolveMultipleMatches:($,I,M)=>Z(`Pattern '${$}' matched ${I} paths (expected exactly 1): ${M}`)};class sM extends Error{constructor($){super($);this.name="ResolveError"}}function qG($,I){let M=$.getSubLogger({context:I});return{trace:(J)=>{M.trace(J)},debug:(J)=>{M.debug(J)},info:(J)=>{M.info(J)},warn:(J)=>{M.warn(J)},error:(J,Q)=>{if(Q!==void 0)M.error(J,Q);else M.error(J)}}}function zM($,I,M,G,J,Q){let Y=VI.join($.paths.binariesDir,M,"current"),X={platform:I.platform,arch:I.arch,homeDir:$.paths.homeDir,hostname:I.hostname},R=async(H,K,O,B)=>{let j=await nM(J,H,K,O,B);if(!j&&B?.errorMessage){let V=K instanceof RegExp?K.source:K;Q.error(M$.replaceInFileNoMatch(V,H))}return j},W=(H)=>{let K=VI.isAbsolute(H),O,B;if(K){let A=VI.dirname(H),T=VI.basename(H);if(/[*?[\]{]/.test(A)){let w=H.split(VI.sep),u=[],h=[],D=!1;for(let m of w)if(!D&&!/[*?[\]{]/.test(m))u.push(m);else D=!0,h.push(m);O=u.join(VI.sep)||"/",B=h.join(VI.sep)}else O=A,B=T}else O=G,B=H;let j=new $4(B),V=[];for(let A of j.scanSync({cwd:O,onlyFiles:!1}))V.push(VI.join(O,A));if(V.length===0)throw Q.error(M$.resolveNoMatches(H)),new sM(`No matches found for pattern: ${H}`);if(V.length>1){let A=V.slice(0,5).join(", ")+(V.length>5?", ...":"");throw Q.error(M$.resolveMultipleMatches(H,V.length,A)),new sM(`Pattern '${H}' matched ${V.length} paths (expected exactly 1)`)}let x=V[0];if(x===void 0)throw Q.error(M$.resolveNoMatches(H)),new sM(`No matches found for pattern: ${H}`);return x},q=qG(Q,M);return{toolName:M,toolDir:G,currentDir:Y,projectConfig:$,systemInfo:X,replaceInFile:R,resolve:W,log:q}}import{z as _J}from"zod";class UG{plugins=new Map;validationCache=new Map;composedToolConfigSchema;composedInstallParamsSchema;logger;schemasComposed=!1;eventHandlers=[];constructor($){this.logger=$.getSubLogger({name:"InstallerPluginRegistry"})}onEvent($){this.eventHandlers.push($)}async emitEvent($){for(let I of this.eventHandlers)await I($)}async register($){let{method:I}=$;try{if(!I||typeof I!=="string")throw Error("Plugin must have a valid method name");if(this.schemasComposed)throw Error("Cannot register plugins after schemas have been composed");if(this.plugins.has(I))this.logger.warn(M$.pluginAlreadyRegistered(I));if($.initialize)await $.initialize();this.plugins.set(I,$),this.logger.debug(M$.pluginRegistered(I,$.displayName,$.version))}catch(M){throw this.logger.error(M$.pluginRegistrationFailed(I),M),Error(`Plugin registration failed: ${I}`,{cause:M})}}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getAll(){return Array.from(this.plugins.values())}getMethods(){return Array.from(this.plugins.keys())}getExternallyManagedMethods(){let $=new Set;for(let[I,M]of this.plugins)if(M.externallyManaged)$.add(I);return $}getMissingBinaryMessagesByMethod(){let $=new Map;for(let[I,M]of this.plugins)if(M.missingBinaryMessage)$.set(I,M.missingBinaryMessage);return $}composeSchemas(){let $=this.getAll();if($.length===0)throw Error("No plugins registered");let I=$.map((G)=>G.toolConfigSchema);if(I.length===1)this.composedToolConfigSchema=I[0];else{let[G,...J]=I;this.composedToolConfigSchema=_J.discriminatedUnion("installationMethod",[G,...J])}let M=$.map((G)=>G.paramsSchema);if(M.length===1)this.composedInstallParamsSchema=M[0];else{let[G,J,...Q]=M;this.composedInstallParamsSchema=_J.union([G,J,...Q])}this.schemasComposed=!0,this.logger.info(M$.schemasComposed($.length,this.getMethods().join(", ")))}getToolConfigSchema(){if(!this.composedToolConfigSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedToolConfigSchema}getInstallParamsSchema(){if(!this.composedInstallParamsSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedInstallParamsSchema}async validatePlugin($,I,M){if(!$.validate)return null;let G=this.validationCache.get($.method);if(!G){if(G=await $.validate(I),$.staticValidation)this.validationCache.set($.method,G)}if(!G.valid){let J=`Plugin validation failed: ${G.errors?.join(", ")}`;return M.error(M$.validationFailed($.method,G.errors?.join(", ")??"Unknown error")),{success:!1,error:J}}if(G.warnings&&G.warnings.length>0)for(let J of G.warnings)M.warn(M$.validationWarning($.method,J));return null}async install($,I,M,G,J,Q){let Y=$.getSubLogger({name:"InstallerPluginRegistry"}).getSubLogger({name:"install"}),X=this.get(I);if(!X){let W=`No plugin registered for installation method: ${I}. Available methods: ${this.getMethods().join(", ")}`;return Y.error(M$.noPluginForMethod(I,this.getMethods().join(", "))),{success:!1,error:W}}let R=await this.validatePlugin(X,J,Y);if(R)return R;return Y.debug(M$.delegatingToPlugin(I)),await X.install(M,G,J,Q,Y)}clearValidationCache(){this.validationCache.clear(),this.logger.debug(M$.validationCacheCleared())}async cleanup(){let $=this.logger.getSubLogger({name:"cleanup"});$.info(M$.cleaningUpPlugins());let I=this.getAll();for(let M of I)if(M.cleanup)try{await M.cleanup(),$.debug(M$.pluginCleanedUp(M.method))}catch(G){$.error(M$.pluginCleanupFailed(M.method),G)}$.info(M$.pluginCleanupComplete())}}import{z as FJ}from"zod";import{z as zI}from"zod";import{z as I4}from"zod";var BM=I4.custom(($)=>typeof $==="function","Must be a function");var s=zI.object({auto:zI.boolean().optional(),env:zI.custom().optional(),hooks:zI.object({"before-install":zI.array(BM).optional(),"after-download":zI.array(BM).optional(),"after-extract":zI.array(BM).optional(),"after-install":zI.array(BM).optional()}).partial().optional()}).strict();import{z as VG}from"zod";import{z as p$}from"zod";import{z as M4}from"zod";import{z as V$}from"zod";import{z as HG}from"zod";var OJ=HG.object({kind:HG.enum(["once","always"]),value:HG.string()});var tM=V$.object({scripts:V$.array(OJ).optional(),aliases:V$.record(V$.string(),V$.string()).optional(),env:V$.record(V$.string(),V$.string()).optional(),functions:V$.record(V$.string(),V$.string()).optional(),paths:V$.array(V$.unknown()).optional(),completions:V$.unknown().optional()}).strict();var jJ=M4.object({zsh:tM.optional(),bash:tM.optional(),powershell:tM.optional()}).strict();import{z as KG}from"zod";var VJ=KG.object({enabled:KG.boolean().optional(),constraint:KG.string().optional()}).strict();import{z as _G}from"zod";var X$=_G.object({name:_G.string().min(1),pattern:_G.string().min(1)}).strict();import{z as OG}from"zod";var zJ=OG.object({source:OG.string().min(1),target:OG.string().min(1)}).strict();import{z as jG}from"zod";var BJ=jG.object({source:jG.string().min(1),target:jG.string().min(1)}).strict();var oM=p$.object({binaries:p$.array(p$.union([p$.string().min(1),X$])).optional(),dependencies:p$.array(p$.string().min(1)).optional(),disabled:p$.boolean().optional(),hostname:p$.string().optional(),version:p$.string().optional(),shellConfigs:jJ.optional(),symlinks:p$.array(BJ).optional(),copies:p$.array(zJ).optional(),updateCheck:VJ.optional()}).strict();var xJ=oM.extend({name:VG.string().min(1),version:VG.string(),configFilePath:VG.string().optional()}).strict();import{z as G4}from"zod";import{z as DJ}from"zod";var AJ=DJ.object({platforms:$J,architectures:IJ.optional(),config:DJ.unknown()}).strict();var t=xJ.extend({platformConfigs:G4.array(AJ).optional()});import{z as xM}from"zod";var r5=xM.object({source:xM.string().min(1).optional(),url:xM.string().url().optional(),cmd:xM.string().min(1).optional(),bin:xM.string().optional()}).strict().refine(($)=>{let I=Boolean($.source),M=Boolean($.cmd),G=Boolean($.url);if(M&&G)return!1;if(M&&I)return!1;if(!I&&!M&&!G)return!1;return!0},{message:"Invalid completion config: use 'source' alone, 'cmd' alone, 'url' alone, or 'url' with 'source'. Cannot combine 'cmd' with 'url' or 'source'."});var UZ=oM.extend({installationMethod:FJ.string().optional(),installParams:FJ.unknown().optional()}).strict();var $M=Symbol("loggingShellBrand");function EJ($,I){let M=(G,...J)=>{let Q=G[0]||"";for(let Y=0;Y<J.length;Y++){let X=J[Y];if(Array.isArray(X))Q+=X.map((R)=>LJ(String(R))).join(" ");else Q+=LJ(String(X));Q+=G[Y+1]||""}return I.info(Z(`$ ${Q}`)),$(G,...J)};return Object.assign(M,$),Object.defineProperty(M,$M,{value:!0,enumerable:!1}),M}function LJ($){if($===""||/[\s"'`$\\]/.test($))return`'${$.replace(/'/g,"'\\''")}'`;return $}class zG extends Error{code;stdout;stderr;name="ShellError";constructor($,I,M,G){super(`Exited with code: ${$}`);this.code=$;this.stdout=I;this.stderr=M;if(M)this.message+=`
26
+ ${M}`}}function Z$($={}){return(M,...G)=>{let J=typeof M==="string"?M:Y4(M,G);return J4(J,$)}}function J4($,I){let M={...I},G=!1,J=null,Q=async()=>{if(J)return J;return G=!0,J=Q4($,M),J},Y={cwd(X){if(G)throw Error("Cannot modify command after execution");return M={...M,cwd:X},Y},env(X){if(G)throw Error("Cannot modify command after execution");return M={...M,env:{...M.env,...X}},Y},quiet(){if(G)throw Error("Cannot modify command after execution");return M={...M,quiet:!0},Y},noThrow(){if(G)throw Error("Cannot modify command after execution");return M={...M,noThrow:!0},Y},async text(){return(await Q()).stdout.replace(/\r?\n$/,"")},async json(){let X=await Q();return JSON.parse(X.stdout)},async lines(){return(await Q()).stdout.replace(/\r?\n$/,"").split(`
27
+ `)},async bytes(){let X=await Q();return new TextEncoder().encode(X.stdout)},then(X,R){return Q().then(X,R)}};return Y}async function Q4($,I){let{cwd:M,env:G,logger:J,noThrow:Q,skipCommandLog:Y}=I;if(J&&!Y)J.info(Z(`$ ${$}`));let X=Object.fromEntries(Object.entries(process.env).filter((H)=>typeof H[1]==="string"));if(G)for(let[H,K]of Object.entries(G))if(K===void 0)delete X[H];else X[H]=K;let R=Bun.spawn(["sh","-c",$],{cwd:M,env:X,stdout:"pipe",stderr:"pipe"}),[W,q]=await Promise.all([TJ(R.stdout,J?(H)=>J.info(Z(`| ${H}`)):void 0),TJ(R.stderr,J?(H)=>J.info(Z(`| ${H}`)):void 0)]),U=await R.exited;if(U!==0&&!Q)throw new zG(U,W,q,$);return{code:U,stdout:W,stderr:q}}async function TJ($,I){let M=$.getReader(),G=new TextDecoder,J=[],Q="";while(!0){let{done:Y,value:X}=await M.read();if(Y)break;let R=G.decode(X,{stream:!0});if(J.push(R),I){Q+=R;let W=Q.split(`
28
+ `);Q=W.pop()??"";for(let q of W)if(q)I(q)}}if(I&&Q)I(Q);return J.join("")}function Y4($,I){let M=$[0]||"";for(let G=0;G<I.length;G++){let J=I[G];if(Array.isArray(J))M+=J.map(SJ).join(" ");else M+=SJ(J);M+=$[G+1]||""}return M}function SJ($){let I=String($);if(/^[a-zA-Z0-9_\-./=:@]+$/.test(I))return I;return`'${I.replace(/'/g,"'\\''")}'`}function eM($){return typeof $==="function"&&$M in $}function kJ($){return{kind:"once",value:$}}function wJ($){return{kind:"always",value:$}}function a$($){return{kind:"raw",value:$}}function $0($){return $.kind==="once"}function I0($){return $.kind==="always"}function M0($){return $.kind==="raw"}function G0($){return $.value}import{randomUUID as g4}from"crypto";import AI from"path";import f4 from"path";var i={directoryDeletionError:()=>Z("Error tracking directory deletion %s: %s"),rmdirTracked:()=>Z("Tracked rmdir operation: %s"),operationRecorded:()=>Z("Recorded %s operation for %s: %s"),operationsRetrieved:()=>Z("Retrieved %d operations with filter: %o"),fileStatesComputed:()=>Z("Computed %d file states for tool: %s"),fileStateComputed:()=>Z("Computed file state for %s: %s"),noOperationsFound:()=>Z("No operations found for file: %s"),toolsFound:()=>Z("Found %d registered tools"),operationsRemoved:()=>Z("Removed %d operations for tool: %s"),compactionComplete:()=>Z("Compaction complete: %d -> %d operations"),validationComplete:()=>Z("Validation complete: %d issues found, %d repaired"),registryClosed:()=>Z("Closed SQLite file registry"),schemaInitialized:()=>Z("Schema initialization complete"),fileCreated:($)=>Z(`write ${$}`),fileUpdated:($)=>Z(`write ${$}`),fileRemoved:($)=>Z(`rm ${$}`),fileMoved:($,I)=>Z(`mv ${$} ${I}`),fileCopied:($,I)=>Z(`cp ${$} ${I}`),symlinkCreated:($,I)=>Z(`ln -s ${I} ${$}`),permissionsChanged:($,I)=>Z(`chmod ${I} ${$}`),directoryCreated:($)=>Z(`mkdir ${$}`)};class BG{db;logger;constructor($,I){this.logger=$.getSubLogger({name:"SqliteFileRegistry"}),this.db=I,this.initializeSchema()}async recordOperation($){let I=this.logger.getSubLogger({name:"recordOperation"}),M=this.db.prepare(`
29
29
  INSERT INTO file_operations (
30
30
  tool_name, operation_type, file_path, target_path, file_type,
31
31
  metadata, size_bytes, permissions, created_at, operation_id
32
32
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
33
- `),Q=Date.now(),Y=$.metadata?JSON.stringify($.metadata):null;J.run($.toolName,$.operationType,$.filePath,$.targetPath||null,$.fileType,Y,$.sizeBytes||null,$.permissions||null,Q,$.operationId),M.debug(l.operationRecorded(),$.operationType,$.toolName,$.filePath)}async getOperations($={}){let M=this.logger.getSubLogger({name:"getOperations"}),J="SELECT * FROM file_operations WHERE 1=1",Q=[];if($.toolName)J+=" AND tool_name = ?",Q.push($.toolName);if($.operationType)J+=" AND operation_type = ?",Q.push($.operationType);if($.fileType)J+=" AND file_type = ?",Q.push($.fileType);if($.filePath)J+=" AND file_path = ?",Q.push($.filePath);if($.createdAfter)J+=" AND created_at > ?",Q.push($.createdAfter);if($.createdBefore)J+=" AND created_at < ?",Q.push($.createdBefore);if($.operationId)J+=" AND operation_id = ?",Q.push($.operationId);J+=" ORDER BY created_at DESC, id DESC";let Y=this.db.prepare(J),G=Q.length>0?Y.all(...Q):Y.all();return M.debug(l.operationsRetrieved(),G.length,$),G.map((X)=>({id:X.id,toolName:X.tool_name,operationType:X.operation_type,filePath:X.file_path,targetPath:X.target_path??void 0,fileType:X.file_type,metadata:X.metadata?JSON.parse(X.metadata):void 0,sizeBytes:X.size_bytes??void 0,permissions:X.permissions?parseInt(X.permissions,10):void 0,createdAt:parseInt(X.created_at,10),operationId:X.operation_id}))}async getFileStatesForTool($){let M=this.logger.getSubLogger({name:"getFileStatesForTool"}),J=await this.getOperations({toolName:$}),Q=new Map;for(let G of[...J].toReversed())if(G.operationType==="rm")Q.delete(G.filePath);else Q.set(G.filePath,{filePath:G.filePath,toolName:G.toolName,fileType:G.fileType,lastOperation:G.operationType,targetPath:G.targetPath,lastModified:G.createdAt,metadata:G.metadata,sizeBytes:G.sizeBytes,permissions:G.permissions});let Y=Array.from(Q.values());return M.debug(l.fileStatesComputed(),Y.length,$),Y}async getFileState($){let M=this.logger.getSubLogger({name:"getFileState"}),J=await this.getOperations({filePath:$});if(J.length===0)return M.debug(l.noOperationsFound(),$),null;let Q=null;for(let Y of[...J].toReversed())if(Y.operationType==="rm")Q=null;else Q={filePath:Y.filePath,toolName:Y.toolName,fileType:Y.fileType,lastOperation:Y.operationType,targetPath:Y.targetPath,lastModified:Y.createdAt,metadata:Y.metadata,sizeBytes:Y.sizeBytes,permissions:Y.permissions};return M.debug(l.fileStateComputed(),$,Q?"active":"deleted"),Q}async getRegisteredTools(){let $=this.logger.getSubLogger({name:"getRegisteredTools"}),M=await this.getOperations(),J=new Map;for(let Y of M)if(!J.has(Y.filePath))J.set(Y.filePath,Y);let Q=Array.from(new Set(Array.from(J.values()).filter((Y)=>Y.operationType!=="rm").map((Y)=>Y.toolName))).toSorted();return $.debug(l.toolsFound(),Q.length),Q}async removeToolOperations($){let M=this.logger.getSubLogger({name:"removeToolOperations"}),Q=this.db.prepare("DELETE FROM file_operations WHERE tool_name = ?").run($);M.debug(l.operationsRemoved(),Q.changes,$)}async compact(){let $=this.logger.getSubLogger({name:"compact"}),M=await this.getStats(),J=await this.getOperations({operationType:"rm"});for(let Y of J)if(!await this.getFileState(Y.filePath))this.db.prepare("DELETE FROM file_operations WHERE file_path = ?").run(Y.filePath);let Q=await this.getStats();$.debug(l.compactionComplete(),M.totalOperations,Q.totalOperations)}async validate(){let $=this.logger.getSubLogger({name:"validate"}),M=[],J=[],Q=this.db.prepare(`
33
+ `),G=Date.now(),J=$.metadata?JSON.stringify($.metadata):null;M.run($.toolName,$.operationType,$.filePath,$.targetPath||null,$.fileType,J,$.sizeBytes||null,$.permissions||null,G,$.operationId),I.debug(i.operationRecorded(),$.operationType,$.toolName,$.filePath)}async getOperations($={}){let I=this.logger.getSubLogger({name:"getOperations"}),M="SELECT * FROM file_operations WHERE 1=1",G=[];if($.toolName)M+=" AND tool_name = ?",G.push($.toolName);if($.operationType)M+=" AND operation_type = ?",G.push($.operationType);if($.fileType)M+=" AND file_type = ?",G.push($.fileType);if($.filePath)M+=" AND file_path = ?",G.push($.filePath);if($.createdAfter)M+=" AND created_at > ?",G.push($.createdAfter);if($.createdBefore)M+=" AND created_at < ?",G.push($.createdBefore);if($.operationId)M+=" AND operation_id = ?",G.push($.operationId);M+=" ORDER BY created_at DESC, id DESC";let J=this.db.prepare(M),Q=G.length>0?J.all(...G):J.all();return I.debug(i.operationsRetrieved(),Q.length,$),Q.map((Y)=>({id:Y.id,toolName:Y.tool_name,operationType:Y.operation_type,filePath:Y.file_path,targetPath:Y.target_path??void 0,fileType:Y.file_type,metadata:Y.metadata?JSON.parse(Y.metadata):void 0,sizeBytes:Y.size_bytes??void 0,permissions:Y.permissions?parseInt(Y.permissions,10):void 0,createdAt:parseInt(Y.created_at,10),operationId:Y.operation_id}))}async getFileStatesForTool($){let I=this.logger.getSubLogger({name:"getFileStatesForTool"}),M=await this.getOperations({toolName:$}),G=new Map;for(let Q of[...M].toReversed())if(Q.operationType==="rm")G.delete(Q.filePath);else G.set(Q.filePath,{filePath:Q.filePath,toolName:Q.toolName,fileType:Q.fileType,lastOperation:Q.operationType,targetPath:Q.targetPath,lastModified:Q.createdAt,metadata:Q.metadata,sizeBytes:Q.sizeBytes,permissions:Q.permissions});let J=Array.from(G.values());return I.debug(i.fileStatesComputed(),J.length,$),J}async getFileState($){let I=this.logger.getSubLogger({name:"getFileState"}),M=await this.getOperations({filePath:$});if(M.length===0)return I.debug(i.noOperationsFound(),$),null;let G=null;for(let J of[...M].toReversed())if(J.operationType==="rm")G=null;else G={filePath:J.filePath,toolName:J.toolName,fileType:J.fileType,lastOperation:J.operationType,targetPath:J.targetPath,lastModified:J.createdAt,metadata:J.metadata,sizeBytes:J.sizeBytes,permissions:J.permissions};return I.debug(i.fileStateComputed(),$,G?"active":"deleted"),G}async getRegisteredTools(){let $=this.logger.getSubLogger({name:"getRegisteredTools"}),I=await this.getOperations(),M=new Map;for(let J of I)if(!M.has(J.filePath))M.set(J.filePath,J);let G=Array.from(new Set(Array.from(M.values()).filter((J)=>J.operationType!=="rm").map((J)=>J.toolName))).toSorted();return $.debug(i.toolsFound(),G.length),G}async removeToolOperations($){let I=this.logger.getSubLogger({name:"removeToolOperations"}),G=this.db.prepare("DELETE FROM file_operations WHERE tool_name = ?").run($);I.debug(i.operationsRemoved(),G.changes,$)}async compact(){let $=this.logger.getSubLogger({name:"compact"}),I=await this.getStats(),M=await this.getOperations({operationType:"rm"});for(let J of M)if(!await this.getFileState(J.filePath))this.db.prepare("DELETE FROM file_operations WHERE file_path = ?").run(J.filePath);let G=await this.getStats();$.debug(i.compactionComplete(),I.totalOperations,G.totalOperations)}async validate(){let $=this.logger.getSubLogger({name:"validate"}),I=[],M=[],G=this.db.prepare(`
34
34
  SELECT operation_id, COUNT(*) as count
35
35
  FROM file_operations
36
36
  GROUP BY operation_id
37
37
  HAVING count > 1
38
- `).all();if(Q.length>0)M.push(`Found ${Q.length} duplicate operation IDs`);let Y=await this.getOperations({operationType:"symlink"});for(let G of Y)if(G.targetPath){if(!await this.getFileState(G.targetPath))M.push(`Symlink ${G.filePath} points to missing target ${G.targetPath}`)}return $.debug(l.validationComplete(),M.length,J.length),{valid:M.length===0,issues:M,repaired:J}}async getStats(){let $=this.db.prepare("SELECT COUNT(*) as count FROM file_operations").get(),M=this.db.prepare("SELECT COUNT(DISTINCT file_path) as count FROM file_operations").get(),J=this.db.prepare("SELECT COUNT(DISTINCT tool_name) as count FROM file_operations").get(),Q=this.db.prepare("SELECT MIN(created_at) as oldest, MAX(created_at) as newest FROM file_operations").get();return{totalOperations:$.count,totalFiles:M.count,totalTools:J.count,oldestOperation:Q.oldest||0,newestOperation:Q.newest||0}}async close(){this.db.close(),this.logger.debug(l.registryClosed())}initializeSchema(){let $=this.logger.getSubLogger({name:"initializeSchema"});this.db.run(`
38
+ `).all();if(G.length>0)I.push(`Found ${G.length} duplicate operation IDs`);let J=await this.getOperations({operationType:"symlink"});for(let Q of J)if(Q.targetPath){if(!await this.getFileState(Q.targetPath))I.push(`Symlink ${Q.filePath} points to missing target ${Q.targetPath}`)}return $.debug(i.validationComplete(),I.length,M.length),{valid:I.length===0,issues:I,repaired:M}}async getStats(){let $=this.db.prepare("SELECT COUNT(*) as count FROM file_operations").get(),I=this.db.prepare("SELECT COUNT(DISTINCT file_path) as count FROM file_operations").get(),M=this.db.prepare("SELECT COUNT(DISTINCT tool_name) as count FROM file_operations").get(),G=this.db.prepare("SELECT MIN(created_at) as oldest, MAX(created_at) as newest FROM file_operations").get();return{totalOperations:$.count,totalFiles:I.count,totalTools:M.count,oldestOperation:G.oldest||0,newestOperation:G.newest||0}}async close(){this.db.close(),this.logger.debug(i.registryClosed())}initializeSchema(){let $=this.logger.getSubLogger({name:"initializeSchema"});this.db.run(`
39
39
  CREATE TABLE IF NOT EXISTS file_operations (
40
40
  id INTEGER PRIMARY KEY AUTOINCREMENT,
41
41
  tool_name TEXT NOT NULL,
@@ -55,124 +55,124 @@ ${J}`}}function W$($={}){return(J,...Q)=>{let Y=typeof J==="string"?J:o7(J,Q);re
55
55
  CREATE INDEX IF NOT EXISTS idx_operation_type ON file_operations(operation_type);
56
56
  CREATE INDEX IF NOT EXISTS idx_created_at ON file_operations(created_at);
57
57
  CREATE INDEX IF NOT EXISTS idx_operation_id ON file_operations(operation_id);
58
- `),$.debug(l.schemaInitialized())}}var V0=Symbol("resolvedFileSystemBrand");import{Volume as e7}from"memfs";class $J{vol;constructor($){if(this.vol=new e7,$)this.vol.fromJSON($)}async readFile($,M="utf8"){return(await this.vol.promises.readFile($,{encoding:M})).toString()}async readFileBuffer($){let M=await this.vol.promises.readFile($);return Buffer.from(M)}async writeFile($,M,J="utf8"){let Q=typeof M==="string"?M:Buffer.isBuffer(M)?M:Buffer.from(M.buffer,M.byteOffset,M.byteLength);await this.vol.promises.writeFile($,Q,{encoding:J})}async exists($){try{return await this.vol.promises.stat($),!0}catch{return!1}}async mkdir($,M){await this.vol.promises.mkdir($,M)}async readdir($){return(await this.vol.promises.readdir($)).map((J)=>J.toString())}async rm($,M){try{if((await this.vol.promises.lstat($)).isSymbolicLink()){await this.vol.promises.unlink($);return}}catch(J){let Q=J;if(M?.force&&Q?.code==="ENOENT")return}try{await this.vol.promises.rm($,M)}catch(J){let Q=J;if(M?.force&&Q?.code==="ENOENT")return;throw J}}async rmdir($,M){await this.vol.promises.rmdir($,M)}async stat($){return await this.vol.promises.stat($)}async lstat($){return await this.vol.promises.lstat($)}async symlink($,M,J){await this.vol.promises.symlink($,M,J)}async readlink($){return(await this.vol.promises.readlink($)).toString()}async chmod($,M){await this.vol.promises.chmod($,typeof M==="string"?parseInt(M,8):M)}async copyFile($,M,J){await this.vol.promises.copyFile($,M,J)}async rename($,M){await this.vol.promises.rename($,M)}async ensureDir($){await this.vol.promises.mkdir($,{recursive:!0})}getVolume(){return this.vol}}import{constants as $X,promises as MX}from"fs";class z${fs;constants;constructor($=MX,M=$X){this.fs=$,this.constants=M}async readFile($,M="utf8"){return this.fs.readFile($,{encoding:M})}async readFileBuffer($){return this.fs.readFile($)}async writeFile($,M,J="utf8"){return this.fs.writeFile($,M,{encoding:J})}async exists($){try{return await this.fs.access($,this.constants.F_OK),!0}catch{return!1}}async mkdir($,M){await this.fs.mkdir($,M)}async readdir($){return this.fs.readdir($)}async rm($,M){return this.fs.rm($,M)}async rmdir($,M){if(M?.recursive)return this.fs.rm($,{recursive:!0,force:!0});return this.fs.rmdir($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async symlink($,M,J){return this.fs.symlink($,M,J)}async readlink($){return this.fs.readlink($)}async chmod($,M){return this.fs.chmod($,M)}async copyFile($,M,J){return this.fs.copyFile($,M,J)}async rename($,M){return this.fs.rename($,M)}async ensureDir($){await this.fs.mkdir($,{recursive:!0})}}class MJ{[V0];inner;homeDir;constructor($,M){this.inner=$,this.homeDir=M,this[V0]=!0}async readFile($,M){return this.inner.readFile(n(this.homeDir,$),M)}async readFileBuffer($){return this.inner.readFileBuffer(n(this.homeDir,$))}async writeFile($,M,J){await this.inner.writeFile(n(this.homeDir,$),M,J)}async exists($){return this.inner.exists(n(this.homeDir,$))}async mkdir($,M){await this.inner.mkdir(n(this.homeDir,$),M)}async readdir($){return this.inner.readdir(n(this.homeDir,$))}async rm($,M){await this.inner.rm(n(this.homeDir,$),M)}async rmdir($,M){await this.inner.rmdir(n(this.homeDir,$),M)}async stat($){return this.inner.stat(n(this.homeDir,$))}async lstat($){return this.inner.lstat(n(this.homeDir,$))}async symlink($,M,J){await this.inner.symlink(n(this.homeDir,$),n(this.homeDir,M),J)}async readlink($){return this.inner.readlink(n(this.homeDir,$))}async chmod($,M){await this.inner.chmod(n(this.homeDir,$),M)}async copyFile($,M,J){await this.inner.copyFile(n(this.homeDir,$),n(this.homeDir,M),J)}async rename($,M){await this.inner.rename(n(this.homeDir,$),n(this.homeDir,M))}async ensureDir($){await this.inner.ensureDir(n(this.homeDir,$))}}import{randomUUID as JX}from"crypto";import z0 from"path";class f{[V0]=!0;fs;registry;logger;parentLogger;context;projectConfig;suppressLogging=!1;constructor($,M,J,Q,Y){this.parentLogger=$,this.logger=$.getSubLogger({name:"TrackedFileSystem",context:Q.toolName}),this.fs=M,this.registry=J,this.context=Q,this.projectConfig=Y}static createContext($,M,J){return{toolName:$,fileType:M,operationId:JX(),metadata:J}}withContext($){let M={...this.context,...$},J=new f(this.parentLogger,this.fs,this.registry,M,this.projectConfig);return J.setSuppressLogging(this.suppressLogging),J}setSuppressLogging($){this.suppressLogging=$}logInfo($){if(!this.suppressLogging)this.logger.info($)}withToolName($){return this.withContext({toolName:$})}withFileType($){return this.withContext({fileType:$})}async readFile($,M){return this.fs.readFile($,M)}async readFileBuffer($){return this.fs.readFileBuffer($)}async writeFile($,M,J){let Q=await this.fs.exists($),Y=!0;if(Q)try{let X=await this.fs.readFile($,J||"utf8"),Z=typeof M==="string"?M:M.toString();Y=X!==Z}catch{Y=!0}if(!Y)return;await this.fs.writeFile($,M,J);let G=await this.getFileStats($);if(await this.recordOperation("writeFile",$,{sizeBytes:G?.sizeBytes,permissions:G?.permissions}),!Q)this.logInfo(l.fileCreated(s(this.projectConfig.paths.homeDir,$)));else this.logInfo(l.fileUpdated(s(this.projectConfig.paths.homeDir,$)))}async copyFile($,M,J){await this.fs.copyFile($,M,J);let Q=await this.getFileStats(M);await this.recordOperation("cp",M,{targetPath:$,sizeBytes:Q?.sizeBytes,permissions:Q?.permissions}),this.logInfo(l.fileCopied(s(this.projectConfig.paths.homeDir,$),s(this.projectConfig.paths.homeDir,M)))}async rename($,M){await this.fs.rename($,M);let J=await this.getFileStats(M);await this.recordOperation("rename",M,{targetPath:$,sizeBytes:J?.sizeBytes,permissions:J?.permissions}),this.logInfo(l.fileMoved(s(this.projectConfig.paths.homeDir,$),s(this.projectConfig.paths.homeDir,M)))}async symlink($,M,J){await this.fs.symlink($,M,J),await this.recordOperation("symlink",M,{targetPath:$}),this.logInfo(l.symlinkCreated(s(this.projectConfig.paths.homeDir,M),s(this.projectConfig.paths.homeDir,$)))}async recordExistingSymlink($,M){let J=z0.resolve(M),Q=z0.resolve($),Y=await this.registry.getFileState(J);if(Y&&Y.targetPath===Q)return;await this.recordOperation("symlink",M,{targetPath:$})}async rm($,M){if(M?.recursive&&await this.fs.exists($))if((await this.fs.stat($)).isDirectory())await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);else if(await this.fs.exists($))await this.trackFileDeletion($);await this.fs.rm($,M),this.logInfo(l.fileRemoved(s(this.projectConfig.paths.homeDir,$)))}async chmod($,M){await this.fs.chmod($,M);let J=await this.getFileStats($);await this.recordOperation("chmod",$,{permissions:J?.permissions}),this.logInfo(l.permissionsChanged(s(this.projectConfig.paths.homeDir,$),H0(M)))}async exists($){return this.fs.exists($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async readlink($){return this.fs.readlink($)}async readdir($){return this.fs.readdir($)}async mkdir($,M){let J=await this.fs.exists($);if(await this.fs.mkdir($,M),!J)await this.recordOperation("mkdir",$),this.logInfo(l.directoryCreated(s(this.projectConfig.paths.homeDir,$)))}async rmdir($,M){let J=this.logger.getSubLogger({name:"rmdir"});if(await this.fs.exists($))if(M?.recursive)await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);await this.fs.rmdir($,M),J.debug(l.rmdirTracked(),$)}async ensureDir($){let M=await this.fs.exists($);if(await this.fs.ensureDir($),!M)await this.recordOperation("mkdir",$),this.logInfo(l.directoryCreated(s(this.projectConfig.paths.homeDir,$)))}async getFileStats($){try{let M=await this.fs.stat($);return{sizeBytes:M.size,permissions:M.mode&511}}catch{return null}}async recordOperation($,M,J){await this.registry.recordOperation({toolName:this.context.toolName,operationType:$,filePath:z0.resolve(M),fileType:this.context.fileType,operationId:this.context.operationId,metadata:this.context.metadata,targetPath:J?.targetPath?z0.resolve(J.targetPath):void 0,sizeBytes:J?.sizeBytes,permissions:J?.permissions})}async trackFileDeletion($){await this.recordOperation("rm",$)}async trackDirectoryDeletion($){try{let M=await this.fs.readdir($);for(let J of M){let Q=z0.join($,J);if((await this.fs.stat(Q)).isDirectory())await this.trackDirectoryDeletion(Q);else await this.trackFileDeletion(Q)}await this.trackFileDeletion($)}catch(M){this.logger.debug(l.directoryDeletionError(),$,M instanceof Error?M.message:String(M))}}}import B0 from"path";var L={binarySetupService:{binaryNotFound:($,M)=>W(`Binary ${$} not found at ${M}, skipping`),extractedFilesTree:($,M)=>W(`Extracted files in ${$}:
59
- ${M}`),cleaningFailedInstall:($)=>W(`No binaries found, cleaning up installation directory: ${$}`),fallbackCleanup:($)=>W(`Directory still exists after rm(), trying rmdir: ${$}`),searchingWithPattern:($,M)=>W(`Searching for binary using pattern ${$} in directory ${M}`),fallbackPattern:($,M)=>W(`Trying fallback binary pattern ${$} in directory ${M}`),patternPathMissing:($)=>W(`Pattern path does not exist: ${$}`),noPatternMatch:($,M)=>W(`No matches found for pattern ${$} in directory ${M}`),directDownloadSingleBinary:($,M)=>W(`Direct download only provides one binary, but ${$} were configured. Only ${M} will be available.`),patternDebug:($,M,J)=>W(`Pattern: ${$}, Parts: [${M.join(", ")}], ExtractDir: ${J}`),processingPart:($,M)=>W(`Processing part: "${$}", currentDir: ${M}`),wildcardMatchResult:($)=>W(`Wildcard match result: ${$??"null"}`),directPath:($)=>W(`Direct path: ${$}`),finalResult:($)=>W(`Final result: ${$}`)},binarySymlink:{targetBinaryMissing:($,M,J)=>W(`Cannot create entrypoint for ${$}/${M}: target binary missing at ${J}`),removingExisting:($)=>W(`Removing old entrypoint: ${$}`),removeExistingFailed:($)=>W(`Failed to remove old entrypoint ${$}`),creating:($,M)=>W(`Creating entrypoint: ${$} <- ${M}`),creationFailed:($,M)=>W(`Failed to create entrypoint ${$} <- ${M}`),verificationMismatch:($,M,J)=>W(`Entrypoint ${$} is ${J}, expected ${M}`),verificationFailed:($)=>W(`Failed to verify entrypoint ${$}`),createdAndVerified:($,M)=>W(`Successfully created and verified entrypoint: ${$} <- ${M}`)},lifecycle:{startingInstallation:($)=>W(`Starting installation for ${$}`),hookExecution:($)=>W(`install: Running ${$} hook`),directoryCreated:($)=>W(`install: Created installation directory: ${$}`),directoryRenamed:($,M)=>W(`install: Renamed installation directory from ${$} to ${M}`),cleaningFailedInstallDir:($)=>W(`install: Cleaning up failed installation directory: ${$}`),versionResolved:($)=>W(`install: Resolved version: ${$}`),versionFallbackToTimestamp:()=>W("install: Version resolution returned null, using timestamp"),versionResolutionFailed:($)=>W(`install: Version resolution failed, using timestamp: ${String($)}`),externalBinaryMissing:($,M,J)=>W(`Cannot create symlink for ${$}/${M}: external binary missing at ${J}`),removingExistingSymlink:($)=>W(`Removing existing symlink: ${$}`),creatingExternalSymlink:($,M)=>W(`Creating external symlink: ${$} -> ${M}`),symlinkVerificationFailed:($)=>W(`Symlink verification failed: ${$}`),externalSymlinkCreated:($,M)=>W(`External symlink created: ${$} -> ${M}`)},outcome:{installSuccess:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),outdatedVersion:($,M,J)=>W(`Tool "${$}" version ${M} is outdated (latest: ${J})`),installFailed:($)=>W(`Installation failed via ${$}`),hookFailed:($)=>W(`Hook failed: ${$}`),unsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`)},archive:{extracting:($)=>W(`Extracting archive: ${$}`),extracted:()=>W("Archive extracted: %o"),cleaning:($)=>W(`Cleaning up downloaded archive: ${$}`)},binaryMovement:{moving:($,M)=>W(`Moving binary from ${$} to ${M}`)},completion:{noCompletionsConfigured:()=>W("install: no completions configured"),generatingCompletions:($)=>W(`install: generating ${$} completion files`),generatedCompletion:($,M)=>W(`install: generated completion: ${$} -> ${M}`),symlinking:($,M,J)=>W(`Symlinking completion for ${$} from ${M} to ${J}`),notFound:($)=>W(`Completion file not found: ${$}`),directoryListing:($)=>W(` ${$}`),preparedFromUrl:($,M)=>W(`install: prepared ${$} completion source at ${M}`),prepareFailed:($)=>W(`install: failed to prepare ${$} completion`)},hookExecutor:{executingHook:($,M)=>W(`Executing ${$} hook with ${M}ms timeout`),hookCompleted:($,M)=>W(`Hook ${$} completed successfully in ${M}ms`),continuingDespiteFailure:($)=>W(`Continuing installation despite ${$} hook failure`),stoppingDueToFailure:($)=>W(`Stopping hook execution due to failure in ${$} hook`),timeoutExceeded:($,M)=>W(`Hook ${$} timed out after ${M}ms`)}};async function JJ($,M,J,Q,Y,G,X){let Z=X.getSubLogger({name:"createBinaryEntrypoint"}),q=B0.join(G,M),I=B0.join(q,Q),U=B0.join(I,J),K=B0.join(I,Y);if(K===U)return;if(!await $.exists(K)){let _=`Cannot create entrypoint: target binary does not exist at ${K}`;throw Z.error(L.binarySymlink.targetBinaryMissing(M,J,K)),Error(_)}await $.ensureDir(I);try{if(await $.exists(U))Z.debug(L.binarySymlink.removingExisting(U)),await $.rm(U,{force:!0})}catch(_){Z.error(L.binarySymlink.removeExistingFailed(U),_);let O=_ instanceof Error?_.message:String(_);throw Error(`Failed to remove old entrypoint ${U}: ${O}`,{cause:_})}try{let _=B0.relative(I,K);if(Z.debug(L.binarySymlink.creating(U,_)),await($ instanceof f?$.withFileType("symlink"):$).symlink(_,U),!(await $.lstat(U)).isSymbolicLink())throw Error("Entrypoint unexpectedly created as regular file instead of symlink")}catch(_){let O=_ instanceof Error?_.message:String(_);throw Z.error(L.binarySymlink.creationFailed(U,K),_),Error(`Failed to create entrypoint at ${U}: ${O}`,{cause:_})}if(!await $.exists(U))throw Z.error(L.binarySymlink.verificationFailed(U)),Error(`Entrypoint creation appeared to succeed but file does not exist at ${U}`);Z.debug(L.binarySymlink.createdAndVerified(U,K))}function $M($,M){let J=(Q,...Y)=>{if(typeof Q==="string")return $(Q).env(M);return $(Q,...Y).env(M)};if(Object.assign(J,$),s0($))Object.defineProperty(J,oM,{value:!0,enumerable:!1});return J}function q$($,M){return $ instanceof f?$.withToolName(M):$}import QJ from"crypto";import i$ from"path";var k={initialized:($,M,J,Q)=>W(`Cache directory: ${$}, TTL: ${M} ms, Strategy: ${J}, Enabled: ${Q}`),cachingDisabled:($,M)=>W(`Cache disabled, ${$} for key: ${M}`),entryMissing:($)=>W(`No cache entry found for key: ${$}`),entryExpired:($)=>W(`Cache entry expired for key: ${$}`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let Y=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${Y}, expires: ${J}`)},cacheEntryRemoved:($)=>W(`Removed cache entry for key: ${$}`),cacheCleared:()=>W("Removed entire cache directory"),expiredEntriesCleared:($)=>W(`Removed ${$} expired cache entries`),cacheEntryExists:($)=>W(`Valid cache entry exists for key: ${$}`),noEntryToDelete:($)=>W(`No cache entry to delete for key: ${$}`),cacheDirectoryMissing:()=>W("Cache directory does not exist, nothing to clear"),binaryFileMissing:($,M)=>W(`Binary file missing for key: ${$}, path: ${M}`),contentHashMismatch:($,M,J)=>W(`Content hash mismatch for key: ${$}, expected: ${M}, actual: ${J}`),metadataProcessingWarning:($,M)=>W(`Error processing cache file ${$}: ${M}`),retrievalFailed:($,M)=>W(`Error retrieving cache for key: ${$}, error: ${M}`),storageFailed:($,M)=>W(`Error caching data for key: ${$}, error: ${M}`),checkFailed:($,M)=>W(`Error checking cache for key: ${$}, error: ${M}`),deleteFailed:($,M)=>W(`Error deleting cache entry for key: ${$}, error: ${M}`),clearExpiredFailed:($)=>W(`Error clearing expired cache entries: ${$}`),clearFailed:($)=>W(`Error clearing cache: ${$}`),directoryCreationFailed:($)=>W(`Error ensuring cache directories exist: ${$}`),binaryDirectoryNotConfigured:()=>W("Binary directory not configured for binary strategy"),binaryDataRequired:()=>W("Binary storage strategy requires Buffer data")};class MM{config;fileSystem;logger;metadataDir;binariesDir;constructor($,M,J){if(this.logger=$.getSubLogger({name:"FileCache"}),this.fileSystem=M,this.config=J,J.storageStrategy==="json")this.metadataDir=J.cacheDir;else this.metadataDir=i$.join(J.cacheDir,"metadata"),this.binariesDir=i$.join(J.cacheDir,"binaries");this.logger.debug(k.initialized(J.cacheDir,J.defaultTtl,J.storageStrategy,J.enabled))}async get($){let M=this.logger.getSubLogger({name:"get"});if(!this.config.enabled)return M.debug(k.cachingDisabled("returning null",$)),null;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(k.entryMissing($)),null;let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);if(this.isExpired(Y))return M.debug(k.entryExpired($)),await this.deleteEntry($,Y),null;if(Y.type==="json")return M.debug(k.cacheHit($,"JSON")),Y.data;else{if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let G=i$.join(this.binariesDir,Y.binaryFileName);if(!await this.fileSystem.exists(G))return M.warn(k.binaryFileMissing($,G)),await this.fileSystem.rm(J).catch(()=>{}),null;let X=await this.fileSystem.readFile(G),Z=Buffer.isBuffer(X)?X:Buffer.from(X),q=QJ.createHash("sha256").update(Z).digest("hex"),I=Y.contentHash;if(q!==I)return M.warn(k.contentHashMismatch($,I,q)),await this.deleteEntry($,Y),null;return M.debug(k.cacheHit($,"binary",Z.length)),Z}}catch(J){return M.warn(k.retrievalFailed($,this.getErrorMessage(J))),null}}async set($,M,J){let Q=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){Q.debug(k.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let Y=J??this.config.defaultTtl,G=Date.now();if(this.config.storageStrategy==="json"){let X={type:"json",data:M,timestamp:G,expiresAt:G+Y},Z=this.getMetadataFilePath($);await this.fileSystem.writeFile(Z,JSON.stringify(X,null,2),"utf8"),Q.debug(k.cacheStored($,"JSON",new Date(X.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(M))throw Error(k.binaryDataRequired());if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let X=M,Z=QJ.createHash("sha256").update(X).digest("hex"),q=`${Z}.bin`,I=i$.join(this.binariesDir,q);await this.fileSystem.writeFile(I,X);let U={type:"binary",binaryFileName:q,contentHash:Z,size:X.length,timestamp:G,expiresAt:G+Y},K=this.getMetadataFilePath($);await this.fileSystem.writeFile(K,JSON.stringify(U,null,2),"utf8"),Q.debug(k.cacheStored($,"binary",new Date(U.expiresAt).toISOString(),X.length))}}catch(Y){let G=this.getErrorMessage(Y);throw Q.warn(k.storageFailed($,G)),Error(`Failed to cache data: ${G}`,{cause:Y})}}async setDownload($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){G.debug(k.cachingDisabled("skipping setDownload",$));return}try{await this.ensureCacheDirectories();let X=J??this.config.defaultTtl,Z=Date.now();if(this.config.storageStrategy==="json")throw Error("Download caching requires binary storage strategy");if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let q=QJ.createHash("sha256").update(M).digest("hex"),I=`${q}.bin`,U=i$.join(this.binariesDir,I);await this.fileSystem.writeFile(U,M);let K={type:"binary",binaryFileName:I,contentHash:q,size:M.length,url:Q,contentType:Y,timestamp:Z,expiresAt:Z+X},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(K,null,2),"utf8"),G.debug(k.cacheStored($,"download",new Date(K.expiresAt).toISOString(),M.length))}catch(X){let Z=this.getErrorMessage(X);throw G.warn(k.storageFailed($,Z)),Error(`Failed to cache download: ${Z}`,{cause:X})}}async has($){let M=this.logger.getSubLogger({name:"has"});if(!this.config.enabled)return M.debug(k.cachingDisabled("returning false",$)),!1;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(k.entryMissing($)),!1;let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);if(this.isExpired(Y))return M.debug(k.entryExpired($)),!1;if(Y.type==="binary"&&this.binariesDir){let G=i$.join(this.binariesDir,Y.binaryFileName);if(!await this.fileSystem.exists(G))return M.debug(k.binaryFileMissing($,G)),!1}return M.debug(k.cacheEntryExists($)),!0}catch(J){return M.warn(k.checkFailed($,this.getErrorMessage(J))),!1}}async delete($){let M=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){M.debug(k.cachingDisabled("skipping delete",$));return}try{let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J)){let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);await this.deleteEntry($,Y),M.debug(k.cacheEntryRemoved($))}else M.debug(k.noEntryToDelete($))}catch(J){let Q=this.getErrorMessage(J);throw M.warn(k.deleteFailed($,Q)),Error(`Failed to delete cache entry: ${Q}`,{cause:J})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(k.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(k.cacheDirectoryMissing());return}let M=await this.fileSystem.readdir(this.metadataDir),J=0;for(let Q of M){if(!Q.endsWith(".json"))continue;let Y=i$.join(this.metadataDir,Q);try{let G=await this.fileSystem.readFile(Y,"utf8"),X=JSON.parse(G);if(this.isExpired(X)){let Z=i$.basename(Q,".json");await this.deleteEntry(Z,X),J++}}catch(G){$.warn(k.metadataProcessingWarning(Q,this.getErrorMessage(G))),await this.fileSystem.rm(Y).catch(()=>{}),J++}}$.debug(k.expiredEntriesCleared(J))}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.clearExpiredFailed(J)),Error(`Failed to clear expired cache entries: ${J}`,{cause:M})}}async clear(){let $=this.logger.getSubLogger({name:"clear"});if(!this.config.enabled){$.debug(k.cachingDisabled("skipping clear","N/A"));return}try{if(await this.fileSystem.exists(this.config.cacheDir))await this.fileSystem.rm(this.config.cacheDir,{recursive:!0,force:!0}),$.debug(k.cacheCleared());else $.debug(k.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.clearFailed(J)),Error(`Failed to clear cache: ${J}`,{cause:M})}}getMetadataFilePath($){let M=QJ.createHash("md5").update($).digest("hex");return i$.join(this.metadataDir,`${M}.json`)}async ensureCacheDirectories(){let $=this.logger.getSubLogger({name:"ensureCacheDirectories"});try{if(await this.fileSystem.ensureDir(this.metadataDir),this.binariesDir)await this.fileSystem.ensureDir(this.binariesDir)}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.directoryCreationFailed(J)),Error(`Failed to create cache directories: ${J}`,{cause:M})}}getErrorMessage($){if($ instanceof Error)return $.message;return String($)}isExpired($){return Date.now()>$.expiresAt}async deleteEntry($,M){let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J))await this.fileSystem.rm(J);if(M.type==="binary"&&this.binariesDir){let Q=i$.join(this.binariesDir,M.binaryFileName);if(await this.fileSystem.exists(Q))await this.fileSystem.rm(Q)}}}import QX from"crypto";function SY($,M={}){let J={headers:M.headers||{}},Q={url:$,options:J};return`download:${QX.createHash("sha256").update(JSON.stringify(Q)).digest("hex")}`}import YX from"path";var D0={strategyCreated:($,M)=>W(`Created ${$}${M}`),downloadStarted:($)=>W(`Downloading URL: ${$}`),downloadToFileStarted:($,M)=>W(`Downloading URL ${$} to file: ${M}`)};var B$={strategyWrapped:($,M)=>W(`Wrapping strategy ${$} with cache, TTL: ${M} ms`),cachingDisabled:($,M,J)=>W(`Cache disabled, ${$} for key: ${M} (${J})`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let Y=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${Y}, expires: ${J}`)},cacheStorageFailed:($)=>W(`Error caching data for key: ${$}`),cacheCheckFailed:($)=>W(`Error checking cache for key: ${$}`),cacheMiss:($)=>W(`No cache entry found for key: ${$}`),cacheDisabledForProgress:($)=>W(`Cache disabled, caching for key: ${$} (reason: progress callback)`),readFileForCaching:($)=>W(`read file for caching: ${$}`),downloadedFileExists:($,M)=>W(`Downloaded file exists (${$}): ${M}`),downloadedFileCached:($,M)=>W(`Successfully read file for caching from ${$}, size: ${M} bytes`),downloadedFileMissing:($)=>W(`Downloaded file not found: ${$}`),downloadedFileReadFailed:($)=>W(`Failed to read ${$}`),downloadFromStrategy:($)=>W(`download from ${$}`),cachedFileWritten:($)=>W(`[CachedDownloadStrategy] write ${$}`)},k$={constructed:($)=>W(`NodeFetchStrategy constructed (fileSystem ${$})`),downloadTimeout:($)=>W(`Download timeout for ${$}`),responseBodyReadFailed:($,M)=>W(`Failed to read response body for ${$}: ${String(M)}`),downloadFailed:($,M,J,Q)=>W(`Download failed: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${Q??"N/A"}`),downloadAttempt:($,M)=>W(`Attempt ${$}: Downloading ${M}`),downloadSuccessful:($,M)=>W(`Download successful for ${$}, size: ${M} bytes`),savingToDestination:($)=>W(`Saving to destination: ${$}`),savedSuccessfully:($)=>W(`Successfully wrote to ${$} using IFileSystem`),downloadAttemptError:($,M,J)=>W(`Error during download attempt ${$} for ${M}: ${String(J)}`),retryingDownload:($,M,J,Q)=>W(`Retrying download for ${$}, attempt ${M}/${J} after ${Q}ms`),exhaustedRetries:($)=>W(`Exhausted retries for ${$}`)},JM={errorCreated:($,M,J)=>W(`${$} created: message=${M}, url=${J}`),networkErrorCreated:($,M,J)=>W(`NetworkError created: message=${$}, url=${M}, originalError=${String(J)}`),httpErrorCreated:($,M,J,Q,Y,G)=>W(`HttpError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(Y)}, responseHeaders=${JSON.stringify(G??{})}`),notFoundErrorCreated:($,M,J)=>W(`NotFoundError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),forbiddenErrorCreated:($,M,J)=>W(`ForbiddenError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),rateLimitErrorCreated:($,M,J,Q,Y,G,X)=>W(`RateLimitError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(Y)}, responseHeaders=${JSON.stringify(G??{})}, resetTimestamp=${String(X)}`),clientErrorCreated:($,M,J,Q,Y)=>W(`ClientError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(Y??{})}`),serverErrorCreated:($,M,J,Q,Y)=>W(`ServerError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(Y??{})}`)};class BQ{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,M,J,Q,Y=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=M,this.cache=J,this.underlyingStrategy=Q,this.cacheTtl=Y,this.name=`cached-${Q.name}`,this.logger.debug(B$.strategyWrapped(Q.name,Y))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,M,J,Q,Y){if($.trace(B$.cacheHit(J,"binary",M.length),{url:Q}),Y.onProgress)Y.onProgress(0,M.length);if(Y.destinationPath){if(await this.fileSystem.ensureDir(YX.dirname(Y.destinationPath)),await this.fileSystem.writeFile(Y.destinationPath,M),$.trace(B$.cachedFileWritten(Y.destinationPath)),Y.onProgress)Y.onProgress(M.length,M.length);return}if(Y.onProgress)Y.onProgress(M.length,M.length);return M}async readFileForCaching($,M){$.trace(B$.readFileForCaching(M));try{let J=await this.fileSystem.exists(M);if($.trace(B$.downloadedFileExists(M,J)),J){let Q=await this.fileSystem.readFileBuffer(M);return $.trace(B$.downloadedFileCached(M,Q.length),{path:M,size:Q.length}),Q}else return $.trace(B$.downloadedFileMissing(M)),null}catch(J){return $.trace(B$.downloadedFileReadFailed(M),J),null}}async determineBufferToCache($,M,J){if(M instanceof Buffer)return M;else if(J.destinationPath&&M===void 0)return await this.readFileForCaching($,J.destinationPath);return null}async cacheResult($,M,J,Q,Y){try{await this.cache.setDownload(J,M,this.cacheTtl,Q,this.extractContentTypeFromHeaders(Y.headers)),$.trace(B$.cacheStored(J,"binary","TTL-based",M.length),{url:Q})}catch(G){$.trace(B$.cacheStorageFailed(J),G)}}async download($,M={}){let J=this.logger.getSubLogger({name:"download"}),Q=SY($,M);try{let X=await this.cache.get(Q);if(X)return await this.handleCacheHit(J,X,Q,$,M);J.trace(B$.cacheMiss(Q),{url:$})}catch(X){J.trace(B$.cacheCheckFailed(Q),X)}J.trace(B$.downloadFromStrategy(this.underlyingStrategy.name),{url:$});let Y=await this.underlyingStrategy.download($,M),G=await this.determineBufferToCache(J,Y,M);if(G)await this.cacheResult(J,G,Q,$,M);return Y}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class DQ extends Error{url;constructor($,M,J){super(M);let Q=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=J,Q.debug(JM.errorCreated("DownloaderError",M,J))}}class U$ extends DQ{originalError;constructor($,M,J,Q){super($,M,J);let Y=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=Q,Y.debug(JM.networkErrorCreated(M,J,Q),Q)}}class F$ extends DQ{statusCode;statusText;responseBody;responseHeaders;constructor($,M,J,Q,Y,G,X){super($,M,J);let Z=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=Q,this.statusText=Y,this.responseBody=G,this.responseHeaders=X,Z.debug(JM.httpErrorCreated(M,J,Q,Y,G,X),{url:J,statusCode:Q,statusText:Y,responseBody:G,responseHeaders:X})}}class S$ extends F${constructor($,M,J,Q){super($,"Resource not found",M,404,"Not Found",J,Q);let Y=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",Y.debug(JM.notFoundErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class bM extends F${constructor($,M,J,Q){super($,"Access forbidden",M,403,"Forbidden",J,Q);let Y=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",Y.debug(JM.forbiddenErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class BM extends F${resetTimestamp;constructor($,M,J,Q,Y,G,X,Z){super($,M,J,Q,Y,G,X);let q=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=Z,q.debug(JM.rateLimitErrorCreated(M,J,Q,Y,G,X,Z),{url:J,statusCode:Q,statusText:Y,responseBody:G,responseHeaders:X,resetTimestamp:Z})}}class NM extends F${constructor($,M,J,Q,Y,G){super($,`Client error: ${Q}`,M,J,Q,Y,G);let X=$.getSubLogger({name:"ClientError"});this.name="ClientError",X.debug(JM.clientErrorCreated(M,J,Q,Y,G),{url:M,statusCode:J,statusText:Q,responseBody:Y,responseHeaders:G})}}class vM extends F${constructor($,M,J,Q,Y,G){super($,`Server error: ${Q}`,M,J,Q,Y,G);let X=$.getSubLogger({name:"ServerError"});this.name="ServerError",X.debug(JM.serverErrorCreated(M,J,Q,Y,G),{url:M,statusCode:J,statusText:Q,responseBody:Y,responseHeaders:G})}}class AQ{name="node-fetch";logger;fileSystem;proxyConfig;constructor($,M,J){this.logger=$.getSubLogger({name:"NodeFetchStrategy"}),this.logger.debug(k$.constructed(M?"provided":"undefined")),this.fileSystem=M,this.proxyConfig=J}async isAvailable(){return typeof fetch==="function"}getResponseHeaders($){let M={};return $.forEach((J,Q)=>{M[Q]=J}),M}parseRateLimitReset($){let M=$.get("X-RateLimit-Reset");if(M){let Q=parseInt(M,10);if(!Number.isNaN(Q))return Q*1000}let J=$.get("Retry-After");if(J){let Q=parseInt(J,10);if(!Number.isNaN(Q))return Date.now()+Q*1000;let Y=Date.parse(J);if(!Number.isNaN(Y))return Y}return}async setupDownloadRequest($,M,J){let Q=new AbortController,Y;if(J)Y=setTimeout(()=>{this.logger.debug(k$.downloadTimeout($)),Q.abort()},J);return{response:await s6($,{headers:M,signal:Q.signal},this.proxyConfig),timeoutId:Y}}async handleErrorResponse($,M){let J;try{J=await $.text()}catch(Z){this.logger.debug(k$.responseBodyReadFailed(M,Z))}let Q=this.getResponseHeaders($.headers),Y=$.status,G=$.statusText;if(this.logger.debug(k$.downloadFailed(M,Y,G,J?.substring(0,100))),Y===404)throw new S$(this.logger,M,J,Q);let X=this.parseRateLimitReset($.headers);if(Y===403){if(X)throw new BM(this.logger,"Forbidden: Rate limit likely exceeded",M,Y,G,J,Q,X);throw new bM(this.logger,M,J,Q)}if(Y===429)throw new BM(this.logger,"Too Many Requests",M,Y,G,J,Q,X);if(Y>=400&&Y<500)throw new NM(this.logger,M,Y,G,J,Q);if(Y>=500&&Y<600)throw new vM(this.logger,M,Y,G,J,Q);throw new F$(this.logger,`HTTP error ${Y}`,M,Y,G,J,Q)}async processResponseStream($,M,J){let Q=$.headers.get("content-length"),Y=null;if(Q){let q=parseInt(Q,10);if(!Number.isNaN(q))Y=q}let G=0;if(J)J(G,Y);let X=[],Z=$.body?.getReader();if(!Z)throw new U$(this.logger,"Response body is not readable.",M);while(!0){let{done:q,value:I}=await Z.read();if(q)break;if(I){if(X.push(Buffer.from(I)),G+=I.length,J)J(G,Y)}}return Buffer.concat(X)}async handleDownloadAttempt($,M,J){let{headers:Q,timeout:Y,onProgress:G,destinationPath:X}=M;this.logger.debug(k$.downloadAttempt(J+1,$));let{response:Z,timeoutId:q}=await this.setupDownloadRequest($,Q,Y);if(q)clearTimeout(q);if(!Z.ok)await this.handleErrorResponse(Z,$);let I=await this.processResponseStream(Z,$,G);if(this.logger.debug(k$.downloadSuccessful($,I.length)),X){this.logger.debug(k$.savingToDestination(X)),await this.fileSystem.writeFile(X,I),this.logger.debug(k$.savedSuccessfully(X));return}else return I}handleDownloadError($,M,J,Q,Y){if(this.logger.debug(k$.downloadAttemptError(J+1,M,$)),J>=Q){if($ instanceof F$||$ instanceof U$)throw $;let G=`Failed to download ${M}`;if($ instanceof Error&&$.name==="AbortError")G=`Download timed out for ${M}`;else if($ instanceof Error)G=$.message;throw new U$(this.logger,G,M,$ instanceof Error?$:void 0)}}async retryDownload($,M,J,Q,Y){this.logger.debug(k$.retryingDownload($,M+2,J+1,Q)),await new Promise((G)=>setTimeout(G,Q))}async download($,M){let{retryCount:J=0,retryDelay:Q=1000,onProgress:Y}=M,G=0;while(G<=J)try{return await this.handleDownloadAttempt($,M,G)}catch(X){if(this.handleDownloadError(X,$,G,J,Y),G<J)await this.retryDownload($,G,J,Q,Y),G++}throw this.logger.debug(k$.exhaustedRetries($)),new U$(this.logger,`Download failed for ${$} after ${J} retries.`,$)}}class EQ{strategies=[];fs;logger;constructor($,M,J,Q,Y){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=M,typeof J<"u")this.strategies=J;else{let G=new AQ(this.logger,this.fs,Y),X=Y?.enabled?` (proxy port ${Y.port})`:"";if(Q)this.logger.debug(D0.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${X}`)),this.strategies.push(new BQ(this.logger,this.fs,Q,G));else this.logger.debug(D0.strategyCreated("NodeFetchStrategy",X||" (no cache)")),this.strategies.push(G)}}registerStrategy($){this.strategies.unshift($)}async tryDownloadWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};return{success:!0,buffer:await $.download(M,J)}}async download($,M,J={}){if($.getSubLogger({name:"Downloader"}).getSubLogger({name:"download"}).debug(D0.downloadStarted(M)),this.strategies.length===0)throw Error("No download strategies registered.");let Y;for(let G of this.strategies)try{let X=await this.tryDownloadWithStrategy(G,M,J);if(X.success)return X.buffer}catch(X){Y=this.normalizeError(X)}if(Y)throw Y;throw Error(`No available download strategy succeeded for ${M}.`)}async tryDownloadToFileWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};if(await $.download(M,J)===void 0)return{success:!0};throw Error("Strategy returned Buffer instead of void for downloadToFile method")}normalizeError($){if($ instanceof Error)return $;else if(typeof $==="string")return Error($);else return Error(`An unknown error occurred during download: ${JSON.stringify($)}`)}async downloadToFile($,M,J,Q={}){$.getSubLogger({name:"Downloader"}).getSubLogger({name:"downloadToFile"}).debug(D0.downloadToFileStarted(M,J));let G={...Q,destinationPath:J};if(this.strategies.length===0)throw Error("No download strategies registered.");let X;for(let Z of this.strategies)try{if((await this.tryDownloadToFileWithStrategy(Z,M,G)).success)return}catch(q){X=this.normalizeError(q)}if(X)throw X;throw Error(`No available download strategy succeeded for ${M}.`)}}import*as eM from"cli-progress";class FQ{filename;progressBar=null;enabled;startTime=0;constructor($,M={}){this.filename=$;this.enabled=M.enabled??!0}createCallback(){if(!this.enabled)return;return($,M)=>{if(this.startTime===0)if(this.startTime=Date.now(),M)this.progressBar=new eM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},eM.Presets.shades_classic),this.progressBar.start(M,0,{speed:"0 B/s"});else this.progressBar=new eM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},eM.Presets.shades_classic),this.progressBar.start(100,0,{speed:"0 B/s"});if(this.progressBar){let J=(Date.now()-this.startTime)/1000,Q=J>0?`${this.formatBytes($/J)}/s`:"0 B/s";if(M){if(this.progressBar.update($,{speed:Q}),$>=M)this.progressBar.stop()}else{let Y=Math.floor(Date.now()/100)%100;this.progressBar.update(Y,{speed:Q,value:this.formatBytes($)})}}}}clear(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}finish(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}formatBytes($){let M=["B","KB","MB","GB"],J=$,Q=0;while(J>=1024&&Q<M.length-1)J/=1024,Q++;return`${J.toFixed(J>=10?0:1)} ${M[Q]}`}}function wY($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.NO_COLOR)return!1;return!0}async function K$($,M,J,Q,Y,G){let X=wY(G?.quiet),Z=new FQ(Q,{enabled:X});try{await Y.download($,M,{destinationPath:J,onProgress:Z.createCallback()})}finally{Z.finish()}}function bY($){return $.installParams?.hooks}async function w$($,M,J,Q,Y){let X=bY($)?.["after-download"];if(!X)return{success:!0};Y.debug(L.lifecycle.hookExecution("after-download"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(Y,"after-download",q,Z);if(!I.success)return{success:!1,error:`afterDownload hook failed: ${I.error}`}}return{success:!0}}async function $0($,M,J,Q,Y){let X=bY($)?.["after-extract"];if(!X)return{success:!0};Y.debug(L.lifecycle.hookExecution("after-extract"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(Y,"after-extract",q,Z);if(!I.success)return{success:!1,error:`afterExtract hook failed: ${I.error}`}}return{success:!0}}function GX($){return typeof $==="object"&&$!==null}function XX($){if(!GX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function NY($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function vY($){if(XX($)){let M=NY($.stderr);if(M.length>0)return M;let J=NY($.stdout);if(J.length>0)return J;if($.message)return $.message;return`exit code ${$.exitCode??"unknown"}`}if($ instanceof Error)return $.message;return String($)}function l$($){if(!$||$.length===0)return[];return $.map((M)=>typeof M==="string"?{name:M,pattern:`{,*/}${M}`}:M)}function YJ($){return l$($).map((J)=>J.name)}import{join as ZX}from"path";function e($,M){return l$($).map((Q)=>ZX(M,Q.name))}import fY from"path";import{codeFrameColumns as WX}from"@babel/code-frame";function qX($){return typeof $==="object"&&$!==null}function CY($){if(!qX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function IX($){return $.isTracingEnabled()}function UX($){return $.endsWith(`
58
+ `),$.debug(i.schemaInitialized())}}var DM=Symbol("resolvedFileSystemBrand");import{Volume as X4}from"memfs";class J0{vol;constructor($){if(this.vol=new X4,$)this.vol.fromJSON($)}async readFile($,I="utf8"){return(await this.vol.promises.readFile($,{encoding:I})).toString()}async readFileBuffer($){let I=await this.vol.promises.readFile($);return Buffer.from(I)}async writeFile($,I,M="utf8"){let G=typeof I==="string"?I:Buffer.isBuffer(I)?I:Buffer.from(I.buffer,I.byteOffset,I.byteLength);await this.vol.promises.writeFile($,G,{encoding:M})}async exists($){try{return await this.vol.promises.stat($),!0}catch{return!1}}async mkdir($,I){await this.vol.promises.mkdir($,I)}async readdir($){return(await this.vol.promises.readdir($)).map((M)=>M.toString())}async rm($,I){try{if((await this.vol.promises.lstat($)).isSymbolicLink()){await this.vol.promises.unlink($);return}}catch(M){let G=M;if(I?.force&&G?.code==="ENOENT")return}try{await this.vol.promises.rm($,I)}catch(M){let G=M;if(I?.force&&G?.code==="ENOENT")return;throw M}}async rmdir($,I){await this.vol.promises.rmdir($,I)}async stat($){return await this.vol.promises.stat($)}async lstat($){return await this.vol.promises.lstat($)}async symlink($,I,M){await this.vol.promises.symlink($,I,M)}async readlink($){return(await this.vol.promises.readlink($)).toString()}async chmod($,I){await this.vol.promises.chmod($,typeof I==="string"?parseInt(I,8):I)}async copyFile($,I,M){await this.vol.promises.copyFile($,I,M)}async rename($,I){await this.vol.promises.rename($,I)}async ensureDir($){await this.vol.promises.mkdir($,{recursive:!0})}getVolume(){return this.vol}}import{constants as Z4,promises as R4}from"fs";class z${fs;constants;constructor($=R4,I=Z4){this.fs=$,this.constants=I}async readFile($,I="utf8"){return this.fs.readFile($,{encoding:I})}async readFileBuffer($){return this.fs.readFile($)}async writeFile($,I,M="utf8"){return this.fs.writeFile($,I,{encoding:M})}async exists($){try{return await this.fs.access($,this.constants.F_OK),!0}catch{return!1}}async mkdir($,I){await this.fs.mkdir($,I)}async readdir($){return this.fs.readdir($)}async rm($,I){return this.fs.rm($,I)}async rmdir($,I){if(I?.recursive)return this.fs.rm($,{recursive:!0,force:!0});return this.fs.rmdir($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async symlink($,I,M){return this.fs.symlink($,I,M)}async readlink($){return this.fs.readlink($)}async chmod($,I){return this.fs.chmod($,I)}async copyFile($,I,M){return this.fs.copyFile($,I,M)}async rename($,I){return this.fs.rename($,I)}async ensureDir($){await this.fs.mkdir($,{recursive:!0})}}class Q0{[DM];inner;homeDir;constructor($,I){this.inner=$,this.homeDir=I,this[DM]=!0}async readFile($,I){return this.inner.readFile(n(this.homeDir,$),I)}async readFileBuffer($){return this.inner.readFileBuffer(n(this.homeDir,$))}async writeFile($,I,M){await this.inner.writeFile(n(this.homeDir,$),I,M)}async exists($){return this.inner.exists(n(this.homeDir,$))}async mkdir($,I){await this.inner.mkdir(n(this.homeDir,$),I)}async readdir($){return this.inner.readdir(n(this.homeDir,$))}async rm($,I){await this.inner.rm(n(this.homeDir,$),I)}async rmdir($,I){await this.inner.rmdir(n(this.homeDir,$),I)}async stat($){return this.inner.stat(n(this.homeDir,$))}async lstat($){return this.inner.lstat(n(this.homeDir,$))}async symlink($,I,M){await this.inner.symlink(n(this.homeDir,$),n(this.homeDir,I),M)}async readlink($){return this.inner.readlink(n(this.homeDir,$))}async chmod($,I){await this.inner.chmod(n(this.homeDir,$),I)}async copyFile($,I,M){await this.inner.copyFile(n(this.homeDir,$),n(this.homeDir,I),M)}async rename($,I){await this.inner.rename(n(this.homeDir,$),n(this.homeDir,I))}async ensureDir($){await this.inner.ensureDir(n(this.homeDir,$))}}import{randomUUID as W4}from"crypto";import AM from"path";class f{[DM]=!0;fs;registry;logger;parentLogger;context;projectConfig;suppressLogging=!1;constructor($,I,M,G,J){this.parentLogger=$,this.logger=$.getSubLogger({name:"TrackedFileSystem",context:G.toolName}),this.fs=I,this.registry=M,this.context=G,this.projectConfig=J}static createContext($,I,M){return{toolName:$,fileType:I,operationId:W4(),metadata:M}}withContext($){let I={...this.context,...$},M=new f(this.parentLogger,this.fs,this.registry,I,this.projectConfig);return M.setSuppressLogging(this.suppressLogging),M}setSuppressLogging($){this.suppressLogging=$}logInfo($){if(!this.suppressLogging)this.logger.info($)}withToolName($){return this.withContext({toolName:$})}withFileType($){return this.withContext({fileType:$})}async readFile($,I){return this.fs.readFile($,I)}async readFileBuffer($){return this.fs.readFileBuffer($)}async writeFile($,I,M){let G=await this.fs.exists($),J=!0;if(G)try{let Y=await this.fs.readFile($,M||"utf8"),X=typeof I==="string"?I:I.toString();J=Y!==X}catch{J=!0}if(!J)return;await this.fs.writeFile($,I,M);let Q=await this.getFileStats($);if(await this.recordOperation("writeFile",$,{sizeBytes:Q?.sizeBytes,permissions:Q?.permissions}),!G)this.logInfo(i.fileCreated(r(this.projectConfig.paths.homeDir,$)));else this.logInfo(i.fileUpdated(r(this.projectConfig.paths.homeDir,$)))}async copyFile($,I,M){await this.fs.copyFile($,I,M);let G=await this.getFileStats(I);await this.recordOperation("cp",I,{targetPath:$,sizeBytes:G?.sizeBytes,permissions:G?.permissions}),this.logInfo(i.fileCopied(r(this.projectConfig.paths.homeDir,$),r(this.projectConfig.paths.homeDir,I)))}async rename($,I){await this.fs.rename($,I);let M=await this.getFileStats(I);await this.recordOperation("rename",I,{targetPath:$,sizeBytes:M?.sizeBytes,permissions:M?.permissions}),this.logInfo(i.fileMoved(r(this.projectConfig.paths.homeDir,$),r(this.projectConfig.paths.homeDir,I)))}async symlink($,I,M){await this.fs.symlink($,I,M),await this.recordOperation("symlink",I,{targetPath:$}),this.logInfo(i.symlinkCreated(r(this.projectConfig.paths.homeDir,I),r(this.projectConfig.paths.homeDir,$)))}async recordExistingSymlink($,I){let M=AM.resolve(I),G=AM.resolve($),J=await this.registry.getFileState(M);if(J&&J.targetPath===G)return;await this.recordOperation("symlink",I,{targetPath:$})}async rm($,I){if(I?.recursive&&await this.fs.exists($))if((await this.fs.stat($)).isDirectory())await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);else if(await this.fs.exists($))await this.trackFileDeletion($);await this.fs.rm($,I),this.logInfo(i.fileRemoved(r(this.projectConfig.paths.homeDir,$)))}async chmod($,I){await this.fs.chmod($,I);let M=await this.getFileStats($);await this.recordOperation("chmod",$,{permissions:M?.permissions}),this.logInfo(i.permissionsChanged(r(this.projectConfig.paths.homeDir,$),jM(I)))}async exists($){return this.fs.exists($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async readlink($){return this.fs.readlink($)}async readdir($){return this.fs.readdir($)}async mkdir($,I){let M=await this.fs.exists($);if(await this.fs.mkdir($,I),!M)await this.recordOperation("mkdir",$),this.logInfo(i.directoryCreated(r(this.projectConfig.paths.homeDir,$)))}async rmdir($,I){let M=this.logger.getSubLogger({name:"rmdir"});if(await this.fs.exists($))if(I?.recursive)await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);await this.fs.rmdir($,I),M.debug(i.rmdirTracked(),$)}async ensureDir($){let I=await this.fs.exists($);if(await this.fs.ensureDir($),!I)await this.recordOperation("mkdir",$),this.logInfo(i.directoryCreated(r(this.projectConfig.paths.homeDir,$)))}async getFileStats($){try{let I=await this.fs.stat($);return{sizeBytes:I.size,permissions:I.mode&511}}catch{return null}}async recordOperation($,I,M){await this.registry.recordOperation({toolName:this.context.toolName,operationType:$,filePath:AM.resolve(I),fileType:this.context.fileType,operationId:this.context.operationId,metadata:this.context.metadata,targetPath:M?.targetPath?AM.resolve(M.targetPath):void 0,sizeBytes:M?.sizeBytes,permissions:M?.permissions})}async trackFileDeletion($){await this.recordOperation("rm",$)}async trackDirectoryDeletion($){try{let I=await this.fs.readdir($);for(let M of I){let G=AM.join($,M);if((await this.fs.stat(G)).isDirectory())await this.trackDirectoryDeletion(G);else await this.trackFileDeletion(G)}await this.trackFileDeletion($)}catch(I){this.logger.debug(i.directoryDeletionError(),$,I instanceof Error?I.message:String(I))}}}import FM from"path";var F={binarySetupService:{binaryNotFound:($,I)=>Z(`Binary ${$} not found at ${I}, skipping`),extractedFilesTree:($,I)=>Z(`Extracted files in ${$}:
59
+ ${I}`),cleaningFailedInstall:($)=>Z(`No binaries found, cleaning up installation directory: ${$}`),fallbackCleanup:($)=>Z(`Directory still exists after rm(), trying rmdir: ${$}`),searchingWithPattern:($,I)=>Z(`Searching for binary using pattern ${$} in directory ${I}`),fallbackPattern:($,I)=>Z(`Trying fallback binary pattern ${$} in directory ${I}`),patternPathMissing:($)=>Z(`Pattern path does not exist: ${$}`),noPatternMatch:($,I)=>Z(`No matches found for pattern ${$} in directory ${I}`),directDownloadSingleBinary:($,I)=>Z(`Direct download only provides one binary, but ${$} were configured. Only ${I} will be available.`),patternDebug:($,I,M)=>Z(`Pattern: ${$}, Parts: [${I.join(", ")}], ExtractDir: ${M}`),processingPart:($,I)=>Z(`Processing part: "${$}", currentDir: ${I}`),wildcardMatchResult:($)=>Z(`Wildcard match result: ${$??"null"}`),directPath:($)=>Z(`Direct path: ${$}`),finalResult:($)=>Z(`Final result: ${$}`)},binarySymlink:{targetBinaryMissing:($,I,M)=>Z(`Cannot create entrypoint for ${$}/${I}: target binary missing at ${M}`),removingExisting:($)=>Z(`Removing old entrypoint: ${$}`),removeExistingFailed:($)=>Z(`Failed to remove old entrypoint ${$}`),creating:($,I)=>Z(`Creating entrypoint: ${$} <- ${I}`),creationFailed:($,I)=>Z(`Failed to create entrypoint ${$} <- ${I}`),verificationMismatch:($,I,M)=>Z(`Entrypoint ${$} is ${M}, expected ${I}`),verificationFailed:($)=>Z(`Failed to verify entrypoint ${$}`),createdAndVerified:($,I)=>Z(`Successfully created and verified entrypoint: ${$} <- ${I}`)},lifecycle:{startingInstallation:($)=>Z(`Starting installation for ${$}`),hookExecution:($)=>Z(`install: Running ${$} hook`),directoryCreated:($)=>Z(`install: Created installation directory: ${$}`),directoryRenamed:($,I)=>Z(`install: Renamed installation directory from ${$} to ${I}`),cleaningFailedInstallDir:($)=>Z(`install: Cleaning up failed installation directory: ${$}`),versionResolved:($)=>Z(`install: Resolved version: ${$}`),versionFallbackToTimestamp:()=>Z("install: Version resolution returned null, using timestamp"),versionResolutionFailed:($)=>Z(`install: Version resolution failed, using timestamp: ${String($)}`),externalBinaryMissing:($,I,M)=>Z(`Cannot create symlink for ${$}/${I}: external binary missing at ${M}`),removingExistingSymlink:($)=>Z(`Removing existing symlink: ${$}`),creatingExternalSymlink:($,I)=>Z(`Creating external symlink: ${$} -> ${I}`),symlinkVerificationFailed:($)=>Z(`Symlink verification failed: ${$}`),externalSymlinkCreated:($,I)=>Z(`External symlink created: ${$} -> ${I}`),existingInstallPathMissing:($)=>Z(`install: existing install path missing: ${$}`),currentDirMissing:($)=>Z(`install: current tool path missing: ${$}`),currentBinaryMissing:($)=>Z(`install: current binary missing: ${$}`)},outcome:{installSuccess:($,I,M)=>Z(`Tool "${$}" \`${I}\` installed successfully using ${M}`),outdatedVersion:($,I,M)=>Z(`Tool "${$}" version ${I} is outdated (latest: ${M})`),installFailed:($)=>Z(`Installation failed via ${$}`),hookFailed:($)=>Z(`Hook failed: ${$}`),unsupportedOperation:($,I)=>Z(`${$} not yet supported (${I})`)},archive:{extracting:($)=>Z(`Extracting archive: ${$}`),extracted:()=>Z("Archive extracted: %o"),cleaning:($)=>Z(`Cleaning up downloaded archive: ${$}`)},binaryMovement:{moving:($,I)=>Z(`Moving binary from ${$} to ${I}`)},completion:{noCompletionsConfigured:()=>Z("install: no completions configured"),generatingCompletions:($)=>Z(`install: generating ${$} completion files`),generatedCompletion:($,I)=>Z(`install: generated completion: ${$} -> ${I}`),symlinking:($,I,M)=>Z(`Symlinking completion for ${$} from ${I} to ${M}`),notFound:($)=>Z(`Completion file not found: ${$}`),directoryListing:($)=>Z(` ${$}`),preparedFromUrl:($,I)=>Z(`install: prepared ${$} completion source at ${I}`),prepareFailed:($)=>Z(`install: failed to prepare ${$} completion`)},hookExecutor:{executingHook:($,I)=>Z(`Executing ${$} hook with ${I}ms timeout`),hookCompleted:($,I)=>Z(`Hook ${$} completed successfully in ${I}ms`),continuingDespiteFailure:($)=>Z(`Continuing installation despite ${$} hook failure`),stoppingDueToFailure:($)=>Z(`Stopping hook execution due to failure in ${$} hook`),timeoutExceeded:($,I)=>Z(`Hook ${$} timed out after ${I}ms`)}};async function Y0($,I,M,G,J,Q,Y){let X=Y.getSubLogger({name:"createBinaryEntrypoint"}),R=FM.join(Q,I),W=FM.join(R,G),q=FM.join(W,M),U=FM.join(W,J);if(U===q)return;if(!await $.exists(U)){let K=`Cannot create entrypoint: target binary does not exist at ${U}`;throw X.error(F.binarySymlink.targetBinaryMissing(I,M,U)),Error(K)}await $.ensureDir(W);try{if(await $.exists(q))X.debug(F.binarySymlink.removingExisting(q)),await $.rm(q,{force:!0})}catch(K){X.error(F.binarySymlink.removeExistingFailed(q),K);let O=K instanceof Error?K.message:String(K);throw Error(`Failed to remove old entrypoint ${q}: ${O}`,{cause:K})}try{let K=FM.relative(W,U);if(X.debug(F.binarySymlink.creating(q,K)),await($ instanceof f?$.withFileType("symlink"):$).symlink(K,q),!(await $.lstat(q)).isSymbolicLink())throw Error("Entrypoint unexpectedly created as regular file instead of symlink")}catch(K){let O=K instanceof Error?K.message:String(K);throw X.error(F.binarySymlink.creationFailed(q,U),K),Error(`Failed to create entrypoint at ${q}: ${O}`,{cause:K})}if(!await $.exists(q))throw X.error(F.binarySymlink.verificationFailed(q)),Error(`Entrypoint creation appeared to succeed but file does not exist at ${q}`);X.debug(F.binarySymlink.createdAndVerified(q,U))}function GI($,I){let M=(G,...J)=>{if(typeof G==="string")return $(G).env(I);return $(G,...J).env(I)};if(Object.assign(M,$),eM($))Object.defineProperty(M,$M,{value:!0,enumerable:!1});return M}function R$($,I){return $ instanceof f?$.withToolName(I):$}import X0 from"crypto";import r$ from"path";var S={initialized:($,I,M,G)=>Z(`Cache directory: ${$}, TTL: ${I} ms, Strategy: ${M}, Enabled: ${G}`),cachingDisabled:($,I)=>Z(`Cache disabled, ${$} for key: ${I}`),entryMissing:($)=>Z(`No cache entry found for key: ${$}`),entryExpired:($)=>Z(`Cache entry expired for key: ${$}`),cacheHit:($,I,M)=>{let G=M!==void 0?`, size: ${M} bytes`:"";return Z(`Cache hit for key: ${$} (${I})${G}`)},cacheStored:($,I,M,G)=>{let J=G!==void 0?`, size: ${G} bytes`:"";return Z(`Cached data for key: ${$} (${I})${J}, expires: ${M}`)},cacheEntryRemoved:($)=>Z(`Removed cache entry for key: ${$}`),cacheCleared:()=>Z("Removed entire cache directory"),expiredEntriesCleared:($)=>Z(`Removed ${$} expired cache entries`),cacheEntryExists:($)=>Z(`Valid cache entry exists for key: ${$}`),noEntryToDelete:($)=>Z(`No cache entry to delete for key: ${$}`),cacheDirectoryMissing:()=>Z("Cache directory does not exist, nothing to clear"),binaryFileMissing:($,I)=>Z(`Binary file missing for key: ${$}, path: ${I}`),contentHashMismatch:($,I,M)=>Z(`Content hash mismatch for key: ${$}, expected: ${I}, actual: ${M}`),metadataProcessingWarning:($,I)=>Z(`Error processing cache file ${$}: ${I}`),retrievalFailed:($,I)=>Z(`Error retrieving cache for key: ${$}, error: ${I}`),storageFailed:($,I)=>Z(`Error caching data for key: ${$}, error: ${I}`),checkFailed:($,I)=>Z(`Error checking cache for key: ${$}, error: ${I}`),deleteFailed:($,I)=>Z(`Error deleting cache entry for key: ${$}, error: ${I}`),clearExpiredFailed:($)=>Z(`Error clearing expired cache entries: ${$}`),clearFailed:($)=>Z(`Error clearing cache: ${$}`),directoryCreationFailed:($)=>Z(`Error ensuring cache directories exist: ${$}`),binaryDirectoryNotConfigured:()=>Z("Binary directory not configured for binary strategy"),binaryDataRequired:()=>Z("Binary storage strategy requires Buffer data")};class JI{config;fileSystem;logger;metadataDir;binariesDir;constructor($,I,M){if(this.logger=$.getSubLogger({name:"FileCache"}),this.fileSystem=I,this.config=M,M.storageStrategy==="json")this.metadataDir=M.cacheDir;else this.metadataDir=r$.join(M.cacheDir,"metadata"),this.binariesDir=r$.join(M.cacheDir,"binaries");this.logger.debug(S.initialized(M.cacheDir,M.defaultTtl,M.storageStrategy,M.enabled))}async get($){let I=this.logger.getSubLogger({name:"get"});if(!this.config.enabled)return I.debug(S.cachingDisabled("returning null",$)),null;try{let M=this.getMetadataFilePath($);if(!await this.fileSystem.exists(M))return I.debug(S.entryMissing($)),null;let G=await this.fileSystem.readFile(M,"utf8"),J=JSON.parse(G);if(this.isExpired(J))return I.debug(S.entryExpired($)),await this.deleteEntry($,J),null;if(J.type==="json")return I.debug(S.cacheHit($,"JSON")),J.data;else{if(!this.binariesDir)throw Error(S.binaryDirectoryNotConfigured());let Q=r$.join(this.binariesDir,J.binaryFileName);if(!await this.fileSystem.exists(Q))return I.warn(S.binaryFileMissing($,Q)),await this.fileSystem.rm(M).catch(()=>{}),null;let Y=await this.fileSystem.readFile(Q),X=Buffer.isBuffer(Y)?Y:Buffer.from(Y),R=X0.createHash("sha256").update(X).digest("hex"),W=J.contentHash;if(R!==W)return I.warn(S.contentHashMismatch($,W,R)),await this.deleteEntry($,J),null;return I.debug(S.cacheHit($,"binary",X.length)),X}}catch(M){return I.warn(S.retrievalFailed($,this.getErrorMessage(M))),null}}async set($,I,M){let G=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){G.debug(S.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let J=M??this.config.defaultTtl,Q=Date.now();if(this.config.storageStrategy==="json"){let Y={type:"json",data:I,timestamp:Q,expiresAt:Q+J},X=this.getMetadataFilePath($);await this.fileSystem.writeFile(X,JSON.stringify(Y,null,2),"utf8"),G.debug(S.cacheStored($,"JSON",new Date(Y.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(I))throw Error(S.binaryDataRequired());if(!this.binariesDir)throw Error(S.binaryDirectoryNotConfigured());let Y=I,X=X0.createHash("sha256").update(Y).digest("hex"),R=`${X}.bin`,W=r$.join(this.binariesDir,R);await this.fileSystem.writeFile(W,Y);let q={type:"binary",binaryFileName:R,contentHash:X,size:Y.length,timestamp:Q,expiresAt:Q+J},U=this.getMetadataFilePath($);await this.fileSystem.writeFile(U,JSON.stringify(q,null,2),"utf8"),G.debug(S.cacheStored($,"binary",new Date(q.expiresAt).toISOString(),Y.length))}}catch(J){let Q=this.getErrorMessage(J);throw G.warn(S.storageFailed($,Q)),Error(`Failed to cache data: ${Q}`,{cause:J})}}async setDownload($,I,M,G,J){let Q=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){Q.debug(S.cachingDisabled("skipping setDownload",$));return}try{await this.ensureCacheDirectories();let Y=M??this.config.defaultTtl,X=Date.now();if(this.config.storageStrategy==="json")throw Error("Download caching requires binary storage strategy");if(!this.binariesDir)throw Error(S.binaryDirectoryNotConfigured());let R=X0.createHash("sha256").update(I).digest("hex"),W=`${R}.bin`,q=r$.join(this.binariesDir,W);await this.fileSystem.writeFile(q,I);let U={type:"binary",binaryFileName:W,contentHash:R,size:I.length,url:G,contentType:J,timestamp:X,expiresAt:X+Y},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(U,null,2),"utf8"),Q.debug(S.cacheStored($,"download",new Date(U.expiresAt).toISOString(),I.length))}catch(Y){let X=this.getErrorMessage(Y);throw Q.warn(S.storageFailed($,X)),Error(`Failed to cache download: ${X}`,{cause:Y})}}async has($){let I=this.logger.getSubLogger({name:"has"});if(!this.config.enabled)return I.debug(S.cachingDisabled("returning false",$)),!1;try{let M=this.getMetadataFilePath($);if(!await this.fileSystem.exists(M))return I.debug(S.entryMissing($)),!1;let G=await this.fileSystem.readFile(M,"utf8"),J=JSON.parse(G);if(this.isExpired(J))return I.debug(S.entryExpired($)),!1;if(J.type==="binary"&&this.binariesDir){let Q=r$.join(this.binariesDir,J.binaryFileName);if(!await this.fileSystem.exists(Q))return I.debug(S.binaryFileMissing($,Q)),!1}return I.debug(S.cacheEntryExists($)),!0}catch(M){return I.warn(S.checkFailed($,this.getErrorMessage(M))),!1}}async delete($){let I=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){I.debug(S.cachingDisabled("skipping delete",$));return}try{let M=this.getMetadataFilePath($);if(await this.fileSystem.exists(M)){let G=await this.fileSystem.readFile(M,"utf8"),J=JSON.parse(G);await this.deleteEntry($,J),I.debug(S.cacheEntryRemoved($))}else I.debug(S.noEntryToDelete($))}catch(M){let G=this.getErrorMessage(M);throw I.warn(S.deleteFailed($,G)),Error(`Failed to delete cache entry: ${G}`,{cause:M})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(S.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(S.cacheDirectoryMissing());return}let I=await this.fileSystem.readdir(this.metadataDir),M=0;for(let G of I){if(!G.endsWith(".json"))continue;let J=r$.join(this.metadataDir,G);try{let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);if(this.isExpired(Y)){let X=r$.basename(G,".json");await this.deleteEntry(X,Y),M++}}catch(Q){$.warn(S.metadataProcessingWarning(G,this.getErrorMessage(Q))),await this.fileSystem.rm(J).catch(()=>{}),M++}}$.debug(S.expiredEntriesCleared(M))}catch(I){let M=this.getErrorMessage(I);throw $.warn(S.clearExpiredFailed(M)),Error(`Failed to clear expired cache entries: ${M}`,{cause:I})}}async clear(){let $=this.logger.getSubLogger({name:"clear"});if(!this.config.enabled){$.debug(S.cachingDisabled("skipping clear","N/A"));return}try{if(await this.fileSystem.exists(this.config.cacheDir))await this.fileSystem.rm(this.config.cacheDir,{recursive:!0,force:!0}),$.debug(S.cacheCleared());else $.debug(S.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(I){let M=this.getErrorMessage(I);throw $.warn(S.clearFailed(M)),Error(`Failed to clear cache: ${M}`,{cause:I})}}getMetadataFilePath($){let I=X0.createHash("md5").update($).digest("hex");return r$.join(this.metadataDir,`${I}.json`)}async ensureCacheDirectories(){let $=this.logger.getSubLogger({name:"ensureCacheDirectories"});try{if(await this.fileSystem.ensureDir(this.metadataDir),this.binariesDir)await this.fileSystem.ensureDir(this.binariesDir)}catch(I){let M=this.getErrorMessage(I);throw $.warn(S.directoryCreationFailed(M)),Error(`Failed to create cache directories: ${M}`,{cause:I})}}getErrorMessage($){if($ instanceof Error)return $.message;return String($)}isExpired($){return Date.now()>$.expiresAt}async deleteEntry($,I){let M=this.getMetadataFilePath($);if(await this.fileSystem.exists(M))await this.fileSystem.rm(M);if(I.type==="binary"&&this.binariesDir){let G=r$.join(this.binariesDir,I.binaryFileName);if(await this.fileSystem.exists(G))await this.fileSystem.rm(G)}}}import q4 from"crypto";function bJ($,I={}){let M={headers:I.headers||{}},G={url:$,options:M};return`download:${q4.createHash("sha256").update(JSON.stringify(G)).digest("hex")}`}import U4 from"path";var LM={strategyCreated:($,I)=>Z(`Created ${$}${I}`),downloadStarted:($)=>Z(`Downloading URL: ${$}`),downloadToFileStarted:($,I)=>Z(`Downloading URL ${$} to file: ${I}`)};var B$={strategyWrapped:($,I)=>Z(`Wrapping strategy ${$} with cache, TTL: ${I} ms`),cachingDisabled:($,I,M)=>Z(`Cache disabled, ${$} for key: ${I} (${M})`),cacheHit:($,I,M)=>{let G=M!==void 0?`, size: ${M} bytes`:"";return Z(`Cache hit for key: ${$} (${I})${G}`)},cacheStored:($,I,M,G)=>{let J=G!==void 0?`, size: ${G} bytes`:"";return Z(`Cached data for key: ${$} (${I})${J}, expires: ${M}`)},cacheStorageFailed:($)=>Z(`Error caching data for key: ${$}`),cacheCheckFailed:($)=>Z(`Error checking cache for key: ${$}`),cacheMiss:($)=>Z(`No cache entry found for key: ${$}`),cacheDisabledForProgress:($)=>Z(`Cache disabled, caching for key: ${$} (reason: progress callback)`),readFileForCaching:($)=>Z(`read file for caching: ${$}`),downloadedFileExists:($,I)=>Z(`Downloaded file exists (${$}): ${I}`),downloadedFileCached:($,I)=>Z(`Successfully read file for caching from ${$}, size: ${I} bytes`),downloadedFileMissing:($)=>Z(`Downloaded file not found: ${$}`),downloadedFileReadFailed:($)=>Z(`Failed to read ${$}`),downloadFromStrategy:($)=>Z(`download from ${$}`),cachedFileWritten:($)=>Z(`[CachedDownloadStrategy] write ${$}`)},b$={constructed:($)=>Z(`NodeFetchStrategy constructed (fileSystem ${$})`),downloadTimeout:($)=>Z(`Download timeout for ${$}`),responseBodyReadFailed:($,I)=>Z(`Failed to read response body for ${$}: ${String(I)}`),downloadFailed:($,I,M,G)=>Z(`Download failed: url=${$}, statusCode=${I}, statusText=${M}, responseBody=${G??"N/A"}`),downloadAttempt:($,I)=>Z(`Attempt ${$}: Downloading ${I}`),downloadSuccessful:($,I)=>Z(`Download successful for ${$}, size: ${I} bytes`),savingToDestination:($)=>Z(`Saving to destination: ${$}`),savedSuccessfully:($)=>Z(`Successfully wrote to ${$} using IFileSystem`),downloadAttemptError:($,I,M)=>Z(`Error during download attempt ${$} for ${I}: ${String(M)}`),retryingDownload:($,I,M,G)=>Z(`Retrying download for ${$}, attempt ${I}/${M} after ${G}ms`),exhaustedRetries:($)=>Z(`Exhausted retries for ${$}`)},QI={errorCreated:($,I,M)=>Z(`${$} created: message=${I}, url=${M}`),networkErrorCreated:($,I,M)=>Z(`NetworkError created: message=${$}, url=${I}, originalError=${String(M)}`),httpErrorCreated:($,I,M,G,J,Q)=>Z(`HttpError created: message=${$}, url=${I}, statusCode=${M}, statusText=${G}, responseBody=${String(J)}, responseHeaders=${JSON.stringify(Q??{})}`),notFoundErrorCreated:($,I,M)=>Z(`NotFoundError created: url=${$}, responseBody=${String(I)}, responseHeaders=${JSON.stringify(M??{})}`),forbiddenErrorCreated:($,I,M)=>Z(`ForbiddenError created: url=${$}, responseBody=${String(I)}, responseHeaders=${JSON.stringify(M??{})}`),rateLimitErrorCreated:($,I,M,G,J,Q,Y)=>Z(`RateLimitError created: message=${$}, url=${I}, statusCode=${M}, statusText=${G}, responseBody=${String(J)}, responseHeaders=${JSON.stringify(Q??{})}, resetTimestamp=${String(Y)}`),clientErrorCreated:($,I,M,G,J)=>Z(`ClientError created: url=${$}, statusCode=${I}, statusText=${M}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(J??{})}`),serverErrorCreated:($,I,M,G,J)=>Z(`ServerError created: url=${$}, statusCode=${I}, statusText=${M}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(J??{})}`)};class xG{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,I,M,G,J=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=I,this.cache=M,this.underlyingStrategy=G,this.cacheTtl=J,this.name=`cached-${G.name}`,this.logger.debug(B$.strategyWrapped(G.name,J))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,I,M,G,J){if($.trace(B$.cacheHit(M,"binary",I.length),{url:G}),J.onProgress)J.onProgress(0,I.length);if(J.destinationPath){if(await this.fileSystem.ensureDir(U4.dirname(J.destinationPath)),await this.fileSystem.writeFile(J.destinationPath,I),$.trace(B$.cachedFileWritten(J.destinationPath)),J.onProgress)J.onProgress(I.length,I.length);return}if(J.onProgress)J.onProgress(I.length,I.length);return I}async readFileForCaching($,I){$.trace(B$.readFileForCaching(I));try{let M=await this.fileSystem.exists(I);if($.trace(B$.downloadedFileExists(I,M)),M){let G=await this.fileSystem.readFileBuffer(I);return $.trace(B$.downloadedFileCached(I,G.length),{path:I,size:G.length}),G}else return $.trace(B$.downloadedFileMissing(I)),null}catch(M){return $.trace(B$.downloadedFileReadFailed(I),M),null}}async determineBufferToCache($,I,M){if(I instanceof Buffer)return I;else if(M.destinationPath&&I===void 0)return await this.readFileForCaching($,M.destinationPath);return null}async cacheResult($,I,M,G,J){try{await this.cache.setDownload(M,I,this.cacheTtl,G,this.extractContentTypeFromHeaders(J.headers)),$.trace(B$.cacheStored(M,"binary","TTL-based",I.length),{url:G})}catch(Q){$.trace(B$.cacheStorageFailed(M),Q)}}async download($,I={}){let M=this.logger.getSubLogger({name:"download"}),G=bJ($,I);try{let Y=await this.cache.get(G);if(Y)return await this.handleCacheHit(M,Y,G,$,I);M.trace(B$.cacheMiss(G),{url:$})}catch(Y){M.trace(B$.cacheCheckFailed(G),Y)}M.trace(B$.downloadFromStrategy(this.underlyingStrategy.name),{url:$});let J=await this.underlyingStrategy.download($,I),Q=await this.determineBufferToCache(M,J,I);if(Q)await this.cacheResult(M,Q,G,$,I);return J}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class DG extends Error{url;constructor($,I,M){super(I);let G=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=M,G.debug(QI.errorCreated("DownloaderError",I,M))}}class q$ extends DG{originalError;constructor($,I,M,G){super($,I,M);let J=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=G,J.debug(QI.networkErrorCreated(I,M,G),G)}}class F$ extends DG{statusCode;statusText;responseBody;responseHeaders;constructor($,I,M,G,J,Q,Y){super($,I,M);let X=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=G,this.statusText=J,this.responseBody=Q,this.responseHeaders=Y,X.debug(QI.httpErrorCreated(I,M,G,J,Q,Y),{url:M,statusCode:G,statusText:J,responseBody:Q,responseHeaders:Y})}}class N$ extends F${constructor($,I,M,G){super($,"Resource not found",I,404,"Not Found",M,G);let J=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",J.debug(QI.notFoundErrorCreated(I,M,G),{url:I,responseBody:M,responseHeaders:G})}}class vI extends F${constructor($,I,M,G){super($,"Access forbidden",I,403,"Forbidden",M,G);let J=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",J.debug(QI.forbiddenErrorCreated(I,M,G),{url:I,responseBody:M,responseHeaders:G})}}class BI extends F${resetTimestamp;constructor($,I,M,G,J,Q,Y,X){super($,I,M,G,J,Q,Y);let R=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=X,R.debug(QI.rateLimitErrorCreated(I,M,G,J,Q,Y,X),{url:M,statusCode:G,statusText:J,responseBody:Q,responseHeaders:Y,resetTimestamp:X})}}class PI extends F${constructor($,I,M,G,J,Q){super($,`Client error: ${G}`,I,M,G,J,Q);let Y=$.getSubLogger({name:"ClientError"});this.name="ClientError",Y.debug(QI.clientErrorCreated(I,M,G,J,Q),{url:I,statusCode:M,statusText:G,responseBody:J,responseHeaders:Q})}}class CI extends F${constructor($,I,M,G,J,Q){super($,`Server error: ${G}`,I,M,G,J,Q);let Y=$.getSubLogger({name:"ServerError"});this.name="ServerError",Y.debug(QI.serverErrorCreated(I,M,G,J,Q),{url:I,statusCode:M,statusText:G,responseBody:J,responseHeaders:Q})}}class AG{name="node-fetch";logger;fileSystem;proxyConfig;constructor($,I,M){this.logger=$.getSubLogger({name:"NodeFetchStrategy"}),this.logger.debug(b$.constructed(I?"provided":"undefined")),this.fileSystem=I,this.proxyConfig=M}async isAvailable(){return typeof fetch==="function"}getResponseHeaders($){let I={};return $.forEach((M,G)=>{I[G]=M}),I}parseRateLimitReset($){let I=$.get("X-RateLimit-Reset");if(I){let G=parseInt(I,10);if(!Number.isNaN(G))return G*1000}let M=$.get("Retry-After");if(M){let G=parseInt(M,10);if(!Number.isNaN(G))return Date.now()+G*1000;let J=Date.parse(M);if(!Number.isNaN(J))return J}return}async setupDownloadRequest($,I,M){let G=new AbortController,J;if(M)J=setTimeout(()=>{this.logger.debug(b$.downloadTimeout($)),G.abort()},M);return{response:await t6($,{headers:I,signal:G.signal},this.proxyConfig),timeoutId:J}}async handleErrorResponse($,I){let M;try{M=await $.text()}catch(X){this.logger.debug(b$.responseBodyReadFailed(I,X))}let G=this.getResponseHeaders($.headers),J=$.status,Q=$.statusText;if(this.logger.debug(b$.downloadFailed(I,J,Q,M?.substring(0,100))),J===404)throw new N$(this.logger,I,M,G);let Y=this.parseRateLimitReset($.headers);if(J===403){if(Y)throw new BI(this.logger,"Forbidden: Rate limit likely exceeded",I,J,Q,M,G,Y);throw new vI(this.logger,I,M,G)}if(J===429)throw new BI(this.logger,"Too Many Requests",I,J,Q,M,G,Y);if(J>=400&&J<500)throw new PI(this.logger,I,J,Q,M,G);if(J>=500&&J<600)throw new CI(this.logger,I,J,Q,M,G);throw new F$(this.logger,`HTTP error ${J}`,I,J,Q,M,G)}async processResponseStream($,I,M){let G=$.headers.get("content-length"),J=null;if(G){let R=parseInt(G,10);if(!Number.isNaN(R))J=R}let Q=0;if(M)M(Q,J);let Y=[],X=$.body?.getReader();if(!X)throw new q$(this.logger,"Response body is not readable.",I);while(!0){let{done:R,value:W}=await X.read();if(R)break;if(W){if(Y.push(Buffer.from(W)),Q+=W.length,M)M(Q,J)}}return Buffer.concat(Y)}async handleDownloadAttempt($,I,M){let{headers:G,timeout:J,onProgress:Q,destinationPath:Y}=I;this.logger.debug(b$.downloadAttempt(M+1,$));let{response:X,timeoutId:R}=await this.setupDownloadRequest($,G,J);if(R)clearTimeout(R);if(!X.ok)await this.handleErrorResponse(X,$);let W=await this.processResponseStream(X,$,Q);if(this.logger.debug(b$.downloadSuccessful($,W.length)),Y){this.logger.debug(b$.savingToDestination(Y)),await this.fileSystem.writeFile(Y,W),this.logger.debug(b$.savedSuccessfully(Y));return}return W}handleDownloadError($,I,M,G,J){if(this.logger.debug(b$.downloadAttemptError(M+1,I,$)),M>=G){if($ instanceof F$||$ instanceof q$)throw $;let Q=`Failed to download ${I}`;if($ instanceof Error&&$.name==="AbortError")Q=`Download timed out for ${I}`;else if($ instanceof Error)Q=$.message;throw new q$(this.logger,Q,I,$ instanceof Error?$:void 0)}}async retryDownload($,I,M,G,J){this.logger.debug(b$.retryingDownload($,I+2,M+1,G)),await new Promise((Q)=>setTimeout(Q,G))}async download($,I){let{retryCount:M=0,retryDelay:G=1000,onProgress:J}=I,Q=0;while(Q<=M)try{return await this.handleDownloadAttempt($,I,Q)}catch(Y){if(this.handleDownloadError(Y,$,Q,M,J),Q<M)await this.retryDownload($,Q,M,G,J),Q++}throw this.logger.debug(b$.exhaustedRetries($)),new q$(this.logger,`Download failed for ${$} after ${M} retries.`,$)}}class FG{strategies=[];fs;logger;constructor($,I,M,G,J){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=I,typeof M<"u")this.strategies=M;else{let Q=new AG(this.logger,this.fs,J),Y=J?.enabled?` (proxy port ${J.port})`:"";if(G)this.logger.debug(LM.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${Y}`)),this.strategies.push(new xG(this.logger,this.fs,G,Q));else this.logger.debug(LM.strategyCreated("NodeFetchStrategy",Y||" (no cache)")),this.strategies.push(Q)}}registerStrategy($){this.strategies.unshift($)}async tryDownloadWithStrategy($,I,M){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};return{success:!0,buffer:await $.download(I,M)}}async download($,I,M={}){if($.getSubLogger({name:"Downloader"}).getSubLogger({name:"download"}).debug(LM.downloadStarted(I)),this.strategies.length===0)throw Error("No download strategies registered.");let J;for(let Q of this.strategies)try{let Y=await this.tryDownloadWithStrategy(Q,I,M);if(Y.success)return Y.buffer}catch(Y){J=this.normalizeError(Y)}if(J)throw J;throw Error(`No available download strategy succeeded for ${I}.`)}async tryDownloadToFileWithStrategy($,I,M){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};if(await $.download(I,M)===void 0)return{success:!0};throw Error("Strategy returned Buffer instead of void for downloadToFile method")}normalizeError($){if($ instanceof Error)return $;if(typeof $==="string")return Error($);return Error(`An unknown error occurred during download: ${JSON.stringify($)}`)}async downloadToFile($,I,M,G={}){$.getSubLogger({name:"Downloader"}).getSubLogger({name:"downloadToFile"}).debug(LM.downloadToFileStarted(I,M));let Q={...G,destinationPath:M};if(this.strategies.length===0)throw Error("No download strategies registered.");let Y;for(let X of this.strategies)try{if((await this.tryDownloadToFileWithStrategy(X,I,Q)).success)return}catch(R){Y=this.normalizeError(R)}if(Y)throw Y;throw Error(`No available download strategy succeeded for ${I}.`)}}import*as IM from"cli-progress";class LG{filename;progressBar=null;enabled;startTime=0;constructor($,I={}){this.filename=$;this.enabled=I.enabled??!0}createCallback(){if(!this.enabled)return;return($,I)=>{if(this.startTime===0)if(this.startTime=Date.now(),I)this.progressBar=new IM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},IM.Presets.shades_classic),this.progressBar.start(I,0,{speed:"0 B/s"});else this.progressBar=new IM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},IM.Presets.shades_classic),this.progressBar.start(100,0,{speed:"0 B/s"});if(this.progressBar){let M=(Date.now()-this.startTime)/1000,G=M>0?`${this.formatBytes($/M)}/s`:"0 B/s";if(I){if(this.progressBar.update($,{speed:G}),$>=I)this.progressBar.stop()}else{let J=Math.floor(Date.now()/100)%100;this.progressBar.update(J,{speed:G,value:this.formatBytes($)})}}}}clear(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}finish(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}formatBytes($){let I=["B","KB","MB","GB"],M=$,G=0;while(M>=1024&&G<I.length-1)M/=1024,G++;return`${M.toFixed(M>=10?0:1)} ${I[G]}`}}function NJ($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.NO_COLOR)return!1;return!0}async function U$($,I,M,G,J,Q){let Y=NJ(Q?.quiet),X=new LG(G,{enabled:Y});try{await J.download($,I,{destinationPath:M,onProgress:X.createCallback()})}finally{X.finish()}}function yJ($){return $.installParams?.hooks}async function y$($,I,M,G,J){let Y=yJ($)?.["after-download"];if(!Y)return{success:!0};J.debug(F.lifecycle.hookExecution("after-download"));let X=M.createEnhancedContext(I,G);for(let R of Y){let W=await M.executeHook(J,"after-download",R,X);if(!W.success)return{success:!1,error:`afterDownload hook failed: ${W.error}`}}return{success:!0}}async function MM($,I,M,G,J){let Y=yJ($)?.["after-extract"];if(!Y)return{success:!0};J.debug(F.lifecycle.hookExecution("after-extract"));let X=M.createEnhancedContext(I,G);for(let R of Y){let W=await M.executeHook(J,"after-extract",R,X);if(!W.success)return{success:!1,error:`afterExtract hook failed: ${W.error}`}}return{success:!0}}function H4($){return typeof $==="object"&&$!==null}function K4($){if(!H4($))return!1;let I=$.name;if(typeof I!=="string")return!1;return I==="ShellError"}function vJ($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function PJ($){if(K4($)){let I=vJ($.stderr);if(I.length>0)return I;let M=vJ($.stdout);if(M.length>0)return M;if($.message)return $.message;return`exit code ${$.exitCode??"unknown"}`}if($ instanceof Error)return $.message;return String($)}function s$($){if(!$||$.length===0)return[];return $.map((I)=>typeof I==="string"?{name:I,pattern:`{,*/}${I}`}:I)}function GM($){return s$($).map((M)=>M.name)}import{join as _4}from"path";function o($,I){return s$($).map((G)=>_4(I,G.name))}import cJ from"path";import{codeFrameColumns as O4}from"@babel/code-frame";function j4($){return typeof $==="object"&&$!==null}function uJ($){if(!j4($))return!1;let I=$.name;if(typeof I!=="string")return!1;return I==="ShellError"}function V4($){return $.isTracingEnabled()}function z4($){return $.endsWith(`
60
60
  `)?$:`${$}
61
- `}function dY($,M,J){return{filePath:$,line:M,column:J}}function yY($,M){let J=M.exec($);if(!J)return null;let Q=J[1],Y=Number(J[2]),G=Number(J[3]);if(!Q||Number.isNaN(Y)||Number.isNaN(G))return null;return dY(Q,Y,G)}function KX($){let M=/([^\s]+\.tool\.ts):(\d+)\s*$/.exec($);if(!M)return null;let J=M[1],Q=Number(M[2]);if(!J||Number.isNaN(Q))return null;return dY(J,Q,1)}function HX($){let M=$.split(`
62
- `);for(let J of M){if(!J.includes(".tool.ts"))continue;let Q=yY(J,/\(([^)]+\.tool\.ts):(\d+):(\d+)\)\s*$/);if(Q)return Q;let Y=yY(J,/\s+at\s+([^\s]+\.tool\.ts):(\d+):(\d+)\s*$/);if(Y)return Y;let G=KX(J);if(G)return G}return null}async function _X($,M){if(!await $.exists(M.filePath))return null;let Q=await $.readFile(M.filePath,"utf8"),Y=WX(Q,{start:{line:M.line,column:M.column}},{linesAbove:2,linesBelow:2,highlightCode:!0,forceColor:!0});return`${M.filePath}:${M.line}:${M.column}
63
- ${Y}
64
- `}function RX($){let M=[],J=typeof $.exitCode==="number"?String($.exitCode):"unknown";M.push(`exit code: ${J}`);let Q=PY($.stderr);if(Q.length>0)M.push("stderr:"),M.push(Q);let Y=PY($.stdout);if(Y.length>0)M.push("stdout:"),M.push(Y);return M.join(`
65
- `)}function PY($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");return""}function OX($,M){let J=[];if($ instanceof Error){if(J.push(`${$.name}: ${$.message}`),M&&typeof $.stack==="string"&&$.stack.length>0)J.push("stack:"),J.push($.stack);return J.join(`
66
- `)}return J.push(String($)),J.join(`
67
- `)}async function jX($,M){if(!M)return null;let J=HX(M);if(!J)return null;return await _X($,J)}function VX($,M){if(!M)return[];if(!$||$.length===0)return[];return["stack:",$]}async function zX($,M){let J=[RX($)],Q=typeof $.stack==="string"?$.stack:void 0,Y=VX(Q,M);return J.push(...Y),J}async function BX($,M){return[OX($,M)]}async function DX($){let M=IX($.logger),J=[],Q=AX($.error),Y=await jX($.fileSystem,Q);if(Y)J.push("---"),J.push(Y),J.push("---");if(M)if(CY($.error)){let X=await zX($.error,!0);J.push(...X)}else{let X=await BX($.error,!0);J.push(...X)}if(J.length===0)return"";return UX(J.join(`
68
- `))}function AX($){if(CY($))return typeof $.stack==="string"?$.stack:void 0;if($ instanceof Error)return $.stack;return}async function uY($){let M=await DX($);if(M.length>0)$.writeOutput(M)}function EX($){if(typeof $!=="object"||$===null)return!1;return $.name==="ShellError"}function FX($,M){return Object.assign((Q,...Y)=>{return $(Q,...Y).cwd(M)},$)}function LX($,M,J,Q){if(M.length===0)return $;let Y=J===4?";":":",G=Q.PATH||"",X=[...M,G].join(Y),Z={...Q,PATH:X};return Object.assign((I,...U)=>{let K=I[0]||"";for(let _=0;_<U.length;_++)K+=String(U[_])+(I[_+1]||"");return $`sh -c ${K}`.env(Z)},$)}class LQ{defaultTimeoutMs=60000;writeOutput;constructor($){this.writeOutput=$}async executeHook($,M,J,Q,Y={}){let G=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHook",context:M}),X=Y.timeoutMs??this.defaultTimeoutMs,Z=Y.continueOnError??!1,q=Date.now();G.debug(L.hookExecutor.executingHook(M,X));let I;try{let U=J(Q),K=new Promise((O,B)=>{I=setTimeout(()=>{B(Error(L.hookExecutor.timeoutExceeded(M,X)))},X)});if(await Promise.race([U,K]),I!==void 0)clearTimeout(I);let H=Date.now()-q;return G.debug(L.hookExecutor.hookCompleted(M,H)),{success:!0,durationMs:H,skipped:!1}}catch(U){if(I!==void 0)clearTimeout(I);let K=Date.now()-q,H=U instanceof Error?U.message:String(U),_=vY(U);if(G.error(L.outcome.hookFailed(_),U),EX(U))await uY({fileSystem:Q.fileSystem,logger:G,hookName:M,toolName:Q.toolName,error:U,writeOutput:this.writeOutput});if(Z)G.debug(L.hookExecutor.continuingDespiteFailure(M));return{success:!1,error:H,durationMs:K,skipped:!1}}}createEnhancedContext($,M,J){let Q=M instanceof f?M.withToolName($.toolName):M,Y=$.toolConfig?.configFilePath,G=Y?fY.dirname(Y):void 0,X="binaryPaths"in $&&Array.isArray($.binaryPaths)?$.binaryPaths:[],Z=[...new Set(X.map((H)=>fY.dirname(H)))],q,I=J&&!s0($.$);if(I&&$.installEnv)q=W$({logger:J,skipCommandLog:!0,env:$.installEnv});else q=$.$;let U=$.installEnv??process.env;if(Z.length>0)q=LX(q,Z,$.systemInfo.platform,U);if(G)q=FX(q,G);if(I)q=FY(q,J);return{...$,$:q,fileSystem:Q}}async executeHooks($,M,J){let Q=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHooks"}),Y=[];for(let X of M){let{name:Z,hook:q,options:I}=X,U=await this.executeHook($,Z,q,J,I);if(Y.push(U),!U.success&&!I?.continueOnError){Q.debug(L.hookExecutor.stoppingDueToFailure(Z));break}}return Y}}import{minimatch as xX}from"minimatch";import DM from"path";async function AM($,M,J,Q,Y,G){let X=G.getSubLogger({name:"setupBinariesFromArchive"}),Z=DM.join(Q.projectConfig.paths.generatedDir,"binaries"),q=l$(J.binaries),I=DM.basename(Q.stagingDir);await TX($,M,q,I,Y,Z,X)}async function TX($,M,J,Q,Y,G,X){let Z=X.getSubLogger({name:"setupBinariesUsingPatterns"}),q=!1;for(let I of J){let{name:U,pattern:K}=I,H=await wX($,Y,K,U,Z);if(!H){Z.error(L.binarySetupService.binaryNotFound(U,K));let O=await pY($,Y);if(O.length>0){let B=O.join(`
69
- `);Z.error(L.binarySetupService.extractedFilesTree(Y,B))}continue}let _=DM.relative(Y,H);await JJ($,M,U,Q,_,G,Z),q=!0}return q}async function pY($,M,J="",Q=3,Y=0){let G=[];if(Y>=Q)return G;let X=[];try{X=await $.readdir(M)}catch{return G}let Z=X.toSorted();for(let q=0;q<Z.length;q++){let I=Z[q];if(!I)continue;let U=q===Z.length-1,K=DM.join(M,I),H=U?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",_=J+(U?" ":"\u2502 "),O=await kX($,K,I,J,H,_,Q,Y);G.push(...O)}return G}async function kX($,M,J,Q,Y,G,X,Z){let q=[];try{let I=await $.stat(M),U=I.isDirectory()?`${J}/`:J;if(q.push(`${Q}${Y}${U}`),I.isDirectory()&&Z<X-1){let K=await pY($,M,G,X,Z+1);q.push(...K)}}catch{q.push(`${Q}${Y}${J} (inaccessible)`)}return q}async function SX($,M){return((await $.stat(M)).mode&73)!==0}async function wX($,M,J,Q,Y){Y.getSubLogger({name:"findBinaryUsingPattern"}).debug(L.binarySetupService.searchingWithPattern(J,M));let Z=(await wM($,M,M)).filter((K)=>xX(K,J));if(Z.length===0)return null;let q=[];for(let K of Z){let H=DM.join(M,K);if(await SX($,H))q.push(K)}if(q.length===0)return null;let I=q.find((K)=>DM.basename(K)===Q);if(I)return DM.join(M,I);let U=q[0];if(U)return DM.join(M,U);return null}import xQ from"path";async function M0($,M,J,Q,Y,G){let X=G.getSubLogger({name:"setupBinariesFromDirectDownload"}),Z=l$(J.binaries),q=Z[0]?.name||M;await $.chmod(Y,493);let I=xQ.join(Q.projectConfig.paths.generatedDir,"binaries"),U=xQ.basename(Y),K=xQ.basename(Q.stagingDir);if(await JJ($,M,q,K,U,I,X),Z.length>1)X.debug(L.binarySetupService.directDownloadSingleBinary(Z.length,q))}async function Q$($,M,J,Q){try{return await Q()}catch(Y){return J.error(L.outcome.installFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:String(Y)}}}class TQ{projectConfig;systemInfo;resolvedFileSystem;fileSystem;$shell;emitInstallEvent;constructor($){this.projectConfig=$.projectConfig,this.systemInfo=$.systemInfo,this.resolvedFileSystem=$.resolvedFileSystem,this.fileSystem=$.fileSystem,this.$shell=$.$shell,this.emitInstallEvent=$.emitInstallEvent}createMinimalContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:"minimalContext"});return{...R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),stagingDir:"",timestamp:"",toolConfig:$.toolConfig,$:$.$shell??$M(this.$shell,process.env),fileSystem:this.fileSystem}}createBaseInstallContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:`install-${$.toolName}`}),Q=R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),Y=$.$shell??$M(this.$shell,process.env),G=(I={})=>({...Q,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:Y,fileSystem:this.fileSystem,installEnv:$.installEnv,...I}),X=G(),Z=async(I,U)=>{await this.emitInstallEvent({type:I,toolName:$.toolName,context:{...G(U),emitEvent:Z,logger:J}})};return X.emitEvent=Z,{context:X,logger:J}}getToolDirectory($){return $.configFilePath?bX.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function GJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function NX($){return Array.isArray($)&&$.every((M)=>typeof M==="function")}function vX($){if(!GJ($))return!1;return typeof $.getSubLogger==="function"}function kQ($){if(!GJ($))return;let M=$.installParams;if(!GJ(M))return;let J=M.hooks;if(!GJ(J))return;let Q=Object.entries(J);if(Q.length===0)return;let Y={};for(let[G,X]of Q){if(!NX(X))return;Y[G]=X}return Y}class SQ{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,M,J){if(!M)return;let Q=kQ(M);if(!Q)return;let Y=Q[$.type];if(!Y)return;let G=$.context.logger,X=vX(G)?G:J,Z=$.context.fileSystem,q=this.hookExecutor.createEnhancedContext($.context,Z,X);for(let I of Y){let U=await this.hookExecutor.executeHook(X,$.type,I,q);if(!U.success){let K=U.error?`${$.type} hook failed: ${U.error}`:`Hook ${$.type} failed`;throw Error(K)}}}async executeBeforeInstallHook($,M,J,Q){let Y=Q.getSubLogger({name:"executeBeforeInstallHook"}),X=kQ($)?.["before-install"];if(!X)return null;Y.debug(L.lifecycle.hookExecution("before-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,Y);for(let q of X){let I=await this.hookExecutor.executeHook(Y,"before-install",q,Z);if(!I.success)return{success:!1,error:`beforeInstall hook failed: ${I.error}`}}return null}async executeAfterInstallHook($,M,J,Q){let Y=Q.getSubLogger({name:"executeAfterInstallHook"}),X=kQ($)?.["after-install"];if(!X)return;Y.debug(L.lifecycle.hookExecution("after-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,Y);for(let q of X)await this.hookExecutor.executeHook(Y,"after-install",q,Z,{continueOnError:!0})}}import QM from"path";function yX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function PX($){let M={};if(!$.success)return M;if(!("metadata"in $))return M;let J=$.metadata;if(!yX(J))return M;let{method:Q,...Y}=J;if(typeof Q==="string")return{...Y,installMethod:Q};return J}class wQ{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,M,J,Q,Y,G){let X=G.getSubLogger({name:"recordInstallation"});if(!Y.success)return;try{let Z="version"in Y&&Y.version?Y.version:Q.timestamp,q=M.installParams,I=q&&typeof q==="object"&&"version"in q&&typeof q.version==="string"?q.version:void 0,U="originalTag"in Y&&typeof Y.originalTag==="string"?Y.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:Z,installPath:J,timestamp:Q.timestamp,binaryPaths:Y.binaryPaths,configuredVersion:I,originalTag:U,...PX(Y)}),X.debug(L.outcome.installSuccess($,Z,"registry-recorded"))}catch(Z){X.error(L.outcome.installFailed("registry-record"),Z)}}async createBinaryEntrypoints($,M,J,Q,Y,G){let X=Q.getSubLogger({name:"createBinaryEntrypoints"}),Z=QM.join(this.projectConfig.paths.binariesDir,$);if(await J.ensureDir(Z),G){let q=QM.join(Z,"external");await J.ensureDir(q);for(let I of M){let U=QM.basename(I),K=QM.join(q,U);try{await this.symlinkGenerator.createBinarySymlink(X,I,K)}catch(H){throw X.error(L.lifecycle.externalBinaryMissing($,U,I)),H}}return}for(let q of M){let I=QM.basename(q),U=QM.join(Y,I);if(q===U)continue;try{if(await J.exists(U))await J.rm(U,{force:!0})}catch(K){throw X.error(L.binarySymlink.removeExistingFailed(U),K),K}try{await J.copyFile(q,U);let H=(await J.stat(q)).mode&511;await J.chmod(U,H)}catch(K){throw X.error(L.binarySymlink.creationFailed(U,q),K),K}}}async updateCurrentSymlink($,M,J,Q,Y){let G=J.getSubLogger({name:"updateCurrentSymlink"}),X=QM.join(this.projectConfig.paths.binariesDir,$),Z=QM.join(X,"current");await M.ensureDir(X);let q=Y?"external":QM.basename(Q);try{if(await M.exists(Z))await M.rm(Z,{force:!0,recursive:!0})}catch(I){throw G.error(L.lifecycle.removingExistingSymlink(Z),I),I}try{await M.withFileType("symlink").symlink(q,Z,"dir")}catch(I){throw G.error(L.lifecycle.creatingExternalSymlink(Z,q),I),I}try{let I=await M.readlink(Z);if(I!==q)throw G.error(L.lifecycle.symlinkVerificationFailed(Z)),Error(`Symlink verification failed: ${Z} points to ${I}, expected ${q}`)}catch(I){throw G.error(L.lifecycle.symlinkVerificationFailed(Z),I),I}}}class bQ{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;completionGenerator;installContextFactory;currentToolConfig;constructor($,M,J,Q,Y,G,X,Z,q,I,U){this.logger=$.getSubLogger({name:"Installer"}),this.fs=M,this.resolvedFs=J,this.projectConfig=Q,this.hookExecutor=I,this.hookLifecycle=new SQ(I),this.toolInstallationRegistry=Y,this.systemInfo=G,this.registry=X,this.installationStateWriter=new wQ({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:Z}),this.$=q,this.completionGenerator=U,this.installContextFactory=new TQ({projectConfig:this.projectConfig,systemInfo:this.systemInfo,resolvedFileSystem:this.resolvedFs,fileSystem:this.fs,$shell:this.$,emitInstallEvent:async(K)=>{await this.registry.emitEvent(K)}}),this.registry.onEvent(async(K)=>{await this.hookLifecycle.handleInstallEvent(K,this.currentToolConfig,this.logger)})}async shouldSkipInstallation($,M,J,Q){let Y=Q.getSubLogger({name:"shouldSkipInstallation"});if(J?.force||J?.skipVersionCheck)return null;let G=await this.toolInstallationRegistry.getToolInstallation($);if(!G)return null;let X=J0.join(this.projectConfig.paths.binariesDir,$,"current"),Z=e(M.binaries,X),I=this.registry.get(M.installationMethod)?.getShellInit?.($,M,X),U=await this.getTargetVersion($,M);if(U){if(G.version===U)return Y.debug(L.outcome.installSuccess($,U,"already-installed")),{success:!0,version:G.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I};return Y.debug(L.outcome.outdatedVersion($,G.version,U)),null}return Y.debug(L.outcome.installSuccess($,G.version,"already-installed-latest")),{success:!0,version:G.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I}}async executeInstallationMethod($,M,J,Q,Y){return await this.registry.install(Y,M.installationMethod,$,M,J,Q)}isShellCompletionConfigInput($){if(typeof $==="string"||typeof $==="function")return!0;if(typeof $!=="object"||$===null)return!1;return"source"in $||"cmd"in $||"url"in $}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin?{bin:$.bin}:{}};if("url"in $)return{url:$.url,...$.source?{source:$.source}:{},...$.bin?{bin:$.bin}:{}};return{source:$.source,...$.bin?{bin:$.bin}:{}}}async prepareUrlCompletionAssets($,M,J,Q,Y){let G=Y.getSubLogger({name:"prepareUrlCompletionAssets"});if(!this.completionGenerator?.prepareUrlCompletionSource)return;let X=["zsh","bash","powershell"],Z=Q??M.version??"latest";for(let q of X){let I=M.shellConfigs?.[q]?.completions;if(!this.isShellCompletionConfigInput(I))continue;let U={version:Z},K=await t$(U,I),H=this.normalizeCompletionConfig(K);if(!H.url)continue;let _={...U,toolName:$,toolInstallDir:J,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,homeDir:this.projectConfig.paths.homeDir,configFilePath:M.configFilePath};try{let O=await this.completionGenerator.prepareUrlCompletionSource(H,$,_);G.debug(L.completion.preparedFromUrl(q,O))}catch(O){G.warn(L.completion.prepareFailed(q),O)}}}async install($,M,J){let Q=this.logger.getSubLogger({name:"install",context:$}),Y=this.getSystemInfo(),G=Y$(M,Y);this.currentToolConfig=G;let X=this.fs.withToolName($);if(J?.shimMode)X.setSuppressLogging(!0);try{let Z=await this.shouldSkipInstallation($,G,J,Q);if(Z)return Z;let q=this.registry.get(G.installationMethod),I=q?.externallyManaged===!0,U=this.projectConfig.paths.binariesDir,K=J0.join(U,$);await X.ensureDir(K);let H=i6(),_=H;if(G.version&&G.version!=="latest")_=G.version;if(!I&&q?.resolveVersion){let g=this.createMinimalContext($,G,Q);try{let $$=await q.resolveVersion($,G,g,Q);if($$)_=$$,Q.debug(L.lifecycle.versionResolved($$));else Q.debug(L.lifecycle.versionFallbackToTimestamp())}catch($$){Q.debug(L.lifecycle.versionResolutionFailed($$))}}let O=CX(),B=J0.join(K,O);if(!I)await X.ensureDir(B),Q.debug(L.lifecycle.directoryCreated(B));let j=`DOTFILES_INSTALLING_${$.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`,V="/home/runner/work/dotfiles/dotfiles/packages/build:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/opt/hostedtoolcache/node/24.14.1/x64/bin:/home/runner/.bun/bin:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin",D=Y.platform===4?";":":",A=I?V:`${B}${D}${V}`,T={...process.env,[j]:"true",PATH:A},S=$M(this.$,T),{context:w,logger:u}=this.createBaseInstallContext($,B,H,G,Q,S,T),i=await this.hookLifecycle.executeBeforeInstallHook(G,w,X,u);if(i)return i;let E;try{E=await this.executeInstallationMethod($,G,w,J,u),E.installationMethod=G.installationMethod;let g=E.success&&"version"in E?E.version:void 0,$$=_===H&&g&&g!==H?g:_,m=I?J0.join(K,"external"):J0.join(K,$$);if(E.success&&!I){if(await X.exists(m))await X.rm(m,{recursive:!0,force:!0});if(await X.rename(B,m),Q.debug(L.lifecycle.directoryRenamed(B,m)),E.success&&"binaryPaths"in E&&E.binaryPaths)E.binaryPaths=E.binaryPaths.map((y)=>y.startsWith(B)?y.replace(B,m):y)}if(E.success&&I)await X.ensureDir(m);let o=E.success&&"binaryPaths"in E?E.binaryPaths:void 0;if(E.success&&o){let y=[];for(let I$ of o)if(await X.exists(I$))y.push(I$);if(y.length>0)await this.installationStateWriter.createBinaryEntrypoints($,y,X,Q,m,I)}if(E.success)await this.installationStateWriter.updateCurrentSymlink($,X,Q,m,I);if(!I&&!E.success&&await X.exists(B)){Q.debug(L.lifecycle.cleaningFailedInstallDir(B)),await X.rm(B,{recursive:!0,force:!0});let y=J0.dirname(B);try{if((await X.readdir(y)).length===0)await X.rmdir(y)}catch{}}if(!E.success&&E.error)Q.error(W(E.error));if(E.success){let y="binaryPaths"in E&&Array.isArray(E.binaryPaths)?E.binaryPaths:[],I$="version"in E?E.version:void 0;await this.prepareUrlCompletionAssets($,G,m,I$,Q);let r$=I?V:`${m}${D}${V}`,d0={...process.env,[j]:"true",PATH:r$},T$=$M(this.$,d0),sJ={...w,$:T$,installedDir:m,binaryPaths:y,version:I$,installEnv:d0};await this.hookLifecycle.executeAfterInstallHook(G,sJ,X,u),await this.installationStateWriter.recordInstallation($,G,m,w,E,u)}return E}catch(g){return E={success:!1,error:g instanceof Error?g.message:String(g),installationMethod:G.installationMethod},Q.error(W(E.error)),E}}catch(Z){let q={success:!1,error:Z instanceof Error?Z.message:String(Z),installationMethod:G.installationMethod};return Q.error(W(q.error)),q}}async getTargetVersion($,M){if(M.version&&M.version!=="latest")return M.version;return null}createMinimalContext($,M,J){return this.installContextFactory.createMinimalContext({toolName:$,toolConfig:M,parentLogger:J})}createBaseInstallContext($,M,J,Q,Y,G=$M(this.$,process.env),X){let Z=Y.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:M,timestamp:J,toolConfig:Q,parentLogger:Z,$shell:G,installEnv:X})}getSystemInfo(){return this.systemInfo}}import{z as yM}from"zod";var u$={installing:($)=>W(`Installing from brew: toolName=${$}`),executingCommand:($)=>W(`installFromBrew: Executing command: ${$}`),fetchingVersion:($)=>W(`Fetching version info for formula: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for formula ${$}`),versionNotFound:($)=>W(`No stable version found for formula ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for formula ${$}`),prefixFetched:($,M)=>W(`Formula ${$} installed at prefix: ${M}`),prefixFetchFailed:($)=>W(`Failed to fetch prefix for formula ${$}`),prefixFallback:($,M)=>W(`Using fallback prefix for formula ${$}: ${M}`)};var dX=yM.object({name:yM.string(),versions:yM.object({stable:yM.string(),head:yM.string().optional(),bottle:yM.boolean().optional()})});async function cY($,M,J,Q,Y,G,X){let Z=Y.getSubLogger({name:"installFromBrew"});if(Z.debug(u$.installing($),M.installParams),!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.formula||$,U=q.cask||!1,K=q.tap;return Q$("brew",$,Z,async()=>{let _=X??W$({logger:Z,skipCommandLog:!0});await pX(I,U,K,Q?.force,Z,G,_);let O=await fX(I,Z,G),B=e(M.binaries,`${O}/bin`),j,V=B[0];if(q.versionArgs&&q.versionRegex&&V)j=await A$({binaryPath:V,args:q.versionArgs,regex:q.versionRegex,shellExecutor:G});else j=await uX(I,Z,G);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:I,isCask:U,tap:K}}})}async function uX($,M,J){try{M.debug(u$.fetchingVersion($));let Y=(await J`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),G=JSON.parse(Y),X=yM.array(dX).parse(G);if(X.length>0&&X[0]?.versions.stable){let Z=X[0].versions.stable,q=j$(Z);return M.debug(u$.versionFetched($,q)),q}M.debug(u$.versionNotFound($));return}catch(Q){M.debug(u$.versionFetchFailed($),Q);return}}async function fX($,M,J){try{let Y=(await J`brew --prefix ${$}`.quiet()).stdout.toString().trim();return M.debug(u$.prefixFetched($,Y)),Y}catch(Q){M.debug(u$.prefixFetchFailed($),Q);let G=`${(await J`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return M.debug(u$.prefixFallback($,G)),G}}async function pX($,M,J,Q,Y,G,X){if(J){let q=Array.isArray(J)?J:[J];for(let I of q)Y.debug(u$.executingCommand(`brew tap ${I}`)),await G`brew tap ${I}`.quiet()}let Z=["install"];if(M)Z.push("--cask");if(Q)Z.push("--force");Z.push($),Y.info(u$.executingCommand(`brew ${Z.join(" ")}`)),await X`brew ${Z}`}import{z as YM}from"zod";var XJ=r.extend({formula:YM.string().optional(),cask:YM.boolean().optional(),tap:YM.union([YM.string(),YM.array(YM.string())]).optional(),versionArgs:YM.array(YM.string()).optional(),versionRegex:YM.string().optional()});import{z as cX}from"zod";var hY=t.extend({installationMethod:cX.literal("brew"),installParams:XJ});var hX="1.0.0";class NQ{shell;method="brew";displayName="Homebrew Installer";version=hX;paramsSchema=XJ;toolConfigSchema=hY;constructor($){this.shell=$}externallyManaged=!0;async install($,M,J,Q,Y){let G=await cY($,M,J,Q,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as mX}from"smol-toml";import{z as f$}from"zod";class Q0 extends Error{statusCode;cause;constructor($,M,J){super($);if(this.name="CargoClientError",this.statusCode=M,this.cause=J,Error.captureStackTrace)Error.captureStackTrace(this,Q0)}}var b$={constructor:{initialized:($,M)=>W(`Initializing ${$} with user agent: ${M}`)},request:{makingRequest:($,M)=>W(`Making ${$} request to ${M}`)},errors:{emptyResponse:($)=>W(`Empty response received from ${$}`),jsonParseError:($)=>W(`JSON parse error for ${$}`)},cratesIo:{querying:($)=>W(`Querying crates.io for crate ${$}`),notFound:($)=>W(`Crate not found: ${$}`),metadataError:($)=>W(`Error fetching crate metadata for ${$}`)},parsing:{parsingCrateMetadata:($)=>W(`Parsing Cargo.toml from ${$}`),cargoTomlParseError:($)=>W(`Error parsing Cargo.toml from ${$}`)}};var gX=f$.object({package:f$.object({name:f$.string(),version:f$.string(),edition:f$.string().optional(),description:f$.string().optional(),authors:f$.array(f$.string()).optional(),license:f$.string().optional(),repository:f$.string().optional(),homepage:f$.string().optional()})});class vQ{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=J,this.cratesIoCache=Q,this.githubRawCache=Y,this.cargoConfig=M.cargo,this.cratesIoCacheEnabled=this.cargoConfig.cratesIo.cache.enabled&&Boolean(this.cratesIoCache),this.cratesIoCacheTtl=this.cargoConfig.cratesIo.cache.ttl,this.githubRawCacheEnabled=this.cargoConfig.githubRaw.cache.enabled&&Boolean(this.githubRawCache),this.githubRawCacheTtl=this.cargoConfig.githubRaw.cache.ttl,this.logger.getSubLogger({name:"constructor"}).debug(b$.constructor.initialized("CargoClient",this.cargoConfig.userAgent))}async request($,M){this.logger.getSubLogger({name:"request"}).debug(b$.request.makingRequest("GET",$));let Q=this.buildRequestHeaders(),{useCache:Y,cacheKey:G,cacheTtl:X}=this.resolveCacheOptions($,M),Z=await this.tryReadCache(G,Y);if(Z)return Z;let q=await this.performDownload($,Q),I=this.parseJson(q,$);return await this.tryStoreCache(G,I,X,Y),I}resolveCacheOptions($,M){if(!M)return{useCache:!1,cacheTtl:0};let J=M.kind,Q=J==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,Y=J==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,G=Q?`cargo:${J}:${$}`:void 0;return{useCache:Q,cacheKey:G,cacheTtl:Y}}async tryReadCache($,M){let J=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!M||!$||!J)return null;try{let Q=await J.get($);if(Q)return Q}catch{}return null}async tryStoreCache($,M,J,Q){let Y=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!Q||!$||!Y)return;try{await Y.set($,M,J)}catch{}}parseJson($,M){let J=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw J.error(b$.errors.emptyResponse(M)),new U$(J,"Empty response received from API",M);try{return JSON.parse($.toString("utf-8"))}catch(Q){if(Q instanceof SyntaxError)throw J.error(b$.errors.jsonParseError(M),Q),new Q0(`Invalid JSON response from ${M}: ${Q.message}`,void 0,Q);throw Q}}async performDownload($,M){let J=this.logger.getSubLogger({name:"performDownload"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q)throw J.error(b$.errors.emptyResponse($)),new U$(J,"Empty response received from API",$);return Q}buildRequestHeaders(){return{Accept:"application/json","User-Agent":this.cargoConfig.userAgent}}async getCrateMetadata($){let M=this.logger.getSubLogger({name:"getCrateMetadata"});M.debug(b$.cratesIo.querying($));let J=`${this.cargoConfig.cratesIo.host}/api/v1/crates/${$}`;try{return await this.request(J,{kind:"cratesIo"})}catch(Q){if(Q instanceof S$)return M.error(b$.cratesIo.notFound($)),null;throw M.error(b$.cratesIo.metadataError($),Q),Q}}buildCargoTomlUrl($,M="main"){return`${this.cargoConfig.githubRaw.host}/${$}/${M}/Cargo.toml`}async getCargoTomlPackage($){let M=this.logger.getSubLogger({name:"getCargoTomlPackage"});M.debug(b$.parsing.parsingCrateMetadata($));let{useCache:J,cacheKey:Q}=this.resolveCacheOptions($,{kind:"githubRaw"});if(J){let Y=await this.tryReadCache(Q,J);if(Y)return Y}try{let Y=await this.downloader.download(M,$,{headers:this.buildRequestHeaders()});if(!Y||Y.length===0)return M.error(b$.errors.emptyResponse($)),null;let G=this.parseCargoToml(Y);return await this.tryStoreCache(Q,G,this.githubRawCacheTtl,J),G}catch(Y){if(Y instanceof Q0)throw Y;if(Y instanceof S$)return null;throw M.error(b$.parsing.cargoTomlParseError($),Y),Y}}parseCargoToml($){let M=this.logger.getSubLogger({name:"parseCargoToml"}),J=$.toString("utf-8"),Q=mX(J),Y=gX.safeParse(Q);if(!Y.success)throw M.zodErrors(Y.error),new Q0("Could not parse version from Cargo.toml [package] section",void 0);return Y.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import nX from"path";var H$={installing:($)=>W(`Installing from cargo: ${$}`),foundVersion:($,M)=>W(`Found crate ${$} version ${M}`),downloadingAsset:($,M)=>W(`Downloading asset ${$} from ${M}`),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),parsingMetadata:($)=>W(`Parsing crate metadata from: ${$}`),queryingCratesIo:($)=>W(`Querying crates.io API for crate: ${$}`),queryingGitHubReleases:($)=>W(`Querying GitHub releases for ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($,M)=>W(`Exception while resolving version for ${$}: ${String(M)}`),updateCheckFailed:($)=>W(`Failed to check update for cargo tool: ${$}`)};async function mY($,M,J,Q,Y,G,X,Z,q,I,U){let K=I.getSubLogger({name:"installFromCargo"});if(K.debug(H$.installing($)),!M.installParams)return{success:!1,error:"Install parameters not specified"};let H=M.installParams,_=H.crateName||$;return Q$("cargo",$,K,async()=>{let B=q$(Y,$),j=await aX(_,H,X,K);K.debug(H$.foundVersion(_,j.version));let V=await rX(_,j.version,H,J,U);K.debug(H$.downloadingAsset(`${_}-${j.version}`,V));let D=`${_}-${j.version}.tar.gz`,A=nX.join(J.stagingDir,D);await K$(K,V,A,D,G,Q);let T={...J,version:j.version},S=await iX(M,q,T,A,B,K);if(!S.success)return S;let w=await Z.extract(K,A,{targetDir:J.stagingDir});K.debug(H$.archiveExtracted(),w),await AM(Y,$,M,J,J.stagingDir,K);let u=await lX(M,q,T,w,B,K);if(!u.success)return u;if(await Y.exists(A))await Y.rm(A),K.debug(H$.cleaningArchive(A));let i=e(M.binaries,J.stagingDir),E={method:"cargo",crateName:_,binarySource:H.binarySource||"cargo-quickinstall",downloadUrl:V};return{success:!0,binaryPaths:i,version:j.version,originalTag:j.originalTag,metadata:E}})}async function iX($,M,J,Q,Y,G){let X=$.installParams?.hooks?.["after-download"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,downloadPath:Q},Y);for(let q of X){let I=await M.executeHook(G,"afterDownload",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function lX($,M,J,Q,Y,G){let X=$.installParams?.hooks?.["after-install"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,extractResult:Q},Y);for(let q of X){let I=await M.executeHook(G,"afterInstall",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function aX($,M,J,Q){let Y=M.versionSource||"cargo-toml";switch(Y){case"cargo-toml":{let G=M.cargoTomlUrl||J.buildCargoTomlUrl(M.githubRepo||`${$}-community/${$}`);Q.debug(H$.parsingMetadata(G));let X=await J.getCargoTomlPackage(G);if(!X)throw Error(`Failed to fetch or parse Cargo.toml from ${G}`);return{version:j$(X.version)}}case"crates-io":{Q.debug(H$.queryingCratesIo($));let G=await J.getLatestVersion($);if(!G)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(G)}}case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases version source");return sX(M.githubRepo,Q)}default:throw Error(`Unknown version source: ${Y}`)}}async function sX($,M){throw M.debug(H$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function rX($,M,J,Q,Y){let G=J.binarySource||"cargo-quickinstall",X=tX(Q.systemInfo.platform),Z=oX(Q.systemInfo.arch);switch(G){case"cargo-quickinstall":return`${Y}/cargo-bins/cargo-quickinstall/releases/download/${$}-${M}/${$}-${M}-${Z}-${X}.tar.gz`;case"github-releases":{if(!J.githubRepo)throw Error("githubRepo is required when using github-releases binary source");let I=(J.assetPattern||"{crateName}-{version}-{platform}-{arch}.tar.gz").replace("{crateName}",$).replace("{version}",M).replace("{platform}",X).replace("{arch}",Z);return`${Y}/${J.githubRepo}/releases/download/v${M}/${I}`}default:throw Error(`Unknown binary source: ${G}`)}}function tX($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function oX($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as Y0}from"zod";var ZJ=r.extend({crateName:Y0.string(),binarySource:Y0.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:Y0.string().optional(),assetPattern:Y0.string().optional(),versionSource:Y0.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:Y0.string().optional()});import{z as eX}from"zod";var gY=t.extend({installationMethod:eX.literal("cargo"),installParams:ZJ});var $8="1.0.0";class yQ{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=$8;paramsSchema=ZJ;toolConfigSchema=gY;constructor($,M,J,Q,Y,G){this.fs=$;this.downloader=M;this.cargoClient=J;this.archiveExtractor=Q;this.hookExecutor=Y;this.githubHost=G}async install($,M,J,Q,Y){let G=await mY($,M,J,Q,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,Y,this.githubHost);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}async resolveVersion($,M,J,Q){let Y=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.crateName;if(!X)return Y.debug(H$.versionResolutionFailed($,"Missing crateName in install params")),null;let Z=await this.cargoClient.getLatestVersion(X);if(!Z)return Y.debug(H$.versionResolutionFailed($,`Could not fetch version for crate: ${X}`)),null;let q=EM(Z);return Y.debug(H$.versionResolutionResolved($,q)),q}catch(G){return Y.debug(H$.versionResolutionException($,G)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams?.crateName;if(!G)return{success:!1,error:"Missing crateName in install params"};let X=await this.cargoClient.getLatestVersion(G);if(!X)return{success:!1,error:`Could not fetch latest version for crate: ${G}`};let Z=M.version||"latest";if(Z==="latest")return{success:!0,hasUpdate:!1,currentVersion:X,latestVersion:X};return{success:!0,hasUpdate:Z!==X,currentVersion:Z,latestVersion:X}}catch(Y){return Q.error(H$.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!1}}import WJ from"path";var GM={installing:($)=>W(`Installing from curl-script: toolName=${$}`),downloadingScript:($)=>W(`Downloading install script from: ${$}`),executingScript:($)=>W(`Executing install script using: ${$}`),movingBinary:($,M)=>W(`Moving binary from ${$} to ${M}`),binaryFoundInInstallDir:($)=>W(`Binary found in install directory: ${$}`),binaryNotFound:($,M)=>W(`Binary ${$} not found in search paths: ${M}`),detectedVersion:($)=>W(`Detected version: ${$}`),versionDetectionFailed:($)=>W(`Failed to detect version: ${$}`),noBinariesInstalled:($)=>W(`No binaries were installed. Expected at: ${$}`),scriptOutput:()=>W("Install script output:")};async function M8($,M,J,Q){let Y=YJ($.binaries);for(let G of Y){let X=WJ.join(M.stagingDir,G);if(await J.exists(X)){Q.debug(GM.binaryFoundInInstallDir(X));continue}let Z=["/usr/local/bin",WJ.join(M.systemInfo.homeDir,".local","bin"),"/usr/bin"],q=!1;for(let I of Z){let U=WJ.join(I,G);if(await J.exists(U)){Q.debug(GM.movingBinary(U,X)),await J.copyFile(U,X),await J.chmod(X,493),q=!0;break}}if(!q)Q.warn(GM.binaryNotFound(G,`${M.stagingDir}, ${Z.join(", ")}`))}}async function nY($,M,J,Q,Y,G,X,Z,q,I){let U=q$(Y,$),K=Z.getSubLogger({name:"installFromCurlScript"});if(K.debug(GM.installing($)),!M.installParams||!("url"in M.installParams)||!("shell"in M.installParams))return{success:!1,error:"URL or shell not specified in installParams"};let H=M.installParams,_=H.url,O=H.shell;return Q$("curl-script",$,K,async()=>{K.debug(GM.downloadingScript(_));let j=WJ.join(J.stagingDir,`${$}-install.sh`);await K$(K,_,j,`${$}-install.sh`,G,Q),await U.chmod(j,493);let V={...J,downloadPath:j},D=await w$(M,V,X,Y,K);if(!D.success)return D;K.debug(GM.executingScript(O));let A={projectConfig:J.projectConfig,scriptPath:j,stagingDir:J.stagingDir},T=H.args?await t$(A,H.args):[],S=H.env?await t$(A,H.env):{},w={...process.env,...S},u=I??W$({logger:K,skipCommandLog:!0}),i="";if(O==="bash"){let y=await u`bash ${j} ${T}`.env(w);i=[y.stdout,y.stderr].filter(Boolean).join(`
70
- `)}else{let y=await u`sh ${j} ${T}`.env(w);i=[y.stdout,y.stderr].filter(Boolean).join(`
71
- `)}await M8(M,J,Y,K);let E=e(M.binaries,J.stagingDir),g=[];for(let y of E)if(await Y.exists(y))g.push(y);if(g.length===0){let y=E.join(", ");if(K.error(GM.noBinariesInstalled(y)),i.trim()){K.error(GM.scriptOutput());for(let I$ of i.trim().split(`
72
- `))K.error(W(I$))}return{success:!1,error:`Installation script completed but no binaries were found at expected locations: ${y}`}}let $$,m=E[0];if(m)$$=await A$({shellExecutor:q,binaryPath:m,args:H.versionArgs,regex:H.versionRegex});return{success:!0,binaryPaths:E,metadata:{method:"curl-script",scriptUrl:_,shell:O},version:$$||(M.version!=="latest"?M.version:void 0)}})}import{z as PM}from"zod";var qJ=r.extend({url:PM.string().url(),shell:PM.enum(["bash","sh"]),args:PM.custom().optional(),env:PM.custom().optional(),versionArgs:PM.array(PM.string()).optional(),versionRegex:PM.string().optional()});import{z as IJ}from"zod";var iY=t.extend({installationMethod:IJ.literal("curl-script"),installParams:qJ,binaries:IJ.array(IJ.union([IJ.string().min(1),Z$])).min(1)});var J8="1.0.0";class PQ{fs;downloader;hookExecutor;shell;method="curl-script";displayName="Curl Script Installer";version=J8;paramsSchema=qJ;toolConfigSchema=iY;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,Y){let G=await nY($,M,J,Q,this.fs,this.downloader,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,metadata:G.metadata,version:G.version}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import Q8 from"path";var G0={installing:($)=>W(`Installing from curl-tar: toolName=${$}`),downloadingArchive:($)=>W(`Downloading archive from: ${$}`),downloadingTarball:($)=>W(`Downloading tarball from: ${$}`),extractingTarball:()=>W("Extracting tarball"),tarballExtracted:()=>W("Tarball extracted successfully"),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`)};async function lY($,M,J,Q,Y,G,X,Z,q,I){let U=q$(Y,$),K=q.getSubLogger({name:"installFromCurlTar"});K.debug(G0.installing($));let H,_;if(!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let O=M.installParams,B=O.url;return Q$("curl-tar",$,K,async()=>{K.debug(G0.downloadingTarball(B));let V=Q8.join(J.stagingDir,`${$}.tar.gz`);await K$(K,B,V,`${$}.tar.gz`,G,Q),H={...J,downloadPath:V};let D=await w$(M,H,Z,Y,K);if(!D.success)return{success:!1,error:D.error};K.debug(G0.extractingTarball());let A=await X.extract(K,V,{targetDir:J.stagingDir});K.debug(G0.tarballExtracted(),A),_={...H,extractDir:J.stagingDir,extractResult:A};let T=await $0(M,_,Z,Y,K);if(!T.success)return{success:!1,error:T.error};if(await AM(U,$,M,J,J.stagingDir,K),await U.exists(V))K.debug(G0.cleaningArchive(V)),await U.rm(V);let S=e(M.binaries,J.stagingDir),w,u=S[0];if(u)w=await A$({binaryPath:u,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});return{success:!0,binaryPaths:S,metadata:{method:"curl-tar",downloadUrl:B,tarballUrl:B},version:w||(M.version!=="latest"?M.version:void 0)}})}import{z as UJ}from"zod";var KJ=r.extend({url:UJ.string().url(),versionArgs:UJ.array(UJ.string()).optional(),versionRegex:UJ.string().optional()});import{z as HJ}from"zod";var aY=t.extend({installationMethod:HJ.literal("curl-tar"),installParams:KJ,binaries:HJ.array(HJ.union([HJ.string().min(1),Z$])).min(1)});var Y8="1.0.0";class CQ{fs;downloader;archiveExtractor;hookExecutor;shell;method="curl-tar";displayName="Curl Tar Installer";version=Y8;paramsSchema=KJ;toolConfigSchema=aY;constructor($,M,J,Q,Y){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=Y}async install($,M,J,Q,Y){let G=await lY($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function sY($){let M=/\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?/,J=$.match(M);if(!J||J.index===void 0)return"";return $.slice(0,J.index)}function rY($){let M=/(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)/,J=$.match(M);if(!J)return $;let Q=J[1];if(!Q)return $;return Q}function tY($,M){let J=sY($),Q=rY(M);return`${J}${Q}`}import G8 from"crypto";import dQ from"semver";class a extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GitHubApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,a.prototype)}}var z={constructor:{initialized:($,M)=>W(`GitHub API client initialized with base URL ${$} and User-Agent ${M}`),authTokenPresent:()=>W("GitHub token authentication enabled"),authTokenMissing:()=>W("No GitHub token provided; requests will be unauthenticated")},ghCli:{initialized:($)=>W(`GitHub CLI API client initialized for hostname ${$}`),executing:($)=>W(`Executing gh api request for ${$}`),cacheHit:($)=>W(`Cache hit for gh api ${$}`),cacheMiss:($)=>W(`Cache miss for gh api ${$}`),commandFailed:($)=>W(`gh cli command failed with exit code ${$}`),parseError:($)=>W(`Failed to parse gh api response for ${$}`),notAvailable:()=>W("gh cli is not available or not authenticated"),downloadingAsset:($,M,J)=>W(`Downloading ${$} from ${M}@${J} via gh release download`),downloadComplete:($)=>W(`Downloaded ${$} via gh cli`),downloadFailed:($,M)=>W(`gh release download failed for ${$} with exit code ${M}`)},cache:{enabled:($)=>W(`GitHub API cache enabled with TTL ${$} ms`),disabled:()=>W("GitHub API cache provided but disabled by configuration"),missing:()=>W("No GitHub API cache provided; responses will not be cached")},request:{performing:($,M)=>W(`GitHub API ${$} request to ${M}`),emptyResponse:($)=>W(`GitHub API returned an empty response buffer for ${$}`)},errors:{requestFailure:($)=>W(`GitHub API request failure for ${$}`),notFound:($)=>W(`GitHub resource not found for ${$}`),rateLimit:($,M)=>W(`GitHub API rate limit exceeded for ${$}, resets at ${M}`),forbidden:($)=>W(`GitHub API request forbidden for ${$}`),client:($,M)=>W(`GitHub API client error for ${$} with status ${M}`),server:($,M)=>W(`GitHub API server error for ${$} with status ${M}`),http:($,M)=>W(`GitHub API HTTP error for ${$} with status ${M}`),network:($)=>W(`GitHub API network error for ${$}`),unknown:($)=>W(`Unknown GitHub API error for ${$}`),constraintLatestError:()=>W("GitHub API latest constraint lookup failed"),constraintError:($,M,J)=>W(`GitHub API error while evaluating constraint ${$} for ${M}/${J}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest GitHub release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest GitHub release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest GitHub release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching GitHub release ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`GitHub release ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching GitHub release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all GitHub releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching GitHub releases page ${$} via ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} GitHub releases for ${M}/${J}`),filteredPrereleases:($)=>W(`Filtered prereleases leaving ${$} GitHub releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},constraints:{searching:($,M,J)=>W(`Searching for GitHub release matching constraint ${$} in ${M}/${J}`),pageFetch:($)=>W(`Iterating GitHub releases pages for constraint ${$}`),pageRequest:($,M,J)=>W(`Fetching GitHub releases page ${$} for ${M}/${J}`),bestCandidate:($,M)=>W(`Best GitHub release candidate so far ${$} (version ${M})`),resultFound:($,M)=>W(`Found GitHub release ${M} for constraint ${$}`),resultMissing:($)=>W(`No GitHub release found for constraint ${$}`)},rateLimit:{fetching:()=>W("Fetching GitHub API rate limit status")},tagPattern:{probing:($,M)=>W(`Probing release tag pattern for ${$}/${M}`),detected:($)=>W(`Detected latest release tag: ${$}`),noRedirect:($,M)=>W(`No redirect found for ${$}/${M} latest release`),probeFailed:($,M)=>W(`Failed to probe tag pattern for ${$}/${M}`)}};class _J{hostname;shell;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GhCliApiClient"}),this.hostname=this.extractHostname(M.github.host),this.shell=J,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let Y=this.logger.getSubLogger({name:"constructor"});if(Y.debug(z.ghCli.initialized(this.hostname)),this.cache&&this.cacheEnabled)Y.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)Y.debug(z.cache.disabled());else Y.debug(z.cache.missing())}extractHostname($){try{let M=new URL($);if(M.hostname==="api.github.com")return"github.com";return M.hostname.replace(/^api\./,"")}catch{return"github.com"}}generateCacheKey($,M){let J=`${M}:${$}`,Q=G8.createHash("sha256").update("gh-cli").digest("hex").substring(0,8);return J+=`:${Q}`,J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=this.generateCacheKey($,M),Y=await this.tryGetFromCache(Q,M,$);if(Y)return Y;J.debug(z.ghCli.executing($));let G=this.buildGhApiArgs($,M);try{let X=await this.executeGhCommand($,G);return await this.tryCacheResponse(Q,X,M),X}catch(X){return this.handleRequestError(X,$)}}buildGhApiArgs($,M){let J=["api"];if(this.hostname!=="github.com")J.push("--hostname",this.hostname);if(M!=="GET")J.push("--method",M);let Q=$.startsWith("/")?$.substring(1):$;return J.push(Q),J}async executeGhCommand($,M){let J=this.logger.getSubLogger({name:"executeGhCommand"}),Q=["gh",...M].join(" "),Y=await this.shell(Q).quiet().noThrow();if(Y.code!==0)throw J.debug(z.ghCli.commandFailed(Y.code)),this.parseGhError(Y.stderr,Y.code,$);try{return JSON.parse(Y.stdout)}catch{throw J.debug(z.ghCli.parseError($)),new a(`Failed to parse gh api response for ${$}`,void 0)}}parseGhError($,M,J){let Q=$.toLowerCase();if(Q.includes("not found")||Q.includes("404"))return new a(`GitHub resource not found: ${J}. Status: 404`,404);if(Q.includes("rate limit")||Q.includes("403"))return new a(`GitHub API rate limit exceeded for ${J}. Status: 403`,403);if(Q.includes("unauthorized")||Q.includes("401"))return new a(`GitHub API unauthorized for ${J}. Status: 401`,401);if(Q.includes("forbidden"))return new a(`GitHub API forbidden for ${J}. Status: 403`,403);return new a(`gh api command failed for ${J} with exit code ${M}: ${$}`,void 0)}async tryGetFromCache($,M,J){let Q=this.logger.getSubLogger({name:"tryGetFromCache"});if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let Y=await this.cache.get($);if(Y)return Q.debug(z.ghCli.cacheHit(J)),Y;Q.debug(z.ghCli.cacheMiss(J))}catch{}return null}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){if(this.logger.getSubLogger({name:"handleRequestError"}).debug(z.errors.requestFailure(M),$),$ instanceof a)throw $;if($ instanceof Error)throw new a(`Error during gh api request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during gh api request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof a&&Q.statusCode===404)return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(Y){if(Y instanceof a&&Y.statusCode===404)return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let Y=J?.perPage||30,G=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${Y}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let Y=null,G=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,Y,G);if(U.release)Y=U.release,G=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,Y),Y}async fetchReleasesPage($,M,J,Q,Y){let G=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(G)}catch(Z){return X.debug(z.errors.constraintError(Y,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let Y=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),G=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))G=Z,X=q,Y.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:G,version:X}}isVersionSatisfying($,M){return Boolean(dQ.valid($))&&dQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||dQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(z.releases.fetchTagsError($,M),Y),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));try{let Q=await this.getLatestRelease($,M);if(Q)return J.debug(z.tagPattern.detected(Q.tag_name)),Q.tag_name;return null}catch{return J.debug(z.tagPattern.probeFailed($,M)),null}}async downloadAsset($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"downloadAsset"});G.debug(z.ghCli.downloadingAsset(Q,`${$}/${M}`,J));let X=Y.substring(0,Y.lastIndexOf("/")),Z=["release","download",J];if(Z.push("--repo",`${$}/${M}`),Z.push("--pattern",Q),Z.push("--dir",X),Z.push("--clobber"),this.hostname!=="github.com");let q=["gh",...Z].join(" "),I=await this.shell(q).quiet().noThrow();if(I.code!==0)throw G.debug(z.ghCli.downloadFailed(Q,I.code)),new a(`gh release download failed for ${Q}: ${I.stderr.trim()||`exit code ${I.code}`}`,void 0);G.debug(z.ghCli.downloadComplete(Q))}}import X8 from"crypto";import uQ from"semver";class RJ{baseUrl;githubToken;downloader;userAgent;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GitHubApiClient"}),this.baseUrl=M.github.host,this.githubToken=M.github.token,this.downloader=J,this.userAgent=M.github.userAgent,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let Y=this.logger.getSubLogger({name:"constructor"});if(Y.debug(z.constructor.initialized(this.baseUrl,this.userAgent)),this.githubToken)Y.debug(z.constructor.authTokenPresent());else Y.debug(z.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)Y.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)Y.debug(z.cache.disabled());else Y.debug(z.cache.missing())}generateCacheKey($,M){let J=`${M}:${$}`;if(this.githubToken&&typeof this.githubToken==="string"&&this.githubToken.length>0){let Q=X8.createHash("sha256").update(this.githubToken).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,Y=this.generateCacheKey($,M),G=await this.tryGetFromCache(Y,M);if(G)return G;J.debug(z.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(Y,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/vnd.github.v3+json","User-Agent":this.userAgent};if(this.githubToken)$.Authorization=`token ${this.githubToken}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(z.request.emptyResponse($)),new U$(this.logger,"Empty response received from API",$);let Y=Q.toString("utf-8");return JSON.parse(Y)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(z.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(z.errors.notFound(M),$.responseBody),Error(`GitHub resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof BM)return this.handleRateLimitError($,M);if($ instanceof bM)return this.handleForbiddenError($,M);if($ instanceof NM)return this.handleClientError($,M);if($ instanceof vM)return this.handleServerError($,M);if($ instanceof F$)return this.handleHttpError($,M);if($ instanceof U$)return this.handleNetworkError($,M);return this.handleUnknownError($,M)}handleRateLimitError($,M){let J=this.logger.getSubLogger({name:"handleRateLimitError"}),Q=$.resetTimestamp?new Date($.resetTimestamp).toISOString():"N/A";throw J.debug(z.errors.rateLimit(M,Q),$.responseBody),new a(`GitHub API rate limit exceeded for ${M}. Status: ${$.statusCode}. Resets at ${Q}.`,$.statusCode,$)}handleForbiddenError($,M){throw this.logger.getSubLogger({name:"handleForbiddenError"}).debug(z.errors.forbidden(M),$.responseBody),new a(`GitHub API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$)}handleClientError($,M){throw this.logger.getSubLogger({name:"handleClientError"}).debug(z.errors.client(M,$.statusCode),$.responseBody),new a(`GitHub API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleServerError($,M){throw this.logger.getSubLogger({name:"handleServerError"}).debug(z.errors.server(M,$.statusCode),$.responseBody),new a(`GitHub API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleHttpError($,M){throw this.logger.getSubLogger({name:"handleHttpError"}).debug(z.errors.http(M,$.statusCode),$),new a(`GitHub API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleNetworkError($,M){throw this.logger.getSubLogger({name:"handleNetworkError"}).debug(z.errors.network(M),$),new a(`Network error while requesting ${M}: ${$.message}`,void 0,$)}handleUnknownError($,M){if(this.logger.getSubLogger({name:"handleUnknownError"}).debug(z.errors.unknown(M),$),$ instanceof Error)throw new a(`Unknown error during GitHub API request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during GitHub API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof Error&&Q.message.includes("GitHub resource not found"))return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(Y){if(Y instanceof Error&&Y.message.includes("GitHub resource not found"))return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let Y=J?.perPage||30,G=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${Y}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let Y=null,G=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,Y,G);if(U.release)Y=U.release,G=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,Y),Y}async fetchReleasesPage($,M,J,Q,Y){let G=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(G)}catch(Z){return X.debug(z.errors.constraintError(Y,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let Y=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),G=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))G=Z,X=q,Y.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:G,version:X}}isVersionSatisfying($,M){return Boolean(uQ.valid($))&&uQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||uQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(z.releases.fetchTagsError($,M),Y),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));let Q=`https://github.com/${$}/${M}/releases/latest`;try{let G=(await fetch(Q,{method:"HEAD",redirect:"manual"})).headers.get("location");if(!G)return J.debug(z.tagPattern.noRedirect($,M)),null;let Z=G.match(/\/releases\/tag\/(.+)$/)?.[1];if(!Z)return J.debug(z.tagPattern.noRedirect($,M)),null;let q=decodeURIComponent(Z);return J.debug(z.tagPattern.detected(q)),q}catch(Y){return J.debug(z.tagPattern.probeFailed($,M),Y),null}}}function fQ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oY($){let M=$.system.length>0?`(${$.system.map(fQ).join("|")})`:"",J=$.cpu.length>0?`(${$.cpu.map(fQ).join("|")})`:"",Q=$.variants.length>0?`(${$.variants.map(fQ).join("|")})`:"";return{systemPattern:M,cpuPattern:J,variantPattern:Q}}function OJ($){let M={system:[],cpu:[],variants:[]};switch($.platform){case 2:M.system=["apple","darwin","apple-darwin","dmg","mac","macos","mac-os","osx","os-x","os64x"],M.variants=["darwin"];break;case 1:M.system=["linux"],M.variants=["musl","gnu","unknown-linux"];break;case 4:M.system=["windows","win32","win64","pc-windows-gnu"],M.variants=["mingw","msys","cygwin","pc-windows"];break;default:M.system=[],M.variants=[];break}switch($.arch){case 2:M.cpu=["arm64","aarch64","aarch"];break;case 1:M.cpu=["amd64","x86_64","x64","x86-64"];break;default:M.cpu=[];break}return M}function eY($){let M=OJ($);return oY(M)}var Z8=[/\.sha\d+(sum)?$/i,/\.md5(sum)?$/i,/\.sum$/i,/^shasums/i,/\.sig$/i,/\.asc$/i,/\.pem$/i,/\.json$/i,/\.txt$/i,/\.sbom$/i,/\.deb$/i,/\.rpm$/i,/\.apk$/i,/\.pkg$/i,/buildable-artifact/i,/\.vsix$/i,/\.b3$/i,/\.zst$/i];function W8($){let M=$.filter((J)=>!Z8.some((Q)=>Q.test(J)));return M.length>0?M:$}function q8($,M){let J=new RegExp(M,"i"),Q=$.filter((Y)=>J.test(Y.toLowerCase()));return Q.length>0?Q:$}function jJ($,M){let J=eY(M),Q=OJ(M),Y=W8($),G;if(J.systemPattern){let Z=new RegExp(J.systemPattern,"i");G=Y.filter((q)=>Z.test(q.toLowerCase()))}else G=[...Y];if(G.length===0)return;let X=[];if(J.cpuPattern)X.push(J.cpuPattern);X.push(...Q.variants);for(let Z of X){if(G.length<=1)break;G=q8(G,Z)}return G[0]}import K8 from"path";var P={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),determiningDownloadUrl:($,M)=>W(`Determining download URL. rawBrowserDownloadUrl="${$}", hasCustomHost=${M}`),usingAbsoluteUrl:($)=>W(`Using absolute browser_download_url directly: "${$}"`),invalidRelativeUrl:($)=>W(`Invalid asset download URL format: ${$}`),resolvedRelativeUrl:($,M,J)=>W(`Resolved relative URL. Base: "${$}", Relative Path: "${M}", Result: "${J}"`),finalDownloadUrl:($,M,J)=>W(`Final download URL determined. Raw: "${$}", Result: "${M}", hasCustomHost=${J}`),downloadUrlError:($,M)=>W(`Download URL construction failed: Raw: "${$}", hasCustomHost=${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),downloadingViaGhCli:($)=>W(`Downloading ${$} via gh release download (authenticated)`),downloadingViaHttp:($)=>W(`Downloading ${$} via HTTP`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),invalidUrl:($)=>W(`Invalid URL: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),detectingTagPattern:()=>W("Detecting tag pattern from latest release"),tagPatternDetectionFailed:()=>W("Failed to detect tag pattern"),tryingCorrectedTag:($,M)=>W(`Trying corrected tag '${$}' (original: '${M}')`),usingCorrectedTag:($,M)=>W(`Found release with corrected tag '${$}' (you specified: '${M}')`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as I8}from"minimatch";function U8($){return/^[dgimsuvy]*$/.test($)}function $9($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function M9($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!U8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function J9($){if(!$9($))return!0;try{return M9($),!0}catch{return!1}}function Q9($){if(typeof $==="string")return $;return $.toString()}function Y9($,M){if(typeof M==="string"){if($9(M))return M9(M).test($);return I8($,M)}return M.test($)}async function X9($,M,J,Q,Y,G,X,Z,q,I,U){let K=U.getSubLogger({name:"installFromGitHubRelease"});if(K.debug(P.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"GitHub repository not specified in installParams"};let H=M.installParams,_=H.repo,O=H.version||"latest",[B,j]=_.split("/");if(!B||!j)return{success:!1,error:`Invalid GitHub repository format: ${_}. Expected format: owner/repo`};try{let V=await A0(_,O,H.prerelease??!1,X,K);if(!V.success)return V;let D=await pQ(V.data,H,J,K);if(!D.success)return D;let A=j8(D.data.browser_download_url,q,K);if(!A.success)return A;let T=K8.join(J.stagingDir,D.data.name),S=await D8(A.data,D.data,G,X,B,j,V.data.tag_name,T,Q,K);if(!S.success)return S;let w={...J,downloadPath:S.data.downloadPath},u=await A8(M,w,I,Y,K);if(!u.success)return u;let i=j$(V.data.tag_name),E=await E8(D.data,S.data.downloadPath,$,M,J,w,Y,Z,I,Y,K);if(!E.success)return E;let g=e(M.binaries,J.stagingDir),$$={method:"github-release",releaseUrl:V.data.html_url,publishedAt:V.data.published_at,releaseName:V.data.name,downloadUrl:A.data,assetName:D.data.name};return{success:!0,binaryPaths:g,version:i,originalTag:V.data.tag_name,metadata:$$}}catch(V){return{success:!1,error:V instanceof Error?V.message:String(V)}}}var H8=5;async function A0($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchGitHubRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid GitHub repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(G.debug(P.fetchLatest($)),J){let O=(await Q.getAllReleases(X,Z,{perPage:1,includePrerelease:!0,limit:1}))[0];if(!O)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:O}}let K=await Q.getLatestRelease(X,Z);if(!K)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:K}}G.debug(P.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};let I=await _8(X,Z,M,Q,G);if(I)return{success:!0,data:I};return await R8(X,Z,Q,G),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function _8($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchWithTagPatternDetection"});G.debug(P.detectingTagPattern());let X=await Q.probeLatestTag($,M);if(!X)return G.debug(P.tagPatternDetectionFailed()),null;let Z=tY(X,J);if(Z!==J){G.debug(P.tryingCorrectedTag(Z,J));let q=await Q.getReleaseByTag($,M,Z);if(q)return G.info(P.usingCorrectedTag(Z,J)),q}return null}async function R8($,M,J,Q){let Y=Q.getSubLogger({name:"showAvailableReleaseTags"}),G=await J.getLatestReleaseTags($,M,H8);if(G.length===0){Y.error(P.noReleaseTagsAvailable());return}Y.info(P.availableReleaseTags());for(let X of G)Y.info(P.releaseTagItem(X))}async function pQ($,M,J,Q){let Y;if(M.assetSelector){Q.debug(P.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};Y=M.assetSelector(X)}else if(M.assetPattern){Q.debug(P.assetPatternMatch(Q9(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>Y9(q.name,X));if(Y=G9(Z,J.systemInfo),!Y&&Z.length>0)Y=Z[0]}else Q.debug(P.assetPlatformMatch(o$(J.systemInfo.platform),e$(J.systemInfo.arch))),Y=G9($.assets,J.systemInfo);if(!Y)return{success:!1,error:O8($,M,J)};return{success:!0,data:Y}}function G9($,M){let J=$.map((Y)=>Y.name),Q=jJ(J,M);if(!Q)return;return $.find((Y)=>Y.name===Q)}function O8($,M,J){let Q=$.assets.map((q)=>q.name),Y=o$(J.systemInfo.platform),G=e$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${Y}/${G}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${Y}/${G}.`;else X=`for platform "${Y}" and architecture "${G}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
73
- `)}function j8($,M,J){let Q=M.github.host,Y=Boolean(Q);J.debug(P.determiningDownloadUrl($,Y));try{let X=V8($)?z8($,J):B8($,Q,J);if(!X.success)return X;return J.debug(P.finalDownloadUrl($,X.data,Y)),X}catch(G){return J.error(P.invalidUrl($)),J.debug(P.downloadUrlError($,Y),G),{success:!1,error:G instanceof Error?G.message:String(G)}}}function V8($){return URL.canParse($)}function z8($,M){return M.debug(P.usingAbsoluteUrl($)),{success:!0,data:$}}function B8($,M,J){if(!$.startsWith("/"))return J.debug(P.invalidRelativeUrl($)),{success:!1,error:`Invalid asset download URL format: ${$}`};let Q=M&&!M.includes("api.github.com")?M:"https://github.com";if(!/^https?:\/\//.test(Q))Q=`https:${Q.startsWith("//")?"":"//"}${Q}`;let G=new URL($,Q).toString();return J.debug(P.resolvedRelativeUrl(Q,$,G)),{success:!0,data:G}}async function D8($,M,J,Q,Y,G,X,Z,q,I){if(Q.downloadAsset){I.debug(P.downloadingViaGhCli(M.name));try{return await Q.downloadAsset(Y,G,X,M.name,Z),{success:!0,data:{downloadPath:Z}}}catch(U){I.debug(P.downloadingAsset($),U instanceof Error?U:Error(String(U)))}}I.debug(P.downloadingViaHttp(M.name));try{return await K$(I,$,Z,M.name,J,q),{success:!0,data:{downloadPath:Z}}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}async function A8($,M,J,Q,Y){let G=await w$($,M,J,Q,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}async function E8($,M,J,Q,Y,G,X,Z,q,I,U){if(CM($.name))return await F8($,M,J,Q,Y,G,X,Z,q,I,U);else return await M0(X,J,Q,Y,M,U),{success:!0,data:void 0}}async function F8($,M,J,Q,Y,G,X,Z,q,I,U){U.debug(P.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:Y.stagingDir});U.debug(P.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...G,extractDir:Y.stagingDir,extractResult:K},_=await L8(Q,H,I,q,U);if(!_.success)return _;if(await AM(X,J,Q,Y,Y.stagingDir,U),await X.exists(M))U.debug(P.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function L8($,M,J,Q,Y){let G=await $0($,M,Q,J,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}import{z as FM}from"zod";var X0=r.extend({repo:FM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:FM.union([FM.string().refine(J9,"assetPattern must be a valid glob or a regex string like /.../"),FM.instanceof(RegExp)]).optional(),version:FM.string().optional(),assetSelector:FM.custom(($)=>typeof $==="function","Must be a function").optional(),ghCli:FM.boolean().optional(),prerelease:FM.boolean().optional()});import{z as VJ}from"zod";var Z9=t.extend({installationMethod:VJ.literal("github-release"),installParams:X0,binaries:VJ.array(VJ.union([VJ.string().min(1),Z$])).min(1)});class cQ{fs;downloader;githubApiClient;ghCliApiClient;archiveExtractor;projectConfig;hookExecutor;method="github-release";displayName="GitHub Release";version="1.0.0";paramsSchema=X0;toolConfigSchema=Z9;constructor($,M,J,Q,Y,G,X){this.fs=$;this.downloader=M;this.githubApiClient=J;this.ghCliApiClient=Q;this.archiveExtractor=Y;this.projectConfig=G;this.hookExecutor=X}getApiClient($){if($.installParams.ghCli&&this.ghCliApiClient)return this.ghCliApiClient;return this.githubApiClient}async install($,M,J,Q,Y){let G=q$(this.fs,$);return await X9($,M,J,Q,G,this.downloader,this.getApiClient(M),this.archiveExtractor,this.projectConfig,this.hookExecutor,Y)}async resolveVersion($,M,J,Q){try{let Y=M.installParams,G=M.version||"latest",X=await A0(Y.repo,G,Y.prerelease??!1,this.getApiClient(M),Q);if(!X.success)return Q.debug(P.versionResolutionFailed($,X.error)),null;let Z=EM(X.data.tag_name);return Q.debug(P.versionResolutionResolved($,Z)),Z}catch(Y){return Q.debug(P.versionResolutionException($),Y),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams.repo,[X,Z]=G.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${G}. Expected owner/repo`};let q=await this.getApiClient(M).getLatestRelease(X,Z);if(!q||!q.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let I=M.version||"latest",U=q.tag_name.replace(/^v/,"");if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:U,latestVersion:U};return{success:!0,hasUpdate:I!==U,currentVersion:I,latestVersion:U}}catch(Y){return Q.error(P.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let Q=M.installParams.repo,[Y,G]=Q.split("/");if(!Y||!G)return null;let X=M.version||"main";return`https://raw.githubusercontent.com/${Y}/${G}/${X}/README.md`}}import dM from"path";var L$={installing:($)=>W(`Installing from dmg: toolName=${$}`),skippingNonMacOS:($)=>W(`Skipping DMG installation for ${$}: not running on macOS`),downloadingDmg:($)=>W(`Downloading DMG from: ${$}`),mountingDmg:($)=>W(`Mounting DMG: ${$}`),dmgMounted:($)=>W(`DMG mounted at: ${$}`),copyingApp:($)=>W(`Copying app bundle: ${$}`),symlinkingBinary:($,M)=>W(`Symlinking binary: ${$} -> ${M}`),unmountingDmg:($)=>W(`Unmounting DMG: ${$}`),appNotFound:($)=>W(`No .app bundle found in DMG at: ${$}`),extractingArchive:()=>W("Extracting archive to find DMG"),archiveExtracted:($)=>W(`Archive extracted: ${$} files`),dmgFoundInArchive:($)=>W(`Found DMG in archive: ${$}`),noDmgInArchive:()=>W("No .dmg file found in archive")};async function W9($,M,J,Q,Y,G,X,Z,q,I,U,K){let H=q$(Y,$),_=q.getSubLogger({name:"installFromDmg"});if(_.debug(L$.installing($)),J.systemInfo.platform!==2)return _.info(L$.skippingNonMacOS($)),{success:!0,binaryPaths:[],metadata:{method:"dmg",dmgUrl:x8(M.installParams.source)}};let O=M.installParams;return Q$("dmg",$,_,async()=>{await Y.ensureDir(J.stagingDir);let j=await k8(O.source,J,Q,G,U,K,_);if(!j.success)return{success:!1,error:j.error};let V={...J,downloadPath:j.data.downloadPath},D=await w$(M,V,Z,Y,_);if(!D.success)return{success:!1,error:D.error};let A=j.data.downloadPath;if(CM(j.data.downloadName)){_.debug(L$.extractingArchive());let o=await X.extract(_,j.data.downloadPath,{targetDir:J.stagingDir});_.debug(L$.archiveExtracted(o.extractedFiles.length));let y=o.extractedFiles.find((I$)=>I$.endsWith(".dmg"));if(!y)return _.error(L$.noDmgInArchive()),{success:!1,error:"No .dmg file found in extracted archive"};_.debug(L$.dmgFoundInArchive(y)),A=y}let T=W$({logger:_,skipCommandLog:!0}),S=dM.join(J.stagingDir,".dmg-mount");await Y.ensureDir(S),_.debug(L$.mountingDmg(A)),await T`hdiutil attach -nobrowse -noautoopen -mountpoint ${S} ${A}`,_.debug(L$.dmgMounted(S));let w,u;try{let o=await v8(O.appName,S,Y,_);if(!o)return{success:!1,error:"No .app bundle found in DMG"};w=o;let y=dM.join(S,w),I$="/Applications";await Y.ensureDir(I$);let r$=dM.join(I$,w);if(await Y.exists(r$))await Y.rm(r$,{recursive:!0,force:!0});_.debug(L$.copyingApp(w)),await I`cp -R ${y} ${r$}`.quiet(),u=r$}finally{_.debug(L$.unmountingDmg(S)),await I`hdiutil detach ${S}`.quiet().noThrow()}if(await H.exists(A))await H.rm(A);if(A!==j.data.downloadPath&&await H.exists(j.data.downloadPath))await H.rm(j.data.downloadPath);if(!u)return{success:!1,error:"App installation path was not resolved"};let E=l$(M.binaries).map((o)=>O.binaryPath?dM.join(u,O.binaryPath):dM.join(u,"Contents","MacOS",o.name)),g,$$=E[0];if($$)g=await A$({binaryPath:$$,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});let m={method:"dmg",downloadUrl:j.data.sourceUrl,dmgUrl:j.data.sourceUrl};return{success:!0,binaryPaths:E,metadata:m,version:g||(M.version!=="latest"?M.version:void 0)}})}function x8($){if($.type==="url")return $.url;return`github-release:${$.repo}`}function T8($,M,J){if($.ghCli&&J)return J;return M}async function k8($,M,J,Q,Y,G,X){if($.type==="url")return await S8($,M,J,Q,X);return await w8($,M,J,Q,Y,G,X)}async function S8($,M,J,Q,Y){Y.debug(L$.downloadingDmg($.url));let G=N8($.url,"download.dmg"),X=dM.join(M.stagingDir,G);try{return await K$(Y,$.url,X,G,Q,J),{success:!0,data:{downloadPath:X,downloadName:G,sourceUrl:$.url}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:String(Z)}}}async function w8($,M,J,Q,Y,G,X){if(!Y)return{success:!1,error:"GitHub API client is not configured for DMG github-release source"};let Z=T8($,Y,G),q=$.version||"latest",I=await A0($.repo,q,$.prerelease??!1,Z,X);if(!I.success)return I;let U=await pQ(I.data,$,M,X);if(!U.success)return U;let K=U.data.name.endsWith(".dmg"),H=CM(U.data.name);if(!K&&!H)return{success:!1,error:`Selected GitHub release asset must be a .dmg or supported archive: ${U.data.name}`};let[_,O]=$.repo.split("/");if(!_||!O)return{success:!1,error:`Invalid GitHub repository format: ${$.repo}. Expected format: owner/repo`};let B=dM.join(M.stagingDir,U.data.name),j=await b8($,U.data,_,O,I.data.tag_name,B,J,Q,Z,X);if(!j.success)return j;return{success:!0,data:{downloadPath:B,downloadName:U.data.name,sourceUrl:U.data.browser_download_url}}}async function b8($,M,J,Q,Y,G,X,Z,q,I){if($.ghCli&&q.downloadAsset)try{return await q.downloadAsset(J,Q,Y,M.name,G),{success:!0,data:void 0}}catch{}try{return await K$(I,M.browser_download_url,G,M.name,Z,X),{success:!0,data:void 0}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}function N8($,M){try{let Q=new URL($).pathname.split("/").pop();if(!Q)return M;return decodeURIComponent(Q)}catch{return M}}async function v8($,M,J,Q){if($)return $;let G=(await J.readdir(M)).find((X)=>X.endsWith(".app"));if(!G)return Q.error(L$.appNotFound(M)),null;return G}import{z as p$}from"zod";var y8=X0.pick({repo:!0,version:!0,assetPattern:!0,assetSelector:!0,ghCli:!0,prerelease:!0}),P8=p$.object({type:p$.literal("url"),url:p$.string().url()}),C8=p$.object({type:p$.literal("github-release")}).extend(y8.shape),d8=p$.discriminatedUnion("type",[P8,C8]),zJ=r.extend({source:d8,appName:p$.string().optional(),binaryPath:p$.string().optional(),versionArgs:p$.array(p$.string()).optional(),versionRegex:p$.string().optional()});import{z as u8}from"zod";var q9=t.extend({installationMethod:u8.literal("dmg"),installParams:zJ});var f8="1.0.0";class hQ{fs;downloader;archiveExtractor;hookExecutor;shell;githubApiClient;ghCliApiClient;method="dmg";displayName="DMG Installer";version=f8;paramsSchema=zJ;toolConfigSchema=q9;staticValidation=!0;externallyManaged=!0;missingBinaryMessage="Installation completed. This tool was installed as a macOS app bundle in /Applications. Launch it from Spotlight, Launchpad, or the Applications folder.";constructor($,M,J,Q,Y,G,X){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=Y;this.githubApiClient=G;this.ghCliApiClient=X}async validate($){if($.systemInfo.platform!==2)return{valid:!0,warnings:["DMG installer only works on macOS"]};try{return await this.shell`which hdiutil`.quiet(),{valid:!0}}catch{return{valid:!1,errors:["hdiutil not found \u2014 required for DMG installation"]}}}async install($,M,J,Q,Y){return W9($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,Y,this.shell,this.githubApiClient,this.ghCliApiClient)}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import p8 from"crypto";class c$ extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GiteaApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,c$.prototype)}}function I9($){return{name:$.name,browser_download_url:$.browser_download_url,size:$.size,content_type:"application/octet-stream",state:"uploaded",download_count:$.download_count,created_at:$.created_at,updated_at:$.created_at}}var d={constructor:{initialized:($)=>W(`Gitea API client initialized. baseUrl=${$}`),authTokenPresent:()=>W("API token is configured"),authTokenMissing:()=>W("No API token configured")},cache:{enabled:($)=>W(`Cache enabled. TTL=${$}ms`),disabled:()=>W("Cache is present but disabled"),missing:()=>W("No cache configured")},request:{performing:($,M)=>W(`Gitea API ${$} request to ${M}`),emptyResponse:($)=>W(`Empty response from ${$}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching release by tag ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`Release tag ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching page ${$}: ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} releases for ${M}/${J}`),filteredPrereleases:($)=>W(`After filtering prereleases: ${$} releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},errors:{requestFailure:($)=>W(`Request failure: ${$}`),notFound:($)=>W(`Resource not found: ${$}`),rateLimit:($)=>W(`Rate limit exceeded: ${$}`),forbidden:($)=>W(`Forbidden: ${$}`),client:($,M)=>W(`Client error ${M}: ${$}`),server:($,M)=>W(`Server error ${M}: ${$}`),http:($,M)=>W(`HTTP error ${M}: ${$}`),network:($)=>W(`Network error: ${$}`),unknown:($)=>W(`Unknown error: ${$}`)}};function mQ($){let M=$.assets.map(I9);return{id:$.id,tag_name:$.tag_name,name:$.name,draft:$.draft,prerelease:$.prerelease,created_at:$.created_at,published_at:$.published_at,assets:M,body:$.body,html_url:$.html_url}}class gQ{baseUrl;token;downloader;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"GiteaApiClient"});let G=M.replace(/\/+$/,"");this.baseUrl=`${G}/api/v1`,this.token=Y?.token,this.downloader=J,this.cache=Q,this.cacheEnabled=Y?.cacheEnabled??!0,this.cacheTtlMs=Y?.cacheTtlMs??300000;let X=this.logger.getSubLogger({name:"constructor"});if(X.debug(d.constructor.initialized(this.baseUrl)),this.token)X.debug(d.constructor.authTokenPresent());else X.debug(d.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)X.debug(d.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)X.debug(d.cache.disabled());else X.debug(d.cache.missing())}generateCacheKey($,M){let J=`gitea:${M}:${$}`;if(this.token&&typeof this.token==="string"&&this.token.length>0){let Q=p8.createHash("sha256").update(this.token).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,Y=this.generateCacheKey($,M),G=await this.tryGetFromCache(Y,M);if(G)return G;J.debug(d.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(Y,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/json"};if(this.token)$.Authorization=`token ${this.token}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(d.request.emptyResponse($)),new U$(this.logger,"Empty response received from API",$);let Y=Q.toString("utf-8");return JSON.parse(Y)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(d.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(d.errors.notFound(M)),Error(`Gitea resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof BM)throw J.debug(d.errors.rateLimit(M)),new c$(`Gitea API rate limit exceeded for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof bM)throw J.debug(d.errors.forbidden(M)),new c$(`Gitea API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof NM)throw J.debug(d.errors.client(M,$.statusCode)),new c$(`Gitea API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof vM)throw J.debug(d.errors.server(M,$.statusCode)),new c$(`Gitea API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof F$)throw J.debug(d.errors.http(M,$.statusCode)),new c$(`Gitea API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof U$)throw J.debug(d.errors.network(M)),new c$(`Network error while requesting ${M}: ${$.message}`,void 0,$);if(J.debug(d.errors.unknown(M),$),$ instanceof Error)throw new c$(`Unknown error during Gitea API request to ${M}: ${$.message}`,void 0,$);throw new c$(`Unknown error during Gitea API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(d.releases.fetchingLatest($,M));try{let Q=await this.request(`/repos/${$}/${M}/releases/latest`);return mQ(Q)}catch(Q){if(Q instanceof Error&&Q.message.includes("Gitea resource not found"))return J.debug(d.releases.latestNotFound($,M)),null;throw J.debug(d.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(d.releases.fetchingByTag(J,$,M));try{let Y=await this.request(`/repos/${$}/${M}/releases/tags/${J}`);return mQ(Y)}catch(Y){if(Y instanceof Error&&Y.message.includes("Gitea resource not found"))return Q.debug(d.releases.tagNotFound(J,$,M)),null;throw Q.debug(d.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(d.releases.fetchingAll($,M));let Y=J?.limit||30,G=J?.maxResults,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?limit=${Y}&page=${X}`;Q.debug(d.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{let K=U.map(mQ);if(Z=Z.concat(K),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(d.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(d.releases.filteredPrereleases(I.length)),I}return Z}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(d.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?limit=${J}`)).map((X)=>X.tag_name);return Q.debug(d.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(d.releases.fetchTagsError($,M),Y),[]}}}import m8 from"path";var J$={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as c8}from"minimatch";function h8($){return/^[dgimsuvy]*$/.test($)}function U9($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function K9($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!h8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function H9($){if(!U9($))return!0;try{return K9($),!0}catch{return!1}}function _9($){if(typeof $==="string")return $;return $.toString()}function R9($,M){if(typeof M==="string"){if(U9(M))return K9(M).test($);return c8($,M)}return M.test($)}var g8=5;async function j9($,M,J,Q,Y,G,X,Z,q,I){let U=I.getSubLogger({name:"installFromGiteaRelease"});if(U.debug(J$.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"Repository not specified in installParams"};let K=M.installParams,H=K.repo,_=K.version||"latest",[O,B]=H.split("/");if(!O||!B)return{success:!1,error:`Invalid repository format: ${H}. Expected format: owner/repo`};try{let j=await nQ(H,_,K.prerelease??!1,X,U);if(!j.success)return j;let V=i8(j.data,K,J,U);if(!V.success)return V;let D=V.data.browser_download_url,A=m8.join(J.stagingDir,V.data.name),T=await a8(D,V.data,G,A,Q,U);if(!T.success)return T;let S={...J,downloadPath:T.data.downloadPath},w=await s8(M,S,q,Y,U);if(!w.success)return w;let u=j$(j.data.tag_name),i=await r8(V.data,T.data.downloadPath,$,M,J,S,Y,Z,q,Y,U);if(!i.success)return i;let E=e(M.binaries,J.stagingDir),g={method:"gitea-release",releaseUrl:j.data.html_url,publishedAt:j.data.published_at,releaseName:j.data.name,instanceUrl:K.instanceUrl,downloadUrl:D,assetName:V.data.name};return{success:!0,binaryPaths:E,version:u,originalTag:j.data.tag_name,metadata:g}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}}async function nQ($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchGiteaRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(G.debug(J$.fetchLatest($)),J){let _=(await Q.getAllReleases(X,Z,{limit:1,includePrerelease:!0,maxResults:1}))[0];if(!_)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:_}}let U=await Q.getLatestRelease(X,Z);if(!U)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:U}}G.debug(J$.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};return await n8(X,Z,Q,G),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function n8($,M,J,Q){let Y=Q.getSubLogger({name:"showAvailableReleaseTags"}),G=await J.getLatestReleaseTags($,M,g8);if(G.length===0){Y.error(J$.noReleaseTagsAvailable());return}Y.info(J$.availableReleaseTags());for(let X of G)Y.info(J$.releaseTagItem(X))}function i8($,M,J,Q){let Y;if(M.assetSelector){Q.debug(J$.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};Y=M.assetSelector(X)}else if(M.assetPattern){Q.debug(J$.assetPatternMatch(_9(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>R9(q.name,X));if(Y=O9(Z,J.systemInfo),!Y&&Z.length>0)Y=Z[0]}else Q.debug(J$.assetPlatformMatch(o$(J.systemInfo.platform),e$(J.systemInfo.arch))),Y=O9($.assets,J.systemInfo);if(!Y)return{success:!1,error:l8($,M,J)};return{success:!0,data:Y}}function O9($,M){let J=$.map((Y)=>Y.name),Q=jJ(J,M);if(!Q)return;return $.find((Y)=>Y.name===Q)}function l8($,M,J){let Q=$.assets.map((q)=>q.name),Y=o$(J.systemInfo.platform),G=e$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${Y}/${G}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${Y}/${G}.`;else X=`for platform "${Y}" and architecture "${G}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
74
- `)}async function a8($,M,J,Q,Y,G){G.debug(J$.downloadingAsset($));try{return await K$(G,$,Q,M.name,J,Y),{success:!0,data:{downloadPath:Q}}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}async function s8($,M,J,Q,Y){let G=await w$($,M,J,Q,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}async function r8($,M,J,Q,Y,G,X,Z,q,I,U){if(CM($.name))return await t8($,M,J,Q,Y,G,X,Z,q,I,U);return await M0(X,J,Q,Y,M,U),{success:!0,data:void 0}}async function t8($,M,J,Q,Y,G,X,Z,q,I,U){U.debug(J$.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:Y.stagingDir});U.debug(J$.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...G,extractDir:Y.stagingDir,extractResult:K},_=await o8(Q,H,I,q,U);if(!_.success)return _;if(await AM(X,J,Q,Y,Y.stagingDir,U),await X.exists(M))U.debug(J$.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function o8($,M,J,Q,Y){let G=await $0($,M,Q,J,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}import{z as XM}from"zod";var BJ=r.extend({instanceUrl:XM.string().url("instanceUrl must be a valid URL"),repo:XM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:XM.union([XM.string().refine(H9,"assetPattern must be a valid glob or a regex string like /.../"),XM.instanceof(RegExp)]).optional(),version:XM.string().optional(),assetSelector:XM.custom(($)=>typeof $==="function","Must be a function").optional(),prerelease:XM.boolean().optional(),token:XM.string().optional()});import{z as DJ}from"zod";var V9=t.extend({installationMethod:DJ.literal("gitea-release"),installParams:BJ,binaries:DJ.array(DJ.union([DJ.string().min(1),Z$])).min(1)});class iQ{fs;downloader;archiveExtractor;hookExecutor;cache;method="gitea-release";displayName="Gitea Release";version="1.0.0";paramsSchema=BJ;toolConfigSchema=V9;constructor($,M,J,Q,Y){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.cache=Y}createApiClient($,M){let J=$.installParams;return new gQ(M,J.instanceUrl,this.downloader,this.cache,{token:J.token})}async install($,M,J,Q,Y){let G=q$(this.fs,$),X=this.createApiClient(M,Y);return await j9($,M,J,Q,G,this.downloader,X,this.archiveExtractor,this.hookExecutor,Y)}async resolveVersion($,M,J,Q){try{let Y=M.installParams,G=M.version||"latest",X=this.createApiClient(M,Q),Z=await nQ(Y.repo,G,Y.prerelease??!1,X,Q);if(!Z.success)return Q.debug(J$.versionResolutionFailed($,Z.error)),null;let q=EM(Z.data.tag_name);return Q.debug(J$.versionResolutionResolved($,q)),q}catch(Y){return Q.debug(J$.versionResolutionException($),Y),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams.repo,[X,Z]=G.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${G}. Expected owner/repo`};let I=await this.createApiClient(M,Q).getLatestRelease(X,Z);if(!I||!I.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let U=M.version||"latest",K=I.tag_name.replace(/^v/,"");if(U==="latest")return{success:!0,hasUpdate:!1,currentVersion:K,latestVersion:K};return{success:!0,hasUpdate:U!==K,currentVersion:U,latestVersion:K}}catch(Y){return Q.error(J$.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let J=M.installParams,Q=J.repo,[Y,G]=Q.split("/");if(!Y||!G)return null;let X=J.instanceUrl.replace(/\/+$/,""),Z=M.version||"main";return`${X}/${Y}/${G}/raw/branch/${Z}/README.md`}}import z9 from"path";var lQ={installing:($)=>W(`Manual installation: toolName=${$}`),manualInstructions:()=>W("Manual installation requires user action"),multipleBinariesNotSupported:()=>W("Manual installation does not support multiple binaries")};async function B9($,M,J,Q,Y,G){let X=q$(Y,$),Z=G.getSubLogger({name:"installManually"});Z.debug(lQ.installing($));let q=M.installParams;return Q$("manual",$,Z,async()=>{let U=[];if(q?.binaryPath){let H=RM(M.configFilePath,q.binaryPath,J.projectConfig,J.systemInfo);if(!await X.exists(H))return{success:!1,error:`Binary not found at ${H}`};await e8(M,$,J,X,H,Z),U=e(M.binaries,J.stagingDir)}return{success:!0,binaryPaths:U,metadata:{method:"manual",manualInstall:!0}}})}async function e8($,M,J,Q,Y,G){let X=G.getSubLogger({name:"installBinariesManually"}),Z=YJ($.binaries);for(let q of Z){let I=z9.join(J.stagingDir,q);if(q===M||Z.length===1)await Q.ensureDir(z9.dirname(I)),await Q.copyFile(Y,I),await Q.chmod(I,493);else X.debug(lQ.multipleBinariesNotSupported())}}import{z as $1}from"zod";var AJ=r.extend({binaryPath:$1.string().min(1).optional()});import{z as EJ}from"zod";var D9=t.extend({installationMethod:EJ.literal("manual"),installParams:AJ.optional(),binaries:EJ.array(EJ.union([EJ.string().min(1),Z$])).optional()});var M1="1.0.0";class aQ{fs;method="manual";displayName="Manual Installer";version=M1;paramsSchema=AJ;toolConfigSchema=D9;constructor($){this.fs=$}async install($,M,J,Q,Y){let G=await B9($,M,J,Q,this.fs,Y);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function J1($,M){if(M.platform===0)return!1;if(!rM($.platforms,M.platform))return!1;if($.architectures!==void 0){if(M.arch===0)return!1;if(!tM($.architectures,M.arch))return!1}return!0}function sQ($){return{...$,scripts:$.scripts?[...$.scripts]:void 0,functions:$.functions?{...$.functions}:void 0,paths:$.paths?[...$.paths]:void 0}}function Q1($){if(!$)return;return{zsh:$.zsh?sQ($.zsh):void 0,bash:$.bash?sQ($.bash):void 0,powershell:$.powershell?sQ($.powershell):void 0}}function Y1($){if(!$.shellConfigs)$.shellConfigs={zsh:void 0,bash:void 0,powershell:void 0}}function rQ($,M,J){if(!J)return;if(!$[M])$[M]={};let Q=$[M];if(J.scripts)Q.scripts=[...Q.scripts||[],...J.scripts];if(J.completions)Q.completions=J.completions;if(J.aliases)Q.aliases={...Q.aliases,...J.aliases};if(J.env)Q.env={...Q.env,...J.env};if(J.functions)Q.functions={...Q.functions,...J.functions};if(J.paths)Q.paths=[...Q.paths||[],...J.paths]}function G1($,M){if(!M)return;Y1($);let J=$.shellConfigs;rQ(J,"zsh",M.zsh),rQ(J,"bash",M.bash),rQ(J,"powershell",M.powershell)}function X1($,M){if(M.binaries!==void 0)$.binaries=M.binaries;if(M.dependencies!==void 0)$.dependencies=M.dependencies;if(M.version!==void 0)$.version=M.version;if(M.updateCheck!==void 0)$.updateCheck=M.updateCheck;if(M.installationMethod!==void 0)$.installationMethod=M.installationMethod;if(M.installParams!==void 0)$.installParams=M.installParams}function Z1($){let M={...$,shellConfigs:Q1($.shellConfigs),dependencies:$.dependencies?[...$.dependencies]:void 0},{platformConfigs:J,...Q}=M;return Q}function Y$($,M){if(!$.platformConfigs||$.platformConfigs.length===0)return $;let J=$.platformConfigs.filter((Y)=>J1(Y,M));if(J.length===0){let{platformConfigs:Y,...G}=$;return G}let Q=Z1($);for(let Y of J){let G=Y.config;if(G1(Q,G.shellConfigs),G.symlinks)Q.symlinks=[...Q.symlinks||[],...G.symlinks];if(G.copies)Q.copies=[...Q.copies||[],...G.copies];X1(Q,G)}return Q}import A9 from"path";function FJ($,M){let J=M.trim();if(A9.isAbsolute(J))return J;return A9.resolve($,J)}function EM($){if(!$)return $;if($.startsWith("v")||$.startsWith("V"))return $.slice(1);return $}import{randomUUID as W1}from"crypto";import{basename as E9,extname as q1,join as E0}from"path";var ZM={shellCommandStarted:($)=>W(`Executing shell command: ${$}`),shellCommandFailed:($,M)=>W(`Shell command failed (exit ${M??"unknown"}): ${$}`),fileCommandFallbackFailed:($)=>W(`Failed to detect archive format using file command: ${$}`),extractionRequested:($)=>W(`Extracting archive ${$}`),executableFlagApplied:($)=>W(`Marked file as executable: ${$}`),executableCheckFailed:($)=>W(`Failed to inspect file for executable permissions: ${$}`)};class tQ{fs;logger;shell;constructor($,M,J){this.fs=M,this.logger=$.getSubLogger({name:"ArchiveExtractor"}),this.shell=J}detectFormatByExtension($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}detectFormatByMimeType($){if($.includes("gzip"))return"tar.gz";if($.includes("zip"))return"zip";if($.includes("x-bzip2"))return"tar.bz2";if($.includes("x-xz"))return"tar.xz";if($.includes("x-tar"))return"tar";if($.includes("x-7z-compressed"))return"7z";if($.includes("x-rar-compressed"))return"rar";if($.includes("x-debian-package"))return"deb";if($.includes("x-rpm"))return"rpm";if($.includes("x-apple-diskimage"))return"dmg";return null}async detectFormatUsingFileCommand($,M){try{M.debug(ZM.shellCommandStarted("file"));let Y=(await this.shell`file -b --mime-type ${$}`.quiet()).stdout.trim();return this.detectFormatByMimeType(Y)}catch(J){return M.debug(ZM.fileCommandFallbackFailed($),J),null}}async detectFormat($){let M=this.logger.getSubLogger({name:"detectFormat"}),J=E9($),Q=this.detectFormatByExtension(J);if(Q)return Q;let Y=await this.detectFormatUsingFileCommand($,M);if(Y)return Y;throw Error(`Unsupported or undetectable archive format for: ${$}`)}isSupported($){return["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"].includes($)}getTarFlagForFormat($){switch($){case"tar.gz":return"-xzf";case"tar.bz2":return"-xjf";case"tar.xz":return"-xJf";case"tar":return"-xf";default:throw Error(`Unsupported tar format: ${$}`)}}async extractArchiveByFormat($,M,J){switch($){case"tar.gz":case"tar.bz2":case"tar.xz":case"tar":{let Q=this.getTarFlagForFormat($),Y="tar";this.logger.debug(ZM.shellCommandStarted("tar")),await this.shell`tar ${Q} ${M} -C ${J}`.quiet();break}case"zip":{this.logger.debug(ZM.shellCommandStarted("unzip")),await this.shell`unzip -qo ${M} -d ${J}`.quiet();break}case"gzip":{this.logger.debug(ZM.shellCommandStarted("gunzip"));let Y=E9(M),G=Y.endsWith(".gz")?Y.slice(0,-3):Y,X=E0(J,G);await this.shell`gunzip -c ${M} > ${X}`.quiet();break}default:throw Error(`Extraction for format ${$} not implemented.`)}}async extract($,M,J={}){let Q=$.getSubLogger({name:"extract"}),{format:Y,targetDir:G=".",detectExecutables:X=!0}=J;Q.debug(ZM.extractionRequested(M),J);let Z=Y||await this.detectFormat(M);if(!this.isSupported(Z))throw Error(`Unsupported archive format: ${Z}`);await this.fs.ensureDir(G);let q=W1(),I=E0(G,`.extract-temp-${q}`);await this.fs.ensureDir(I);try{await this.extractArchiveByFormat(Z,M,I);let U=await wM(this.fs,I);for(let _ of U){let O=_.substring(I.length+1),B=E0(G,O),j=E0(B,"..");await this.fs.ensureDir(j),await this.fs.rename(_,B)}await this.fs.rm(I,{recursive:!0,force:!0});let K=U.map((_)=>{let O=_.substring(I.length+1);return E0(G,O)}),H={extractedFiles:K,executables:[]};if(X)H.executables=await this.detectAndSetExecutables(K);return H}catch(U){try{await this.fs.rm(I,{recursive:!0,force:!0})}catch{}throw U}}async detectAndSetExecutables($){let M=this.logger.getSubLogger({name:"detectAndSetExecutables"}),J=[];for(let Q of $)try{let Y=await this.fs.stat(Q);if(Y.isFile()){let G=q1(Q);if(G===""||[".sh",".py",".pl",".rb"].includes(G)){if(!(Y.mode&64))M.debug(ZM.executableFlagApplied(Q)),await this.fs.chmod(Q,Y.mode|64);J.push(Q)}}}catch(Y){M.debug(ZM.executableCheckFailed(Q),Y)}return J}}var I1=["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"];function U1($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}function CM($){let M=U1($);if(!M)return!1;return I1.includes(M)}var WM={configurationFieldIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configurationFieldRequired:($,M)=>W(`Required configuration missing: ${$}${M?`. Example: ${M}`:""}`),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),invalidFunctionName:($)=>W(`Invalid function name: "${$}"`)};import oQ from"path";var D$={generationStarted:($,M)=>W(`Starting completion generation for "${$}" (shell: ${M})`),generationComplete:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),commandExecutionStarted:($,M,J)=>W(`Executing completion command for "${$}" (shell: ${J}): ${M}`),commandExecutionFailed:($,M,J,Q)=>W(`Completion command failed for "${$}" [${M}] exit ${J}: ${Q}`),commandExecutionCompleted:($,M)=>W(`Completion command succeeded for "${$}" (shell: ${M})`),symlinkCreated:($,M)=>W(`Symlinked completion: ${$} -> ${M}`),sourceNotFound:($)=>W(`Completion source file not found: ${$}`),downloadingCompletion:($)=>W(`Downloading completion from: ${$}`),completionDownloaded:($)=>W(`Completion downloaded to: ${$}`),completionAlreadyDownloaded:($)=>W(`Completion already downloaded: ${$}`),extractingCompletionArchive:($)=>W(`Extracting completion archive: ${$}`),completionArchiveExtracted:($)=>W(`Completion archive extracted to: ${$}`)};class F0{logger;shell;constructor($,M){this.logger=$.getSubLogger({name:"CompletionCommandExecutor"}),this.shell=M}async executeCompletionCommand($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"executeCompletionCommand"}).setPrefix(M);G.debug(D$.commandExecutionStarted(M,$,J));let X=Y?.map((I)=>oQ.dirname(I))??[],Z=[...new Set([...X,Q])],q=Z.join(oQ.delimiter);if(Y&&Y.length>0){let I=[...new Set(Y.map((K)=>oQ.basename(K)))];if(!await this.checkAnyBinaryExistsInPath(I,q)){let K=Z.join(", ");throw Error(`None of the expected binaries (${I.join(", ")}) found in: ${K}. Skipping completion generation to prevent infinite loop.`)}}try{let I=`cd ${Q} && PATH=${q}:$PATH ${$}`,U=await this.shell`sh -c ${I}`.quiet();return G.debug(D$.commandExecutionCompleted(M,J)),U.stdout}catch(I){let U=I&&typeof I==="object"&&"exitCode"in I?I.exitCode:-1,K=I&&typeof I==="object"&&"stderr"in I?I.stderr.toString():"Unknown error",H=`Completion command failed for ${M}: ${$}`;throw G.error(D$.commandExecutionFailed(M,$,U,K)),Error(`${H}
75
- Exit code: ${U}
76
- Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)try{let Q=`PATH=${M} command -v ${J}`;return await this.shell`sh -c ${Q}`.quiet(),!0}catch{}return!1}}import{minimatch as K1}from"minimatch";import N$ from"path";var H1=["tar.gz","tar.xz","tar.bz2","zip","tar","tar.lzma","7z"];class eQ{logger;commandExecutor;fs;downloader;archiveExtractor;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"CompletionGenerator"}),this.fs=M,this.commandExecutor=Q||new F0(this.logger,J),this.downloader=Y?.downloader,this.archiveExtractor=Y?.archiveExtractor}async prepareUrlCompletionSource($,M,J){if(!$.url)throw Error(`URL not provided for ${M}`);await this.downloadCompletionFromUrl($.url,J.toolInstallDir,M);let Q=$.source||this.getFilenameFromUrl($.url),Y=N$.isAbsolute(Q)?Q:N$.join(J.toolInstallDir,Q);if(!await this.fs.exists(Y))throw this.logger.warn(D$.sourceNotFound(Y)),Error(`Completion source file not found: ${Y}`);return Y}async generateCompletionFile($,M,J,Q){this.logger.getSubLogger({name:"generateCompletionFile"}).setPrefix(M).debug(D$.generationStarted(M,J));let G=$.url?await this.prepareUrlCompletionSource($,M,Q):$.source;if($.cmd)return this.generateFromCommand($,M,J,Q);if(G){let X={...$,source:G};return this.generateFromSource(X,M,J,Q)}throw Error(`Invalid completion config for ${M}: either 'cmd', 'source', or 'url' must be provided`)}async downloadCompletionFromUrl($,M,J){let Q=this.logger.getSubLogger({name:"downloadCompletionFromUrl"}).setPrefix(J);if(!this.downloader)throw Error("Downloader not provided - cannot download completion from URL");Q.info(D$.downloadingCompletion($)),await this.fs.ensureDir(M);let Y=this.getFilenameFromUrl($),G=N$.join(M,Y);if(await this.fs.exists(G)){Q.debug(D$.completionAlreadyDownloaded(G));return}if(await this.downloader.downloadToFile(Q,$,G),Q.debug(D$.completionDownloaded(G)),this.detectArchiveFormat(Y))await this.extractCompletionArchive(G,M,J)}async extractCompletionArchive($,M,J){let Q=this.logger.getSubLogger({name:"extractCompletionArchive"}).setPrefix(J);if(!this.archiveExtractor)throw Error("Archive extractor not provided - cannot extract completion archive");Q.debug(D$.extractingCompletionArchive($)),await this.archiveExtractor.extract(Q,$,{targetDir:M}),Q.debug(D$.completionArchiveExtracted(M))}getFilenameFromUrl($){let J=new URL($).pathname;return N$.basename(J)||"completion-download"}detectArchiveFormat($){let M=$.toLowerCase();for(let J of H1)if(M.endsWith(`.${J}`))return J;return null}async generateAndWriteCompletionFile($){let{config:M,toolName:J,shellType:Q,context:Y,fs:G}=$,X=await this.generateCompletionFile(M,J,Q,Y);if(await G.ensureDir(N$.dirname(X.targetPath)),X.generatedBy==="source"&&X.sourcePath){if(await G.exists(X.targetPath))await G.rm(X.targetPath);await G.symlink(X.sourcePath,X.targetPath),this.logger.debug(D$.symlinkCreated(X.sourcePath,X.targetPath))}else await G.writeFile(X.targetPath,X.content);return X}async generateFromCommand($,M,J,Q){if(!$.cmd)throw Error(`Command not provided for ${M}`);let Y=await this.commandExecutor.executeCompletionCommand($.cmd,M,J,Q.toolInstallDir,Q.binaryPaths),G=this.generateCompletionFilename($,M,J),X=this.resolveTargetPath(J,Q);return{content:Y,filename:G,targetPath:N$.join(X,G),generatedBy:"command"}}async generateFromSource($,M,J,Q){if(!$.source)throw Error(`Source not provided for ${M}`);let Y=await this.resolveSourcePath($.source,Q.configFilePath);if(!await this.fs.exists(Y))throw this.logger.warn(D$.sourceNotFound(Y)),Error(`Completion source file not found: ${Y}`);let G=this.generateCompletionFilename($,M,J),X=this.resolveTargetPath(J,Q);return{content:"",filename:G,targetPath:N$.join(X,G),generatedBy:"source",sourcePath:Y}}async resolveSourcePath($,M){if(N$.isAbsolute($))return $;let J=M?N$.dirname(M):void 0;if(!J)throw Error(`Cannot resolve relative path '${$}' without configFilePath`);if($.includes("*")||$.includes("?")||$.includes("[")){let Y=(await wM(this.fs,J,J)).find((G)=>K1(G,$));if(Y)return N$.join(J,Y);throw Error(`No files matching pattern '${$}' found in toolDir: ${J}`)}return FJ(J,$)}generateCompletionFilename($,M,J){let Q=$.bin??M;switch(J){case"zsh":return`_${Q}`;case"bash":return`${Q}.bash`;case"powershell":return`${Q}.ps1`;default:return`${Q}.${J}`}}resolveTargetPath($,M){return N$.join(M.shellScriptsDir,$,"completions")}}var F9=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;class Z0{headerWidth;indentSize;onceScriptDir;constructor($){this.headerWidth=$.headerWidth??80,this.indentSize=$.indentSize??2,this.onceScriptDir=$.onceScriptDir}comment($){return`# ${$}`}commentBlock($){return $.map((M)=>this.comment(M)).join(`
77
- `)}formatFileHeader($){let M=[this.headerLine("="),this.comment("THIS FILE IS AUTOMATICALLY GENERATED BY THE DOTFILES MANAGEMENT TOOL"),this.comment("DO NOT EDIT THIS FILE DIRECTLY - YOUR CHANGES WILL BE OVERWRITTEN"),this.headerLine("="),""];if($?.sourceFile)M.push(this.comment(`Dotfiles directory: ${$.sourceFile}`)),M.push("");return M.join(`
78
- `)}formatSectionHeader($){return this.headerLine("=",$)}formatChildBlockHeader($){return this.headerLine("=")}formatFileFooter(){return this.headerLine("=","End of Generated File")}headerLine($,M){let J=this.headerWidth;if(!M)return this.comment($.repeat(J-2));let Q=` ${M} `,Y=Math.max(0,J-1-Q.length),G=$.repeat(Math.floor(Y/2)),X=$.repeat(Math.ceil(Y/2));return this.comment(`${G}${Q}${X}`)}generateSourceFunctionName($){return`__source_${$.replace(/[^a-zA-Z0-9]/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}`}}class W0 extends Z0{generateOnceScriptContent($,M){let J=["# Generated once script - will self-delete after execution"];return J.push($),J.push(`rm "${M}"`),J.join(`
79
- `)}}class LM extends Error{blockId;constructor($,M){super(`Block "${$}": ${M}`);this.blockId=$;this.name="BlockValidationError"}}class qM extends Error{emissionKind;field;constructor($,M,J){super(`${$}.${M}: ${J}`);this.emissionKind=$;this.field=M;this.name="EmissionValidationError"}}var L9=/^[a-zA-Z_][a-zA-Z0-9_]*$/,x9=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;function _1($,M,J){if(!L9.test(J))throw new qM($,M,`"${J}" is not a valid identifier (must match ${L9.source})`)}function $6($,M,J){if(!x9.test(J))throw new qM($,M,`"${J}" is not a valid name (must match ${x9.source})`)}function LJ($,M,J){if(J.trim().length===0)throw new qM($,M,"cannot be empty")}function T9($,M,J){if(Object.keys(J).length===0)throw new qM($,M,"must have at least one entry")}function k9($){T9("environment","variables",$);for(let M of Object.keys($))_1("environment",`variables.${M}`,M)}function S9($){T9("alias","aliases",$);for(let M of Object.keys($))$6("alias",`aliases.${M}`,M)}function L0($){return k9($),{kind:"environment",variables:$}}function x0($){return S9($),{kind:"alias",aliases:$}}function q0($,M){return $6("function","name",$),LJ("function","body",M),{kind:"function",name:$,body:M}}function IM($,M){return LJ("script","content",$),{kind:"script",content:$,timing:M}}function T0($){let M=$.directories&&$.directories.length>0,J=$.files&&$.files.length>0,Q=$.commands&&$.commands.length>0;if(!M&&!J&&!Q)throw new qM("completion","config","at least one of directories, files, or commands must be provided");return{kind:"completion",directories:$.directories,files:$.files,commands:$.commands}}function xJ($,M){return LJ("path","directory",$),{kind:"path",directory:$,position:M?.position??"prepend",deduplicate:M?.deduplicate??!0}}function x$($,M){return{...$,source:M}}function M6($,M){return{...$,priority:M}}function uM($){return $.kind==="environment"}function fM($){return $.kind==="alias"}function pM($){return $.kind==="function"}function h$($){return $.kind==="script"}function cM($){return $.kind==="sourceFile"}function hM($){return $.kind==="source"}function mM($){return $.kind==="sourceFunction"}function UM($){return $.kind==="completion"}function gM($){return $.kind==="path"}var R1=new Set(["environment","path","completion"]);function J6($){return R1.has($.kind)}class TJ{sections=new Map;sectionOrder=[];addSection($,M){if(this.sections.has($))throw new LM($,"section already exists");if(M.priority<0)throw new LM($,"priority must be non-negative");return this.sections.set($,{id:$,options:M,emissions:[],children:new Map,childInsertionOrder:[]}),this.sectionOrder.push($),this}addEmission($,M){if(J6($))this.addHoistedEmission($);else this.addNonHoistedEmission($,M);return this}addEmissionToSection($,M){let J=this.sections.get(M);if(!J)throw new LM(M,"section does not exist");return J.emissions.push($),this}build(){let $=[];for(let M of this.sectionOrder){let J=this.sections.get(M);if(!J)continue;let Q=this.buildBlock(J);$.push(Q)}return $.toSorted((M,J)=>M.priority-J.priority)}addHoistedEmission($){let M=this.findHoistTarget($.kind);if(!M)throw new LM("unknown",`no section accepts hoisted emission kind "${$.kind}"`);M.emissions.push($)}addNonHoistedEmission($,M){let J=this.findChildrenSection();if(!J)throw new LM("unknown","no section allows children for non-hoisted emissions");if(M){let Q=J.children.get(M);if(!Q)Q={id:M,emissions:[],sourceFile:$.source},J.children.set(M,Q),J.childInsertionOrder.push(M);Q.emissions.push($)}else J.emissions.push($)}findHoistTarget($){for(let M of this.sections.values())if(M.options.hoistKinds?.includes($))return M;return}findChildrenSection(){for(let $ of this.sections.values())if($.options.allowChildren)return $;return}buildBlock($){let J=this.deduplicateCompletions($.emissions).toSorted((Y,G)=>(Y.priority??0)-(G.priority??0)),Q=[];for(let Y of $.childInsertionOrder){let G=$.children.get(Y);if(!G)continue;let X=G.emissions.toSorted((Z,q)=>(Z.priority??0)-(q.priority??0));Q.push({id:G.id,title:G.id,priority:Q.length,emissions:X,metadata:G.sourceFile?{sourceFile:G.sourceFile}:void 0})}return{id:$.id,title:$.options.title,priority:$.options.priority,emissions:J,children:Q.length>0?Q:void 0,metadata:$.options.metadata,isFileHeader:$.options.isFileHeader,isFileFooter:$.options.isFileFooter}}deduplicateCompletions($){let M=[],J=[];for(let q of $)if(UM(q))M.push(q);else J.push(q);if(M.length<=1)return $;let Q=new Set,Y=new Set,G=new Set,X;for(let q of M){if(q.directories)for(let I of q.directories)Q.add(I);if(q.files)for(let I of q.files)Y.add(I);if(q.commands)for(let I of q.commands)G.add(I);if(q.priority!==void 0)X=X===void 0?q.priority:Math.min(X,q.priority)}let Z={kind:"completion",directories:Q.size>0?[...Q]:void 0,files:Y.size>0?[...Y]:void 0,commands:G.size>0?[...G]:void 0,priority:X};return[...J,Z]}}var w9=1,nM=3;class kJ{render($,M){let J=$.toSorted((q,I)=>q.priority-I.priority),Q=[],Y=[],G=w9,X=[];for(let q of J)this.collectOnceScripts(q,X);let Z=-1;if(X.length>0)for(let q=J.length-1;q>=0;q--){let I=J[q];if(I&&I.priority<400){Z=q;break}}for(let[q,I]of J.entries()){let U=this.renderBlock(I,M,Y,G);if(U.length>0){if(Q.length>0)Q.push("");Q.push(...U)}if(G=Y.length+1,q===Z&&X.length>0)Q.push(""),Q.push(M.formatOnceScriptInitializer())}return{content:Q.join(`
80
- `),fileExtension:M.fileExtension,onceScripts:Y}}collectOnceScripts($,M){for(let J of $.emissions)if(h$(J)&&J.timing==="once")M.push({emission:J,blockPriority:$.priority});for(let J of $.children??[])this.collectOnceScripts(J,M)}renderBlock($,M,J,Q){let Y=[],G=Q;if($.isFileHeader)return Y.push(M.formatFileHeader($.metadata)),Y;if($.isFileFooter)return Y.push(M.formatFileFooter()),Y;let X=$.emissions.length>0,Z=($.children?.length??0)>0;if(!X&&!Z)return Y;if($.title)Y.push(M.formatSectionHeader($.title));let q;for(let I of $.emissions){if(I.source&&I.source!==q)Y.push(M.comment(I.source)),q=I.source;if(h$(I)&&I.timing==="once"){let U=M.formatOnceScript(I,G);J.push({filename:U.filename,content:U.content,executable:!0}),G++}else Y.push(M.formatEmission(I))}for(let I of $.children??[]){if(I.emissions.length===0)continue;Y.push(""),Y.push(M.formatChildBlockHeader(I));let U;for(let K of I.emissions){if(K.source&&K.source!==U)Y.push(M.comment(K.source)),U=K.source;if(h$(K)&&K.timing==="once"){let H=M.formatOnceScript(K,G);J.push({filename:H.filename,content:H.content,executable:!0}),G++}else Y.push(M.formatEmission(K))}}return Y}}class SJ extends W0{fileExtension=".bash";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.bash`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
61
+ `}function fJ($,I,M){return{filePath:$,line:I,column:M}}function CJ($,I){let M=I.exec($);if(!M)return null;let G=M[1],J=Number(M[2]),Q=Number(M[3]);if(!G||Number.isNaN(J)||Number.isNaN(Q))return null;return fJ(G,J,Q)}function B4($){let I=/([^\s]+\.tool\.ts):(\d+)\s*$/.exec($);if(!I)return null;let M=I[1],G=Number(I[2]);if(!M||Number.isNaN(G))return null;return fJ(M,G,1)}function x4($){let I=$.split(`
62
+ `);for(let M of I){if(!M.includes(".tool.ts"))continue;let G=CJ(M,/\(([^)]+\.tool\.ts):(\d+):(\d+)\)\s*$/);if(G)return G;let J=CJ(M,/\s+at\s+([^\s]+\.tool\.ts):(\d+):(\d+)\s*$/);if(J)return J;let Q=B4(M);if(Q)return Q}return null}async function D4($,I){if(!await $.exists(I.filePath))return null;let G=await $.readFile(I.filePath,"utf8"),J=O4(G,{start:{line:I.line,column:I.column}},{linesAbove:2,linesBelow:2,highlightCode:!0,forceColor:!0});return`${I.filePath}:${I.line}:${I.column}
63
+ ${J}
64
+ `}function A4($){let I=[],M=typeof $.exitCode==="number"?String($.exitCode):"unknown";I.push(`exit code: ${M}`);let G=dJ($.stderr);if(G.length>0)I.push("stderr:"),I.push(G);let J=dJ($.stdout);if(J.length>0)I.push("stdout:"),I.push(J);return I.join(`
65
+ `)}function dJ($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");return""}function F4($,I){let M=[];if($ instanceof Error){if(M.push(`${$.name}: ${$.message}`),I&&typeof $.stack==="string"&&$.stack.length>0)M.push("stack:"),M.push($.stack);return M.join(`
66
+ `)}return M.push(String($)),M.join(`
67
+ `)}async function L4($,I){if(!I)return null;let M=x4(I);if(!M)return null;return await D4($,M)}function E4($,I){if(!I)return[];if(!$||$.length===0)return[];return["stack:",$]}async function T4($,I){let M=[A4($)],G=typeof $.stack==="string"?$.stack:void 0,J=E4(G,I);return M.push(...J),M}async function S4($,I){return[F4($,I)]}async function k4($){let I=V4($.logger),M=[],G=w4($.error),J=await L4($.fileSystem,G);if(J)M.push("---"),M.push(J),M.push("---");if(I)if(uJ($.error)){let Y=await T4($.error,!0);M.push(...Y)}else{let Y=await S4($.error,!0);M.push(...Y)}if(M.length===0)return"";return z4(M.join(`
68
+ `))}function w4($){if(uJ($))return typeof $.stack==="string"?$.stack:void 0;if($ instanceof Error)return $.stack;return}async function pJ($){let I=await k4($);if(I.length>0)$.writeOutput(I)}function b4($){if(typeof $!=="object"||$===null)return!1;return $.name==="ShellError"}function N4($,I){return Object.assign((G,...J)=>{return $(G,...J).cwd(I)},$)}function y4($,I,M,G){if(I.length===0)return $;let J=M===4?";":":",Q=G.PATH||"",Y=[...I,Q].join(J),X={...G,PATH:Y};return Object.assign((W,...q)=>{let U=W[0]||"";for(let K=0;K<q.length;K++)U+=String(q[K])+(W[K+1]||"");return $`sh -c ${U}`.env(X)},$)}class EG{defaultTimeoutMs=60000;writeOutput;constructor($){this.writeOutput=$}async executeHook($,I,M,G,J={}){let Q=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHook",context:I}),Y=J.timeoutMs??this.defaultTimeoutMs,X=J.continueOnError??!1,R=Date.now();Q.debug(F.hookExecutor.executingHook(I,Y));let W;try{let q=M(G),U=new Promise((O,B)=>{W=setTimeout(()=>{B(Error(F.hookExecutor.timeoutExceeded(I,Y)))},Y)});if(await Promise.race([q,U]),W!==void 0)clearTimeout(W);let H=Date.now()-R;return Q.debug(F.hookExecutor.hookCompleted(I,H)),{success:!0,durationMs:H,skipped:!1}}catch(q){if(W!==void 0)clearTimeout(W);let U=Date.now()-R,H=q instanceof Error?q.message:String(q),K=PJ(q);if(Q.error(F.outcome.hookFailed(K),q),b4(q))await pJ({fileSystem:G.fileSystem,logger:Q,hookName:I,toolName:G.toolName,error:q,writeOutput:this.writeOutput});if(X)Q.debug(F.hookExecutor.continuingDespiteFailure(I));return{success:!1,error:H,durationMs:U,skipped:!1}}}createEnhancedContext($,I,M){let G=I instanceof f?I.withToolName($.toolName):I,J=$.toolConfig?.configFilePath,Q=J?cJ.dirname(J):void 0,Y="binaryPaths"in $&&Array.isArray($.binaryPaths)?$.binaryPaths:[],X=[...new Set(Y.map((H)=>cJ.dirname(H)))],R,W=M&&!eM($.$);if(W&&$.installEnv)R=Z$({logger:M,skipCommandLog:!0,env:$.installEnv});else R=$.$;let q=$.installEnv??process.env;if(X.length>0)R=y4(R,X,$.systemInfo.platform,q);if(Q)R=N4(R,Q);if(W)R=EJ(R,M);return{...$,$:R,fileSystem:G}}async executeHooks($,I,M){let G=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHooks"}),J=[];for(let Y of I){let{name:X,hook:R,options:W}=Y,q=await this.executeHook($,X,R,M,W);if(J.push(q),!q.success&&!W?.continueOnError){G.debug(F.hookExecutor.stoppingDueToFailure(X));break}}return J}}import{minimatch as v4}from"minimatch";import xI from"path";async function DI($,I,M,G,J,Q){let Y=Q.getSubLogger({name:"setupBinariesFromArchive"}),X=xI.join(G.projectConfig.paths.generatedDir,"binaries"),R=s$(M.binaries),W=xI.basename(G.stagingDir);return await P4($,I,R,W,J,X,Y)}async function P4($,I,M,G,J,Q,Y){let X=Y.getSubLogger({name:"setupBinariesUsingPatterns"}),R=[];for(let W of M){let{name:q,pattern:U}=W,H=await u4($,J,U,q,X);if(!H){X.error(F.binarySetupService.binaryNotFound(q,U));let O=await hJ($,J);if(O.length>0){let B=O.join(`
69
+ `);X.error(F.binarySetupService.extractedFilesTree(J,B))}continue}let K=xI.relative(J,H);await Y0($,I,q,G,K,Q,X),R.push(H)}return R}async function hJ($,I,M="",G=3,J=0){let Q=[];if(J>=G)return Q;let Y=[];try{Y=await $.readdir(I)}catch{return Q}let X=Y.toSorted();for(let R=0;R<X.length;R++){let W=X[R];if(!W)continue;let q=R===X.length-1,U=xI.join(I,W),H=q?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",K=M+(q?" ":"\u2502 "),O=await C4($,U,W,M,H,K,G,J);Q.push(...O)}return Q}async function C4($,I,M,G,J,Q,Y,X){let R=[];try{let W=await $.stat(I),q=W.isDirectory()?`${M}/`:M;if(R.push(`${G}${J}${q}`),W.isDirectory()&&X<Y-1){let U=await hJ($,I,Q,Y,X+1);R.push(...U)}}catch{R.push(`${G}${J}${M} (inaccessible)`)}return R}async function d4($,I){return((await $.stat(I)).mode&73)!==0}async function u4($,I,M,G,J){J.getSubLogger({name:"findBinaryUsingPattern"}).debug(F.binarySetupService.searchingWithPattern(M,I));let X=(await yI($,I,I)).filter((U)=>v4(U,M));if(X.length===0)return null;let R=[];for(let U of X){let H=xI.join(I,U);if(await d4($,H))R.push(U)}if(R.length===0)return null;let W=R.find((U)=>xI.basename(U)===G);if(W)return xI.join(I,W);let q=R[0];if(q)return xI.join(I,q);return null}import TG from"path";async function JM($,I,M,G,J,Q){let Y=Q.getSubLogger({name:"setupBinariesFromDirectDownload"}),X=s$(M.binaries),R=X[0]?.name||I;await $.chmod(J,493);let W=TG.join(G.projectConfig.paths.generatedDir,"binaries"),q=TG.basename(J),U=TG.basename(G.stagingDir);if(await Y0($,I,R,U,q,W,Y),X.length>1)Y.debug(F.binarySetupService.directDownloadSingleBinary(X.length,R))}async function J$($,I,M,G){try{return await G()}catch(J){return M.error(F.outcome.installFailed($),J),{success:!1,error:J instanceof Error?J.message:String(J)}}}class SG{projectConfig;systemInfo;resolvedFileSystem;fileSystem;$shell;emitInstallEvent;constructor($){this.projectConfig=$.projectConfig,this.systemInfo=$.systemInfo,this.resolvedFileSystem=$.resolvedFileSystem,this.fileSystem=$.fileSystem,this.$shell=$.$shell,this.emitInstallEvent=$.emitInstallEvent}createMinimalContext($){let I=this.getToolDirectory($.toolConfig),M=$.parentLogger.getSubLogger({name:"minimalContext"});return{...zM(this.projectConfig,this.systemInfo,$.toolName,I,this.resolvedFileSystem,M),stagingDir:"",timestamp:"",toolConfig:$.toolConfig,$:$.$shell??GI(this.$shell,process.env),fileSystem:this.fileSystem}}createBaseInstallContext($){let I=this.getToolDirectory($.toolConfig),M=$.parentLogger.getSubLogger({name:`install-${$.toolName}`}),G=zM(this.projectConfig,this.systemInfo,$.toolName,I,this.resolvedFileSystem,M),J=$.$shell??GI(this.$shell,process.env),Q=(W={})=>({...G,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:J,fileSystem:this.fileSystem,installEnv:$.installEnv,...W}),Y=Q(),X=async(W,q)=>{await this.emitInstallEvent({type:W,toolName:$.toolName,context:{...Q(q),emitEvent:X,logger:M}})};return Y.emitEvent=X,{context:Y,logger:M}}getToolDirectory($){return $.configFilePath?f4.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function Z0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function p4($){return Array.isArray($)&&$.every((I)=>typeof I==="function")}function c4($){if(!Z0($))return!1;return typeof $.getSubLogger==="function"}function kG($){if(!Z0($))return;let I=$.installParams;if(!Z0(I))return;let M=I.hooks;if(!Z0(M))return;let G=Object.entries(M);if(G.length===0)return;let J={};for(let[Q,Y]of G){if(!p4(Y))return;J[Q]=Y}return J}class wG{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,I,M){if(!I)return;let G=kG(I);if(!G)return;let J=G[$.type];if(!J)return;let Q=$.context.logger,Y=c4(Q)?Q:M,X=$.context.fileSystem,R=this.hookExecutor.createEnhancedContext($.context,X,Y);for(let W of J){let q=await this.hookExecutor.executeHook(Y,$.type,W,R);if(!q.success){let U=q.error?`${$.type} hook failed: ${q.error}`:`Hook ${$.type} failed`;throw Error(U)}}}async executeBeforeInstallHook($,I,M,G){let J=G.getSubLogger({name:"executeBeforeInstallHook"}),Y=kG($)?.["before-install"];if(!Y)return null;J.debug(F.lifecycle.hookExecution("before-install"));let X=this.hookExecutor.createEnhancedContext(I,M,J);for(let R of Y){let W=await this.hookExecutor.executeHook(J,"before-install",R,X);if(!W.success)return{success:!1,error:`beforeInstall hook failed: ${W.error}`}}return null}async executeAfterInstallHook($,I,M,G){let J=G.getSubLogger({name:"executeAfterInstallHook"}),Y=kG($)?.["after-install"];if(!Y)return;J.debug(F.lifecycle.hookExecution("after-install"));let X=this.hookExecutor.createEnhancedContext(I,M,J);for(let R of Y)await this.hookExecutor.executeHook(J,"after-install",R,X,{continueOnError:!0})}}import YI from"path";function h4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function m4($){let I={};if(!$.success)return I;if(!("metadata"in $))return I;let M=$.metadata;if(!h4(M))return I;let{method:G,...J}=M;if(typeof G==="string")return{...J,installMethod:G};return M}class bG{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,I,M,G,J,Q){let Y=Q.getSubLogger({name:"recordInstallation"});if(!J.success)return;try{let X="version"in J&&J.version?J.version:G.timestamp,R=I.installParams,W=R&&typeof R==="object"&&"version"in R&&typeof R.version==="string"?R.version:void 0,q="originalTag"in J&&typeof J.originalTag==="string"?J.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:X,installPath:M,timestamp:G.timestamp,binaryPaths:J.binaryPaths,configuredVersion:W,originalTag:q,...m4(J)}),Y.debug(F.outcome.installSuccess($,X,"registry-recorded"))}catch(X){Y.error(F.outcome.installFailed("registry-record"),X)}}async createBinaryEntrypoints($,I,M,G,J,Q){let Y=G.getSubLogger({name:"createBinaryEntrypoints"}),X=YI.join(this.projectConfig.paths.binariesDir,$);if(await M.ensureDir(X),Q){let R=YI.join(X,"external");await M.ensureDir(R);for(let W of I){let q=YI.basename(W),U=YI.join(R,q);try{await this.symlinkGenerator.createBinarySymlink(Y,W,U)}catch(H){throw Y.error(F.lifecycle.externalBinaryMissing($,q,W)),H}}return}for(let R of I){let W=YI.basename(R),q=YI.join(J,W);if(R===q)continue;try{if(await M.exists(q))await M.rm(q,{force:!0})}catch(U){throw Y.error(F.binarySymlink.removeExistingFailed(q),U),U}try{await M.copyFile(R,q);let H=(await M.stat(R)).mode&511;await M.chmod(q,H)}catch(U){throw Y.error(F.binarySymlink.creationFailed(q,R),U),U}}}async updateCurrentSymlink($,I,M,G,J){let Q=M.getSubLogger({name:"updateCurrentSymlink"}),Y=YI.join(this.projectConfig.paths.binariesDir,$),X=YI.join(Y,"current");await I.ensureDir(Y);let R=J?"external":YI.basename(G);try{if(await I.exists(X))await I.rm(X,{force:!0,recursive:!0})}catch(W){throw Q.error(F.lifecycle.removingExistingSymlink(X),W),W}try{await I.withFileType("symlink").symlink(R,X,"dir")}catch(W){throw Q.error(F.lifecycle.creatingExternalSymlink(X,R),W),W}try{let W=await I.readlink(X);if(W!==R)throw Q.error(F.lifecycle.symlinkVerificationFailed(X)),Error(`Symlink verification failed: ${X} points to ${W}, expected ${R}`)}catch(W){throw Q.error(F.lifecycle.symlinkVerificationFailed(X),W),W}}}class NG{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;completionGenerator;installContextFactory;currentToolConfig;constructor($,I,M,G,J,Q,Y,X,R,W,q){this.logger=$.getSubLogger({name:"Installer"}),this.fs=I,this.resolvedFs=M,this.projectConfig=G,this.hookExecutor=W,this.hookLifecycle=new wG(W),this.toolInstallationRegistry=J,this.systemInfo=Q,this.registry=Y,this.installationStateWriter=new bG({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:X}),this.$=R,this.completionGenerator=q,this.installContextFactory=new SG({projectConfig:this.projectConfig,systemInfo:this.systemInfo,resolvedFileSystem:this.resolvedFs,fileSystem:this.fs,$shell:this.$,emitInstallEvent:async(U)=>{await this.registry.emitEvent(U)}}),this.registry.onEvent(async(U)=>{await this.hookLifecycle.handleInstallEvent(U,this.currentToolConfig,this.logger)})}async isExistingInstallationHealthy($,I,M,G){let J=G.getSubLogger({name:"isExistingInstallationHealthy"});if(!await this.resolvedFs.exists(I.installPath))return J.warn(F.lifecycle.existingInstallPathMissing(I.installPath)),!1;let Y=o(M.binaries,AI.join(this.projectConfig.paths.binariesDir,$,"current"));if(Y.length===0)return!0;let X=AI.join(this.projectConfig.paths.binariesDir,$,"current");if(!await this.resolvedFs.exists(X))return J.warn(F.lifecycle.currentDirMissing(X)),!1;for(let W of Y)if(!await this.resolvedFs.exists(W))return J.warn(F.lifecycle.currentBinaryMissing(W)),!1;return!0}async shouldSkipInstallation($,I,M,G){let J=G.getSubLogger({name:"shouldSkipInstallation"});if(M?.force||M?.skipVersionCheck)return null;let Q=await this.toolInstallationRegistry.getToolInstallation($);if(!Q)return null;if(!await this.isExistingInstallationHealthy($,Q,I,J))return null;let X=AI.join(this.projectConfig.paths.binariesDir,$,"current"),R=o(I.binaries,X),q=this.registry.get(I.installationMethod)?.getShellInit?.($,I,X),U=await this.getTargetVersion($,I);if(U){if(Q.version===U)return J.debug(F.outcome.installSuccess($,U,"already-installed")),{success:!0,version:Q.version,installationMethod:"already-installed",binaryPaths:R,shellInit:q};return J.debug(F.outcome.outdatedVersion($,Q.version,U)),null}return J.debug(F.outcome.installSuccess($,Q.version,"already-installed-latest")),{success:!0,version:Q.version,installationMethod:"already-installed",binaryPaths:R,shellInit:q}}async executeInstallationMethod($,I,M,G,J){return await this.registry.install(J,I.installationMethod,$,I,M,G)}isShellCompletionConfigInput($){if(typeof $==="string"||typeof $==="function")return!0;if(typeof $!=="object"||$===null)return!1;return"source"in $||"cmd"in $||"url"in $}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin?{bin:$.bin}:{}};if("url"in $)return{url:$.url,...$.source?{source:$.source}:{},...$.bin?{bin:$.bin}:{}};return{source:$.source,...$.bin?{bin:$.bin}:{}}}async prepareUrlCompletionAssets($,I,M,G,J){let Q=J.getSubLogger({name:"prepareUrlCompletionAssets"});if(!this.completionGenerator?.prepareUrlCompletionSource)return;let Y=["zsh","bash","powershell"],X=G??I.version??"latest";for(let R of Y){let W=I.shellConfigs?.[R]?.completions;if(!this.isShellCompletionConfigInput(W))continue;let q={version:X},U=await $I(q,W),H=this.normalizeCompletionConfig(U);if(!H.url)continue;let K={...q,toolName:$,toolInstallDir:M,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,homeDir:this.projectConfig.paths.homeDir,configFilePath:I.configFilePath};try{let O=await this.completionGenerator.prepareUrlCompletionSource(H,$,K);Q.debug(F.completion.preparedFromUrl(R,O))}catch(O){Q.warn(F.completion.prepareFailed(R),O)}}}async install($,I,M){let G=this.logger.getSubLogger({name:"install",context:$}),J=this.getSystemInfo(),Q=I$(I,J);this.currentToolConfig=Q;let Y=this.fs.withToolName($);if(M?.shimMode)Y.setSuppressLogging(!0);try{let X=await this.shouldSkipInstallation($,Q,M,G);if(X)return X;let R=this.registry.get(Q.installationMethod),W=R?.externallyManaged===!0,q=this.projectConfig.paths.binariesDir,U=AI.join(q,$);await Y.ensureDir(U);let H=a6(),K=H;if(Q.version&&Q.version!=="latest")K=Q.version;if(!W&&R?.resolveVersion){let m=this.createMinimalContext($,Q,G);try{let e=await R.resolveVersion($,Q,m,G);if(e)K=e,G.debug(F.lifecycle.versionResolved(e));else G.debug(F.lifecycle.versionFallbackToTimestamp())}catch(e){G.debug(F.lifecycle.versionResolutionFailed(e))}}let O=g4(),B=AI.join(U,O);if(!W)await Y.ensureDir(B),G.debug(F.lifecycle.directoryCreated(B));let j=`DOTFILES_INSTALLING_${$.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`,V="/home/runner/work/dotfiles/dotfiles/packages/build:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/opt/hostedtoolcache/node/24.14.1/x64/bin:/home/runner/.bun/bin:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin",x=J.platform===4?";":":",A=W?V:`${B}${x}${V}`,T={...process.env,[j]:"true",PATH:A},k=GI(this.$,T),{context:w,logger:u}=this.createBaseInstallContext($,B,H,Q,G,k,T),h=await this.hookLifecycle.executeBeforeInstallHook(Q,w,Y,u);if(h)return h;let D;try{D=await this.executeInstallationMethod($,Q,w,M,u),D.installationMethod=Q.installationMethod;let m=D.success&&"version"in D?D.version:void 0,e=K===H&&m&&m!==H?m:K,a=W?AI.join(U,"external"):AI.join(U,e);if(D.success&&!W){if(await Y.exists(a))await Y.rm(a,{recursive:!0,force:!0});if(await Y.rename(B,a),G.debug(F.lifecycle.directoryRenamed(B,a)),D.success&&"binaryPaths"in D&&D.binaryPaths)D.binaryPaths=D.binaryPaths.map((N)=>N.startsWith(B)?N.replace(B,a):N)}if(D.success&&W)await Y.ensureDir(a);let $$=D.success&&"binaryPaths"in D?D.binaryPaths:void 0;if(D.success&&$$){let N=[];for(let W$ of $$)if(await Y.exists(W$))N.push(W$);if(N.length>0)await this.installationStateWriter.createBinaryEntrypoints($,N,Y,G,a,W)}if(D.success)await this.installationStateWriter.updateCurrentSymlink($,Y,G,a,W);if(!W&&!D.success&&await Y.exists(B)){G.debug(F.lifecycle.cleaningFailedInstallDir(B)),await Y.rm(B,{recursive:!0,force:!0});let N=AI.dirname(B);try{if((await Y.readdir(N)).length===0)await Y.rmdir(N)}catch{}}if(!D.success&&D.error)G.error(Z(D.error));if(D.success){let N="binaryPaths"in D&&Array.isArray(D.binaryPaths)?D.binaryPaths:[],W$="version"in D?D.version:void 0;await this.prepareUrlCompletionAssets($,Q,a,W$,G);let e$=W?V:`${a}${x}${V}`,cM={...process.env,[j]:"true",PATH:e$},k$=GI(this.$,cM),s0={...w,$:k$,installedDir:a,binaryPaths:N,version:W$,installEnv:cM};await this.hookLifecycle.executeAfterInstallHook(Q,s0,Y,u),await this.installationStateWriter.recordInstallation($,Q,a,w,D,u)}return D}catch(m){return D={success:!1,error:m instanceof Error?m.message:String(m),installationMethod:Q.installationMethod},G.error(Z(D.error)),D}}catch(X){let R={success:!1,error:X instanceof Error?X.message:String(X),installationMethod:Q.installationMethod};return G.error(Z(R.error)),R}}async getTargetVersion($,I){if(I.version&&I.version!=="latest")return I.version;return null}createMinimalContext($,I,M){return this.installContextFactory.createMinimalContext({toolName:$,toolConfig:I,parentLogger:M})}createBaseInstallContext($,I,M,G,J,Q=GI(this.$,process.env),Y){let X=J.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:I,timestamp:M,toolConfig:G,parentLogger:X,$shell:Q,installEnv:Y})}getSystemInfo(){return this.systemInfo}}import{z as dI}from"zod";var c$={installing:($)=>Z(`Installing from brew: toolName=${$}`),executingCommand:($)=>Z(`installFromBrew: Executing command: ${$}`),fetchingVersion:($)=>Z(`Fetching version info for formula: ${$}`),versionFetched:($,I)=>Z(`Fetched version ${I} for formula ${$}`),versionNotFound:($)=>Z(`No stable version found for formula ${$}`),versionFetchFailed:($)=>Z(`Failed to fetch version for formula ${$}`),prefixFetched:($,I)=>Z(`Formula ${$} installed at prefix: ${I}`),prefixFetchFailed:($)=>Z(`Failed to fetch prefix for formula ${$}`),prefixFallback:($,I)=>Z(`Using fallback prefix for formula ${$}: ${I}`)};var n4=dI.object({name:dI.string(),versions:dI.object({stable:dI.string(),head:dI.string().optional(),bottle:dI.boolean().optional()})});async function mJ($,I,M,G,J,Q,Y){let X=J.getSubLogger({name:"installFromBrew"});if(X.debug(c$.installing($),I.installParams),!I.installParams)return{success:!1,error:"Install parameters not specified"};let R=I.installParams,W=R.formula||$,q=R.cask||!1,U=R.tap;return J$("brew",$,X,async()=>{let K=Y??Z$({logger:X,skipCommandLog:!0});await a4(W,q,U,G?.force,X,Q,K);let O=await l4(W,X,Q),B=o(I.binaries,`${O}/bin`),j,V=B[0];if(R.versionArgs&&R.versionRegex&&V)j=await D$({binaryPath:V,args:R.versionArgs,regex:R.versionRegex,shellExecutor:Q});else j=await i4(W,X,Q);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:W,isCask:q,tap:U}}})}async function i4($,I,M){try{I.debug(c$.fetchingVersion($));let J=(await M`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),Q=JSON.parse(J),Y=dI.array(n4).parse(Q);if(Y.length>0&&Y[0]?.versions.stable){let X=Y[0].versions.stable,R=j$(X);return I.debug(c$.versionFetched($,R)),R}I.debug(c$.versionNotFound($));return}catch(G){I.debug(c$.versionFetchFailed($),G);return}}async function l4($,I,M){try{let J=(await M`brew --prefix ${$}`.quiet()).stdout.toString().trim();return I.debug(c$.prefixFetched($,J)),J}catch(G){I.debug(c$.prefixFetchFailed($),G);let Q=`${(await M`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return I.debug(c$.prefixFallback($,Q)),Q}}async function a4($,I,M,G,J,Q,Y){if(M){let R=Array.isArray(M)?M:[M];for(let W of R)J.debug(c$.executingCommand(`brew tap ${W}`)),await Q`brew tap ${W}`.quiet()}let X=["install"];if(I)X.push("--cask");if(G)X.push("--force");X.push($),J.info(c$.executingCommand(`brew ${X.join(" ")}`)),await Y`brew ${X}`}import{z as h$}from"zod";var R0=s.extend({formula:h$.string().optional(),cask:h$.boolean().optional(),tap:h$.union([h$.string(),h$.array(h$.string())]).optional(),versionArgs:h$.array(h$.string()).optional(),versionRegex:h$.union([h$.string(),h$.instanceof(RegExp)]).optional()});import{z as r4}from"zod";var gJ=t.extend({installationMethod:r4.literal("brew"),installParams:R0});var s4="1.0.0";class yG{shell;method="brew";displayName="Homebrew Installer";version=s4;paramsSchema=R0;toolConfigSchema=gJ;constructor($){this.shell=$}externallyManaged=!0;async install($,I,M,G,J){let Q=await mJ($,I,M,G,J,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as t4}from"smol-toml";import{z as m$}from"zod";class QM extends Error{statusCode;cause;constructor($,I,M){super($);if(this.name="CargoClientError",this.statusCode=I,this.cause=M,Error.captureStackTrace)Error.captureStackTrace(this,QM)}}var v$={constructor:{initialized:($,I)=>Z(`Initializing ${$} with user agent: ${I}`)},request:{makingRequest:($,I)=>Z(`Making ${$} request to ${I}`)},errors:{emptyResponse:($)=>Z(`Empty response received from ${$}`),jsonParseError:($)=>Z(`JSON parse error for ${$}`)},cratesIo:{querying:($)=>Z(`Querying crates.io for crate ${$}`),notFound:($)=>Z(`Crate not found: ${$}`),metadataError:($)=>Z(`Error fetching crate metadata for ${$}`)},parsing:{parsingCrateMetadata:($)=>Z(`Parsing Cargo.toml from ${$}`),cargoTomlParseError:($)=>Z(`Error parsing Cargo.toml from ${$}`)}};var o4=m$.object({package:m$.object({name:m$.string(),version:m$.string(),edition:m$.string().optional(),description:m$.string().optional(),authors:m$.array(m$.string()).optional(),license:m$.string().optional(),repository:m$.string().optional(),homepage:m$.string().optional()})});class vG{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,I,M,G,J){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=M,this.cratesIoCache=G,this.githubRawCache=J,this.cargoConfig=I.cargo,this.cratesIoCacheEnabled=this.cargoConfig.cratesIo.cache.enabled&&Boolean(this.cratesIoCache),this.cratesIoCacheTtl=this.cargoConfig.cratesIo.cache.ttl,this.githubRawCacheEnabled=this.cargoConfig.githubRaw.cache.enabled&&Boolean(this.githubRawCache),this.githubRawCacheTtl=this.cargoConfig.githubRaw.cache.ttl,this.logger.getSubLogger({name:"constructor"}).debug(v$.constructor.initialized("CargoClient",this.cargoConfig.userAgent))}async request($,I){this.logger.getSubLogger({name:"request"}).debug(v$.request.makingRequest("GET",$));let G=this.buildRequestHeaders(),{useCache:J,cacheKey:Q,cacheTtl:Y}=this.resolveCacheOptions($,I),X=await this.tryReadCache(Q,J);if(X)return X;let R=await this.performDownload($,G),W=this.parseJson(R,$);return await this.tryStoreCache(Q,W,Y,J),W}resolveCacheOptions($,I){if(!I)return{useCache:!1,cacheTtl:0};let M=I.kind,G=M==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,J=M==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,Q=G?`cargo:${M}:${$}`:void 0;return{useCache:G,cacheKey:Q,cacheTtl:J}}async tryReadCache($,I){let M=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!I||!$||!M)return null;try{let G=await M.get($);if(G)return G}catch{}return null}async tryStoreCache($,I,M,G){let J=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!G||!$||!J)return;try{await J.set($,I,M)}catch{}}parseJson($,I){let M=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw M.error(v$.errors.emptyResponse(I)),new q$(M,"Empty response received from API",I);try{return JSON.parse($.toString("utf-8"))}catch(G){if(G instanceof SyntaxError)throw M.error(v$.errors.jsonParseError(I),G),new QM(`Invalid JSON response from ${I}: ${G.message}`,void 0,G);throw G}}async performDownload($,I){let M=this.logger.getSubLogger({name:"performDownload"}),G=await this.downloader.download(M,$,{headers:I});if(!G)throw M.error(v$.errors.emptyResponse($)),new q$(M,"Empty response received from API",$);return G}buildRequestHeaders(){return{Accept:"application/json","User-Agent":this.cargoConfig.userAgent}}async getCrateMetadata($){let I=this.logger.getSubLogger({name:"getCrateMetadata"});I.debug(v$.cratesIo.querying($));let M=`${this.cargoConfig.cratesIo.host}/api/v1/crates/${$}`;try{return await this.request(M,{kind:"cratesIo"})}catch(G){if(G instanceof N$)return I.error(v$.cratesIo.notFound($)),null;throw I.error(v$.cratesIo.metadataError($),G),G}}buildCargoTomlUrl($,I="main"){return`${this.cargoConfig.githubRaw.host}/${$}/${I}/Cargo.toml`}async getCargoTomlPackage($){let I=this.logger.getSubLogger({name:"getCargoTomlPackage"});I.debug(v$.parsing.parsingCrateMetadata($));let{useCache:M,cacheKey:G}=this.resolveCacheOptions($,{kind:"githubRaw"});if(M){let J=await this.tryReadCache(G,M);if(J)return J}try{let J=await this.downloader.download(I,$,{headers:this.buildRequestHeaders()});if(!J||J.length===0)return I.error(v$.errors.emptyResponse($)),null;let Q=this.parseCargoToml(J);return await this.tryStoreCache(G,Q,this.githubRawCacheTtl,M),Q}catch(J){if(J instanceof QM)throw J;if(J instanceof N$)return null;throw I.error(v$.parsing.cargoTomlParseError($),J),J}}parseCargoToml($){let I=this.logger.getSubLogger({name:"parseCargoToml"}),M=$.toString("utf-8"),G=t4(M),J=o4.safeParse(G);if(!J.success)throw I.zodErrors(J.error),new QM("Could not parse version from Cargo.toml [package] section",void 0);return J.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import e4 from"path";var H$={installing:($)=>Z(`Installing from cargo: ${$}`),foundVersion:($,I)=>Z(`Found crate ${$} version ${I}`),downloadingAsset:($,I)=>Z(`Downloading asset ${$} from ${I}`),archiveExtracted:()=>Z("Archive extracted: %o"),cleaningArchive:($)=>Z(`Cleaning up downloaded archive: ${$}`),parsingMetadata:($)=>Z(`Parsing crate metadata from: ${$}`),queryingCratesIo:($)=>Z(`Querying crates.io API for crate: ${$}`),queryingGitHubReleases:($)=>Z(`Querying GitHub releases for ${$}`),versionResolutionResolved:($,I)=>Z(`Resolved version for ${$}: ${I}`),versionResolutionFailed:($,I)=>Z(`Failed to resolve version for ${$}: ${I}`),versionResolutionException:($,I)=>Z(`Exception while resolving version for ${$}: ${String(I)}`),updateCheckFailed:($)=>Z(`Failed to check update for cargo tool: ${$}`)};async function nJ($,I,M,G,J,Q,Y,X,R,W,q){let U=W.getSubLogger({name:"installFromCargo"});if(U.debug(H$.installing($)),!I.installParams)return{success:!1,error:"Install parameters not specified"};let H=I.installParams,K=H.crateName||$;return J$("cargo",$,U,async()=>{let B=R$(J,$),j=await M9(K,H,Y,U);U.debug(H$.foundVersion(K,j.version));let V=await J9(K,j.version,H,M,q);U.debug(H$.downloadingAsset(`${K}-${j.version}`,V));let x=`${K}-${j.version}.tar.gz`,A=e4.join(M.stagingDir,x);await U$(U,V,A,x,Q,G);let T={...M,version:j.version},k=await $9(I,R,T,A,B,U);if(!k.success)return k;let w=await X.extract(U,A,{targetDir:M.stagingDir});U.debug(H$.archiveExtracted(),w);let u=await DI(J,$,I,M,M.stagingDir,U),h=await I9(I,R,T,w,B,U);if(!h.success)return h;if(await J.exists(A))await J.rm(A),U.debug(H$.cleaningArchive(A));let D=u.length>0?u:o(I.binaries,M.stagingDir),m={method:"cargo",crateName:K,binarySource:H.binarySource||"cargo-quickinstall",downloadUrl:V};return{success:!0,binaryPaths:D,version:j.version,originalTag:j.originalTag,metadata:m}})}async function $9($,I,M,G,J,Q){let Y=$.installParams?.hooks?.["after-download"];if(!Y)return{success:!0};let X=I.createEnhancedContext({...M,downloadPath:G},J);for(let R of Y){let W=await I.executeHook(Q,"afterDownload",R,X);if(!W.success)return{success:!1,error:W.error}}return{success:!0}}async function I9($,I,M,G,J,Q){let Y=$.installParams?.hooks?.["after-install"];if(!Y)return{success:!0};let X=I.createEnhancedContext({...M,extractResult:G},J);for(let R of Y){let W=await I.executeHook(Q,"afterInstall",R,X);if(!W.success)return{success:!1,error:W.error}}return{success:!0}}async function M9($,I,M,G){let J=I.versionSource||"cargo-toml";switch(J){case"cargo-toml":{let Q=I.cargoTomlUrl||M.buildCargoTomlUrl(I.githubRepo||`${$}-community/${$}`);G.debug(H$.parsingMetadata(Q));let Y=await M.getCargoTomlPackage(Q);if(!Y)throw Error(`Failed to fetch or parse Cargo.toml from ${Q}`);return{version:j$(Y.version)}}case"crates-io":{G.debug(H$.queryingCratesIo($));let Q=await M.getLatestVersion($);if(!Q)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(Q)}}case"github-releases":{if(!I.githubRepo)throw Error("githubRepo is required when using github-releases version source");return G9(I.githubRepo,G)}default:throw Error(`Unknown version source: ${J}`)}}async function G9($,I){throw I.debug(H$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function J9($,I,M,G,J){let Q=M.binarySource||"cargo-quickinstall",Y=Q9(G.systemInfo.platform),X=Y9(G.systemInfo.arch);switch(Q){case"cargo-quickinstall":return`${J}/cargo-bins/cargo-quickinstall/releases/download/${$}-${I}/${$}-${I}-${X}-${Y}.tar.gz`;case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases binary source");let W=(M.assetPattern||"{crateName}-{version}-{platform}-{arch}.tar.gz").replace("{crateName}",$).replace("{version}",I).replace("{platform}",Y).replace("{arch}",X);return`${J}/${M.githubRepo}/releases/download/v${I}/${W}`}default:throw Error(`Unknown binary source: ${Q}`)}}function Q9($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function Y9($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as YM}from"zod";var W0=s.extend({crateName:YM.string(),binarySource:YM.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:YM.string().optional(),assetPattern:YM.string().optional(),versionSource:YM.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:YM.string().optional()});import{z as X9}from"zod";var iJ=t.extend({installationMethod:X9.literal("cargo"),installParams:W0});var Z9="1.0.0";class PG{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=Z9;paramsSchema=W0;toolConfigSchema=iJ;constructor($,I,M,G,J,Q){this.fs=$;this.downloader=I;this.cargoClient=M;this.archiveExtractor=G;this.hookExecutor=J;this.githubHost=Q}async install($,I,M,G,J){let Q=await nJ($,I,M,G,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,J,this.githubHost);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata}}async resolveVersion($,I,M,G){let J=G.getSubLogger({name:"resolveVersion"});try{let Y=I.installParams?.crateName;if(!Y)return J.debug(H$.versionResolutionFailed($,"Missing crateName in install params")),null;let X=await this.cargoClient.getLatestVersion(Y);if(!X)return J.debug(H$.versionResolutionFailed($,`Could not fetch version for crate: ${Y}`)),null;let R=FI(X);return J.debug(H$.versionResolutionResolved($,R)),R}catch(Q){return J.debug(H$.versionResolutionException($,Q)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,I,M,G){try{let Q=I.installParams?.crateName;if(!Q)return{success:!1,error:"Missing crateName in install params"};let Y=await this.cargoClient.getLatestVersion(Q);if(!Y)return{success:!1,error:`Could not fetch latest version for crate: ${Q}`};let X=I.version||"latest";if(X==="latest")return{success:!0,hasUpdate:!1,currentVersion:Y,latestVersion:Y};return{success:!0,hasUpdate:X!==Y,currentVersion:X,latestVersion:Y}}catch(J){return G.error(H$.updateCheckFailed($),J),{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}supportsReadme(){return!1}}import q0 from"path";var XI={installing:($)=>Z(`Installing from curl-script: toolName=${$}`),downloadingScript:($)=>Z(`Downloading install script from: ${$}`),executingScript:($)=>Z(`Executing install script using: ${$}`),movingBinary:($,I)=>Z(`Moving binary from ${$} to ${I}`),binaryFoundInInstallDir:($)=>Z(`Binary found in install directory: ${$}`),binaryNotFound:($,I)=>Z(`Binary ${$} not found in search paths: ${I}`),detectedVersion:($)=>Z(`Detected version: ${$}`),versionDetectionFailed:($)=>Z(`Failed to detect version: ${$}`),noBinariesInstalled:($)=>Z(`No binaries were installed. Expected at: ${$}`),scriptOutput:()=>Z("Install script output:")};async function R9($,I,M,G){let J=GM($.binaries);for(let Q of J){let Y=q0.join(I.stagingDir,Q);if(await M.exists(Y)){G.debug(XI.binaryFoundInInstallDir(Y));continue}let X=["/usr/local/bin",q0.join(I.systemInfo.homeDir,".local","bin"),"/usr/bin"],R=!1;for(let W of X){let q=q0.join(W,Q);if(await M.exists(q)){G.debug(XI.movingBinary(q,Y)),await M.copyFile(q,Y),await M.chmod(Y,493),R=!0;break}}if(!R)G.warn(XI.binaryNotFound(Q,`${I.stagingDir}, ${X.join(", ")}`))}}async function lJ($,I,M,G,J,Q,Y,X,R,W){let q=R$(J,$),U=X.getSubLogger({name:"installFromCurlScript"});if(U.debug(XI.installing($)),!I.installParams||!("url"in I.installParams)||!("shell"in I.installParams))return{success:!1,error:"URL or shell not specified in installParams"};let H=I.installParams,K=H.url,O=H.shell;return J$("curl-script",$,U,async()=>{U.debug(XI.downloadingScript(K));let j=q0.join(M.stagingDir,`${$}-install.sh`);await U$(U,K,j,`${$}-install.sh`,Q,G),await q.chmod(j,493);let V={...M,downloadPath:j},x=await y$(I,V,Y,J,U);if(!x.success)return x;U.debug(XI.executingScript(O));let A={projectConfig:M.projectConfig,scriptPath:j,stagingDir:M.stagingDir},T=H.args?await $I(A,H.args):[],k=H.env?await $I(A,H.env):{},w={...process.env,...k},u=W??Z$({logger:U,skipCommandLog:!0}),h="";if(O==="bash"){let N=await u`bash ${j} ${T}`.env(w);h=[N.stdout,N.stderr].filter(Boolean).join(`
70
+ `)}else{let N=await u`sh ${j} ${T}`.env(w);h=[N.stdout,N.stderr].filter(Boolean).join(`
71
+ `)}await R9(I,M,J,U);let D=o(I.binaries,M.stagingDir),m=[];for(let N of D)if(await J.exists(N))m.push(N);if(m.length===0){let N=D.join(", ");if(U.error(XI.noBinariesInstalled(N)),h.trim()){U.error(XI.scriptOutput());for(let W$ of h.trim().split(`
72
+ `))U.error(Z(W$))}return{success:!1,error:`Installation script completed but no binaries were found at expected locations: ${N}`}}let e,a=D[0];if(a)e=await D$({shellExecutor:R,binaryPath:a,args:H.versionArgs,regex:H.versionRegex});return{success:!0,binaryPaths:D,metadata:{method:"curl-script",scriptUrl:K,shell:O},version:e||(I.version!=="latest"?I.version:void 0)}})}import{z as ZI}from"zod";var U0=s.extend({url:ZI.string().url(),shell:ZI.enum(["bash","sh"]),args:ZI.custom().optional(),env:ZI.custom().optional(),versionArgs:ZI.array(ZI.string()).optional(),versionRegex:ZI.union([ZI.string(),ZI.instanceof(RegExp)]).optional()});import{z as H0}from"zod";var aJ=t.extend({installationMethod:H0.literal("curl-script"),installParams:U0,binaries:H0.array(H0.union([H0.string().min(1),X$])).min(1)});var W9="1.0.0";class CG{fs;downloader;hookExecutor;shell;method="curl-script";displayName="Curl Script Installer";version=W9;paramsSchema=U0;toolConfigSchema=aJ;constructor($,I,M,G){this.fs=$;this.downloader=I;this.hookExecutor=M;this.shell=G}async install($,I,M,G,J){let Q=await lJ($,I,M,G,this.fs,this.downloader,this.hookExecutor,J,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,metadata:Q.metadata,version:Q.version}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import q9 from"path";var XM={installing:($)=>Z(`Installing from curl-tar: toolName=${$}`),downloadingArchive:($)=>Z(`Downloading archive from: ${$}`),downloadingTarball:($)=>Z(`Downloading tarball from: ${$}`),extractingTarball:()=>Z("Extracting tarball"),tarballExtracted:()=>Z("Tarball extracted successfully"),archiveExtracted:()=>Z("Archive extracted: %o"),cleaningArchive:($)=>Z(`Cleaning up downloaded archive: ${$}`)};async function rJ($,I,M,G,J,Q,Y,X,R,W){let q=R$(J,$),U=R.getSubLogger({name:"installFromCurlTar"});U.debug(XM.installing($));let H,K;if(!I.installParams||!("url"in I.installParams))return{success:!1,error:"URL not specified in installParams"};let O=I.installParams,B=O.url;return J$("curl-tar",$,U,async()=>{U.debug(XM.downloadingTarball(B));let V=q9.join(M.stagingDir,`${$}.tar.gz`);await U$(U,B,V,`${$}.tar.gz`,Q,G),H={...M,downloadPath:V};let x=await y$(I,H,X,J,U);if(!x.success)return{success:!1,error:x.error};U.debug(XM.extractingTarball());let A=await Y.extract(U,V,{targetDir:M.stagingDir});U.debug(XM.tarballExtracted(),A),K={...H,extractDir:M.stagingDir,extractResult:A};let T=await MM(I,K,X,J,U);if(!T.success)return{success:!1,error:T.error};let k=await DI(q,$,I,M,M.stagingDir,U);if(await q.exists(V))U.debug(XM.cleaningArchive(V)),await q.rm(V);let w=k.length>0?k:o(I.binaries,M.stagingDir),u,h=w[0];if(h)u=await D$({binaryPath:h,args:O.versionArgs,regex:O.versionRegex,shellExecutor:W});return{success:!0,binaryPaths:w,metadata:{method:"curl-tar",downloadUrl:B,tarballUrl:B},version:u||(I.version!=="latest"?I.version:void 0)}})}import{z as ZM}from"zod";var K0=s.extend({url:ZM.string().url(),versionArgs:ZM.array(ZM.string()).optional(),versionRegex:ZM.union([ZM.string(),ZM.instanceof(RegExp)]).optional()}).strict();import{z as _0}from"zod";var sJ=t.extend({installationMethod:_0.literal("curl-tar"),installParams:K0,binaries:_0.array(_0.union([_0.string().min(1),X$])).min(1)});var U9="1.0.0";class dG{fs;downloader;archiveExtractor;hookExecutor;shell;method="curl-tar";displayName="Curl Tar Installer";version=U9;paramsSchema=K0;toolConfigSchema=sJ;constructor($,I,M,G,J){this.fs=$;this.downloader=I;this.archiveExtractor=M;this.hookExecutor=G;this.shell=J}async install($,I,M,G,J){let Q=await rJ($,I,M,G,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,J,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function tJ($){let I=/\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?/,M=$.match(I);if(!M||M.index===void 0)return"";return $.slice(0,M.index)}function oJ($){let I=/(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)/,M=$.match(I);if(!M)return $;let G=M[1];if(!G)return $;return G}function eJ($,I){let M=tJ($),G=oJ(I);return`${M}${G}`}import H9 from"crypto";import uG from"semver";class l extends Error{originalError;statusCode;constructor($,I,M){super($);this.name="GitHubApiClientError",this.statusCode=I,this.originalError=M,Object.setPrototypeOf(this,l.prototype)}}var z={constructor:{initialized:($,I)=>Z(`GitHub API client initialized with base URL ${$} and User-Agent ${I}`),authTokenPresent:()=>Z("GitHub token authentication enabled"),authTokenMissing:()=>Z("No GitHub token provided; requests will be unauthenticated")},ghCli:{initialized:($)=>Z(`GitHub CLI API client initialized for hostname ${$}`),executing:($)=>Z(`Executing gh api request for ${$}`),cacheHit:($)=>Z(`Cache hit for gh api ${$}`),cacheMiss:($)=>Z(`Cache miss for gh api ${$}`),commandFailed:($)=>Z(`gh cli command failed with exit code ${$}`),parseError:($)=>Z(`Failed to parse gh api response for ${$}`),notAvailable:()=>Z("gh cli is not available or not authenticated"),downloadingAsset:($,I,M)=>Z(`Downloading ${$} from ${I}@${M} via gh release download`),downloadComplete:($)=>Z(`Downloaded ${$} via gh cli`),downloadFailed:($,I)=>Z(`gh release download failed for ${$} with exit code ${I}`)},cache:{enabled:($)=>Z(`GitHub API cache enabled with TTL ${$} ms`),disabled:()=>Z("GitHub API cache provided but disabled by configuration"),missing:()=>Z("No GitHub API cache provided; responses will not be cached")},request:{performing:($,I)=>Z(`GitHub API ${$} request to ${I}`),emptyResponse:($)=>Z(`GitHub API returned an empty response buffer for ${$}`)},errors:{requestFailure:($)=>Z(`GitHub API request failure for ${$}`),notFound:($)=>Z(`GitHub resource not found for ${$}`),rateLimit:($,I)=>Z(`GitHub API rate limit exceeded for ${$}, resets at ${I}`),forbidden:($)=>Z(`GitHub API request forbidden for ${$}`),client:($,I)=>Z(`GitHub API client error for ${$} with status ${I}`),server:($,I)=>Z(`GitHub API server error for ${$} with status ${I}`),http:($,I)=>Z(`GitHub API HTTP error for ${$} with status ${I}`),network:($)=>Z(`GitHub API network error for ${$}`),unknown:($)=>Z(`Unknown GitHub API error for ${$}`),constraintLatestError:()=>Z("GitHub API latest constraint lookup failed"),constraintError:($,I,M)=>Z(`GitHub API error while evaluating constraint ${$} for ${I}/${M}`)},releases:{fetchingLatest:($,I)=>Z(`Fetching latest GitHub release for ${$}/${I}`),latestNotFound:($,I)=>Z(`Latest GitHub release not found for ${$}/${I}`),latestError:($,I)=>Z(`Error fetching latest GitHub release for ${$}/${I}`),fetchingByTag:($,I,M)=>Z(`Fetching GitHub release ${$} for ${I}/${M}`),tagNotFound:($,I,M)=>Z(`GitHub release ${$} not found for ${I}/${M}`),tagError:($,I,M)=>Z(`Error fetching GitHub release ${$} for ${I}/${M}`),fetchingAll:($,I)=>Z(`Fetching all GitHub releases for ${$}/${I}`),fetchingPage:($,I)=>Z(`Fetching GitHub releases page ${$} via ${I}`),totalFetched:($,I,M)=>Z(`Fetched ${$} GitHub releases for ${I}/${M}`),filteredPrereleases:($)=>Z(`Filtered prereleases leaving ${$} GitHub releases`),fetchingLatestTags:($,I,M)=>Z(`Fetching ${M} latest release tags for ${$}/${I}`),fetchedTags:($)=>Z(`Fetched ${$} release tags`),fetchTagsError:($,I)=>Z(`Error fetching release tags for ${$}/${I}`)},constraints:{searching:($,I,M)=>Z(`Searching for GitHub release matching constraint ${$} in ${I}/${M}`),pageFetch:($)=>Z(`Iterating GitHub releases pages for constraint ${$}`),pageRequest:($,I,M)=>Z(`Fetching GitHub releases page ${$} for ${I}/${M}`),bestCandidate:($,I)=>Z(`Best GitHub release candidate so far ${$} (version ${I})`),resultFound:($,I)=>Z(`Found GitHub release ${I} for constraint ${$}`),resultMissing:($)=>Z(`No GitHub release found for constraint ${$}`)},rateLimit:{fetching:()=>Z("Fetching GitHub API rate limit status")},tagPattern:{probing:($,I)=>Z(`Probing release tag pattern for ${$}/${I}`),detected:($)=>Z(`Detected latest release tag: ${$}`),noRedirect:($,I)=>Z(`No redirect found for ${$}/${I} latest release`),probeFailed:($,I)=>Z(`Failed to probe tag pattern for ${$}/${I}`)}};class O0{hostname;shell;cache;cacheEnabled;cacheTtlMs;logger;constructor($,I,M,G){this.logger=$.getSubLogger({name:"GhCliApiClient"}),this.hostname=this.extractHostname(I.github.host),this.shell=M,this.cache=G,this.cacheEnabled=I.github.cache.enabled,this.cacheTtlMs=I.github.cache.ttl;let J=this.logger.getSubLogger({name:"constructor"});if(J.debug(z.ghCli.initialized(this.hostname)),this.cache&&this.cacheEnabled)J.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)J.debug(z.cache.disabled());else J.debug(z.cache.missing())}extractHostname($){try{let I=new URL($);if(I.hostname==="api.github.com")return"github.com";return I.hostname.replace(/^api\./,"")}catch{return"github.com"}}generateCacheKey($,I){let M=`${I}:${$}`,G=H9.createHash("sha256").update("gh-cli").digest("hex").substring(0,8);return M+=`:${G}`,M}async request($,I="GET"){let M=this.logger.getSubLogger({name:"request"}),G=this.generateCacheKey($,I),J=await this.tryGetFromCache(G,I,$);if(J)return J;M.debug(z.ghCli.executing($));let Q=this.buildGhApiArgs($,I);try{let Y=await this.executeGhCommand($,Q);return await this.tryCacheResponse(G,Y,I),Y}catch(Y){return this.handleRequestError(Y,$)}}buildGhApiArgs($,I){let M=["api"];if(this.hostname!=="github.com")M.push("--hostname",this.hostname);if(I!=="GET")M.push("--method",I);let G=$.startsWith("/")?$.substring(1):$;return M.push(G),M}async executeGhCommand($,I){let M=this.logger.getSubLogger({name:"executeGhCommand"}),G=["gh",...I].join(" "),J=await this.shell(G).quiet().noThrow();if(J.code!==0)throw M.debug(z.ghCli.commandFailed(J.code)),this.parseGhError(J.stderr,J.code,$);try{return JSON.parse(J.stdout)}catch{throw M.debug(z.ghCli.parseError($)),new l(`Failed to parse gh api response for ${$}`,void 0)}}parseGhError($,I,M){let G=$.toLowerCase();if(G.includes("not found")||G.includes("404"))return new l(`GitHub resource not found: ${M}. Status: 404`,404);if(G.includes("rate limit")||G.includes("403"))return new l(`GitHub API rate limit exceeded for ${M}. Status: 403`,403);if(G.includes("unauthorized")||G.includes("401"))return new l(`GitHub API unauthorized for ${M}. Status: 401`,401);if(G.includes("forbidden"))return new l(`GitHub API forbidden for ${M}. Status: 403`,403);return new l(`gh api command failed for ${M} with exit code ${I}: ${$}`,void 0)}async tryGetFromCache($,I,M){let G=this.logger.getSubLogger({name:"tryGetFromCache"});if(!this.cache||!this.cacheEnabled||I!=="GET")return null;try{let J=await this.cache.get($);if(J)return G.debug(z.ghCli.cacheHit(M)),J;G.debug(z.ghCli.cacheMiss(M))}catch{}return null}async tryCacheResponse($,I,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return;try{await this.cache.set($,I,this.cacheTtlMs)}catch{}}handleRequestError($,I){if(this.logger.getSubLogger({name:"handleRequestError"}).debug(z.errors.requestFailure(I),$),$ instanceof l)throw $;if($ instanceof Error)throw new l(`Error during gh api request to ${I}: ${$.message}`,void 0,$);throw new l(`Unknown error during gh api request to ${I}`)}async getLatestRelease($,I){let M=this.logger.getSubLogger({name:"getLatestRelease"});M.debug(z.releases.fetchingLatest($,I));try{return await this.request(`/repos/${$}/${I}/releases/latest`)}catch(G){if(G instanceof l&&G.statusCode===404)return M.debug(z.releases.latestNotFound($,I)),null;throw M.debug(z.releases.latestError($,I),G),G}}async getReleaseByTag($,I,M){let G=this.logger.getSubLogger({name:"getReleaseByTag"});G.debug(z.releases.fetchingByTag(M,$,I));try{return await this.request(`/repos/${$}/${I}/releases/tags/${M}`)}catch(J){if(J instanceof l&&J.statusCode===404)return G.debug(z.releases.tagNotFound(M,$,I)),null;throw G.debug(z.releases.tagError(M,$,I),J),J}}async getAllReleases($,I,M){let G=this.logger.getSubLogger({name:"getAllReleases"});G.debug(z.releases.fetchingAll($,I),M);let J=M?.perPage||30,Q=M?.limit,Y=1,X=[],R=!0;while(R){let W=`/repos/${$}/${I}/releases?per_page=${J}&page=${Y}`;G.debug(z.releases.fetchingPage(Y,W));let q=await this.request(W);if(q.length===0)R=!1;else{if(X=X.concat(q),Y++,q.length<J)R=!1;if(Q!==void 0&&X.length>=Q)X=X.slice(0,Q),R=!1}}if(G.debug(z.releases.totalFetched(X.length,$,I)),M?.includePrerelease===!1){let W=X.filter((q)=>!q.prerelease);return G.debug(z.releases.filteredPrereleases(W.length)),W}return X}async getReleaseByConstraint($,I,M){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(M,$,I)),M==="latest")return await this.handleLatestConstraint($,I);return await this.findReleaseByVersionConstraint($,I,M)}async handleLatestConstraint($,I){try{return await this.getLatestRelease($,I)}catch(M){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),M),null}}async findReleaseByVersionConstraint($,I,M){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(M));let J=null,Q=null,Y=1,X=30,R=100;while(Y<=R){let W=await this.fetchReleasesPage($,I,Y,X,M);if(!W)break;if(W.length===0)break;let q=this.findBestReleaseFromPage(W,M,J,Q);if(q.release)J=q.release,Q=q.version;if(W.length<X)break;Y++}return this.logConstraintResult(M,J),J}async fetchReleasesPage($,I,M,G,J){let Q=`/repos/${$}/${I}/releases?per_page=${G}&page=${M}`,Y=this.logger.getSubLogger({name:"fetchReleasesPage"});Y.debug(z.constraints.pageRequest(M,$,I));try{return await this.request(Q)}catch(X){return Y.debug(z.errors.constraintError(J,$,I),X),null}}findBestReleaseFromPage($,I,M,G){let J=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Q=M,Y=G;for(let X of $){if(!X.tag_name)continue;let R=X.tag_name.startsWith("v")?X.tag_name.substring(1):X.tag_name;if(this.isVersionSatisfying(R,I)){if(this.isBetterVersion(R,Y))Q=X,Y=R,J.debug(z.constraints.bestCandidate(X.tag_name,R))}}return{release:Q,version:Y}}isVersionSatisfying($,I){return Boolean(uG.valid($))&&uG.satisfies($,I,{includePrerelease:!0})}isBetterVersion($,I){return!I||uG.gt($,I)}logConstraintResult($,I){let M=this.logger.getSubLogger({name:"logConstraintResult"});if(I)M.debug(z.constraints.resultFound($,I.tag_name));else M.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,I,M=5){let G=this.logger.getSubLogger({name:"getLatestReleaseTags"});G.debug(z.releases.fetchingLatestTags($,I,M));try{let Q=(await this.request(`/repos/${$}/${I}/releases?per_page=${M}`)).map((Y)=>Y.tag_name);return G.debug(z.releases.fetchedTags(Q.length)),Q}catch(J){return G.debug(z.releases.fetchTagsError($,I),J),[]}}async probeLatestTag($,I){let M=this.logger.getSubLogger({name:"probeLatestTag"});M.debug(z.tagPattern.probing($,I));try{let G=await this.getLatestRelease($,I);if(G)return M.debug(z.tagPattern.detected(G.tag_name)),G.tag_name;return null}catch{return M.debug(z.tagPattern.probeFailed($,I)),null}}async downloadAsset($,I,M,G,J){let Q=this.logger.getSubLogger({name:"downloadAsset"});Q.debug(z.ghCli.downloadingAsset(G,`${$}/${I}`,M));let Y=J.substring(0,J.lastIndexOf("/")),X=["release","download",M];if(X.push("--repo",`${$}/${I}`),X.push("--pattern",G),X.push("--dir",Y),X.push("--clobber"),this.hostname!=="github.com");let R=["gh",...X].join(" "),W=await this.shell(R).quiet().noThrow();if(W.code!==0)throw Q.debug(z.ghCli.downloadFailed(G,W.code)),new l(`gh release download failed for ${G}: ${W.stderr.trim()||`exit code ${W.code}`}`,void 0);Q.debug(z.ghCli.downloadComplete(G))}}import K9 from"crypto";import fG from"semver";class j0{baseUrl;githubToken;downloader;userAgent;cache;cacheEnabled;cacheTtlMs;logger;constructor($,I,M,G){this.logger=$.getSubLogger({name:"GitHubApiClient"}),this.baseUrl=I.github.host,this.githubToken=I.github.token,this.downloader=M,this.userAgent=I.github.userAgent,this.cache=G,this.cacheEnabled=I.github.cache.enabled,this.cacheTtlMs=I.github.cache.ttl;let J=this.logger.getSubLogger({name:"constructor"});if(J.debug(z.constructor.initialized(this.baseUrl,this.userAgent)),this.githubToken)J.debug(z.constructor.authTokenPresent());else J.debug(z.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)J.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)J.debug(z.cache.disabled());else J.debug(z.cache.missing())}generateCacheKey($,I){let M=`${I}:${$}`;if(this.githubToken&&typeof this.githubToken==="string"&&this.githubToken.length>0){let G=K9.createHash("sha256").update(this.githubToken).digest("hex").substring(0,8);M+=`:${G}`}return M}async request($,I="GET"){let M=this.logger.getSubLogger({name:"request"}),G=`${this.baseUrl}${$}`,J=this.generateCacheKey($,I),Q=await this.tryGetFromCache(J,I);if(Q)return Q;M.debug(z.request.performing(I,G));let Y=this.buildRequestHeaders();try{let X=await this.performRequest(G,Y);return await this.tryCacheResponse(J,X,I),X}catch(X){return this.handleRequestError(X,G)}}async tryGetFromCache($,I){if(!this.cache||!this.cacheEnabled||I!=="GET")return null;try{let M=await this.cache.get($);if(M)return M}catch{}return null}buildRequestHeaders(){let $={Accept:"application/vnd.github.v3+json","User-Agent":this.userAgent};if(this.githubToken)$.Authorization=`token ${this.githubToken}`;return $}async performRequest($,I){let M=this.logger.getSubLogger({name:"performRequest"}),G=await this.downloader.download(M,$,{headers:I});if(!G||G.length===0)throw M.debug(z.request.emptyResponse($)),new q$(this.logger,"Empty response received from API",$);let J=G.toString("utf-8");return JSON.parse(J)}async tryCacheResponse($,I,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return;try{await this.cache.set($,I,this.cacheTtlMs)}catch{}}handleRequestError($,I){let M=this.logger.getSubLogger({name:"handleRequestError"});if(M.debug(z.errors.requestFailure(I),$),$ instanceof N$)throw M.debug(z.errors.notFound(I),$.responseBody),Error(`GitHub resource not found: ${I}. Status: ${$.statusCode}`);if($ instanceof BI)return this.handleRateLimitError($,I);if($ instanceof vI)return this.handleForbiddenError($,I);if($ instanceof PI)return this.handleClientError($,I);if($ instanceof CI)return this.handleServerError($,I);if($ instanceof F$)return this.handleHttpError($,I);if($ instanceof q$)return this.handleNetworkError($,I);return this.handleUnknownError($,I)}handleRateLimitError($,I){let M=this.logger.getSubLogger({name:"handleRateLimitError"}),G=$.resetTimestamp?new Date($.resetTimestamp).toISOString():"N/A";throw M.debug(z.errors.rateLimit(I,G),$.responseBody),new l(`GitHub API rate limit exceeded for ${I}. Status: ${$.statusCode}. Resets at ${G}.`,$.statusCode,$)}handleForbiddenError($,I){throw this.logger.getSubLogger({name:"handleForbiddenError"}).debug(z.errors.forbidden(I),$.responseBody),new l(`GitHub API request forbidden for ${I}. Status: ${$.statusCode}.`,$.statusCode,$)}handleClientError($,I){throw this.logger.getSubLogger({name:"handleClientError"}).debug(z.errors.client(I,$.statusCode),$.responseBody),new l(`GitHub API client error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleServerError($,I){throw this.logger.getSubLogger({name:"handleServerError"}).debug(z.errors.server(I,$.statusCode),$.responseBody),new l(`GitHub API server error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleHttpError($,I){throw this.logger.getSubLogger({name:"handleHttpError"}).debug(z.errors.http(I,$.statusCode),$),new l(`GitHub API HTTP error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleNetworkError($,I){throw this.logger.getSubLogger({name:"handleNetworkError"}).debug(z.errors.network(I),$),new l(`Network error while requesting ${I}: ${$.message}`,void 0,$)}handleUnknownError($,I){if(this.logger.getSubLogger({name:"handleUnknownError"}).debug(z.errors.unknown(I),$),$ instanceof Error)throw new l(`Unknown error during GitHub API request to ${I}: ${$.message}`,void 0,$);throw new l(`Unknown error during GitHub API request to ${I}`)}async getLatestRelease($,I){let M=this.logger.getSubLogger({name:"getLatestRelease"});M.debug(z.releases.fetchingLatest($,I));try{return await this.request(`/repos/${$}/${I}/releases/latest`)}catch(G){if(G instanceof Error&&G.message.includes("GitHub resource not found"))return M.debug(z.releases.latestNotFound($,I)),null;throw M.debug(z.releases.latestError($,I),G),G}}async getReleaseByTag($,I,M){let G=this.logger.getSubLogger({name:"getReleaseByTag"});G.debug(z.releases.fetchingByTag(M,$,I));try{return await this.request(`/repos/${$}/${I}/releases/tags/${M}`)}catch(J){if(J instanceof Error&&J.message.includes("GitHub resource not found"))return G.debug(z.releases.tagNotFound(M,$,I)),null;throw G.debug(z.releases.tagError(M,$,I),J),J}}async getAllReleases($,I,M){let G=this.logger.getSubLogger({name:"getAllReleases"});G.debug(z.releases.fetchingAll($,I),M);let J=M?.perPage||30,Q=M?.limit,Y=1,X=[],R=!0;while(R){let W=`/repos/${$}/${I}/releases?per_page=${J}&page=${Y}`;G.debug(z.releases.fetchingPage(Y,W));let q=await this.request(W);if(q.length===0)R=!1;else{if(X=X.concat(q),Y++,q.length<J)R=!1;if(Q!==void 0&&X.length>=Q)X=X.slice(0,Q),R=!1}}if(G.debug(z.releases.totalFetched(X.length,$,I)),M?.includePrerelease===!1){let W=X.filter((q)=>!q.prerelease);return G.debug(z.releases.filteredPrereleases(W.length)),W}return X}async getReleaseByConstraint($,I,M){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(M,$,I)),M==="latest")return await this.handleLatestConstraint($,I);return await this.findReleaseByVersionConstraint($,I,M)}async handleLatestConstraint($,I){try{return await this.getLatestRelease($,I)}catch(M){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),M),null}}async findReleaseByVersionConstraint($,I,M){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(M));let J=null,Q=null,Y=1,X=30,R=100;while(Y<=R){let W=await this.fetchReleasesPage($,I,Y,X,M);if(!W)break;if(W.length===0)break;let q=this.findBestReleaseFromPage(W,M,J,Q);if(q.release)J=q.release,Q=q.version;if(W.length<X)break;Y++}return this.logConstraintResult(M,J),J}async fetchReleasesPage($,I,M,G,J){let Q=`/repos/${$}/${I}/releases?per_page=${G}&page=${M}`,Y=this.logger.getSubLogger({name:"fetchReleasesPage"});Y.debug(z.constraints.pageRequest(M,$,I));try{return await this.request(Q)}catch(X){return Y.debug(z.errors.constraintError(J,$,I),X),null}}findBestReleaseFromPage($,I,M,G){let J=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Q=M,Y=G;for(let X of $){if(!X.tag_name)continue;let R=X.tag_name.startsWith("v")?X.tag_name.substring(1):X.tag_name;if(this.isVersionSatisfying(R,I)){if(this.isBetterVersion(R,Y))Q=X,Y=R,J.debug(z.constraints.bestCandidate(X.tag_name,R))}}return{release:Q,version:Y}}isVersionSatisfying($,I){return Boolean(fG.valid($))&&fG.satisfies($,I,{includePrerelease:!0})}isBetterVersion($,I){return!I||fG.gt($,I)}logConstraintResult($,I){let M=this.logger.getSubLogger({name:"logConstraintResult"});if(I)M.debug(z.constraints.resultFound($,I.tag_name));else M.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,I,M=5){let G=this.logger.getSubLogger({name:"getLatestReleaseTags"});G.debug(z.releases.fetchingLatestTags($,I,M));try{let Q=(await this.request(`/repos/${$}/${I}/releases?per_page=${M}`)).map((Y)=>Y.tag_name);return G.debug(z.releases.fetchedTags(Q.length)),Q}catch(J){return G.debug(z.releases.fetchTagsError($,I),J),[]}}async probeLatestTag($,I){let M=this.logger.getSubLogger({name:"probeLatestTag"});M.debug(z.tagPattern.probing($,I));let G=`https://github.com/${$}/${I}/releases/latest`;try{let Q=(await fetch(G,{method:"HEAD",redirect:"manual"})).headers.get("location");if(!Q)return M.debug(z.tagPattern.noRedirect($,I)),null;let X=Q.match(/\/releases\/tag\/(.+)$/)?.[1];if(!X)return M.debug(z.tagPattern.noRedirect($,I)),null;let R=decodeURIComponent(X);return M.debug(z.tagPattern.detected(R)),R}catch(J){return M.debug(z.tagPattern.probeFailed($,I),J),null}}}function pG($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $Q($){let I=$.system.length>0?`(${$.system.map(pG).join("|")})`:"",M=$.cpu.length>0?`(${$.cpu.map(pG).join("|")})`:"",G=$.variants.length>0?`(${$.variants.map(pG).join("|")})`:"";return{systemPattern:I,cpuPattern:M,variantPattern:G}}function V0($){let I={system:[],cpu:[],variants:[]};switch($.platform){case 2:I.system=["apple","darwin","apple-darwin","dmg","mac","macos","mac-os","osx","os-x","os64x"],I.variants=["darwin"];break;case 1:I.system=["linux"],I.variants=["musl","gnu","unknown-linux"];break;case 4:I.system=["windows","win32","win64","pc-windows-gnu"],I.variants=["mingw","msys","cygwin","pc-windows"];break;default:I.system=[],I.variants=[];break}switch($.arch){case 2:I.cpu=["arm64","aarch64","aarch"];break;case 1:I.cpu=["amd64","x86_64","x64","x86-64"];break;default:I.cpu=[];break}return I}function IQ($){let I=V0($);return $Q(I)}var _9=[/\.sha\d+(sum)?$/i,/\.md5(sum)?$/i,/\.sum$/i,/^shasums/i,/\.sig$/i,/\.asc$/i,/\.pem$/i,/\.json$/i,/\.txt$/i,/\.sbom$/i,/\.deb$/i,/\.rpm$/i,/\.apk$/i,/\.pkg$/i,/buildable-artifact/i,/\.vsix$/i,/\.b3$/i,/\.zst$/i];function O9($){let I=$.filter((M)=>!_9.some((G)=>G.test(M)));return I.length>0?I:$}function j9($,I){let M=new RegExp(I,"i"),G=$.filter((J)=>M.test(J.toLowerCase()));return G.length>0?G:$}function z0($,I){let M=IQ(I),G=V0(I),J=O9($),Q;if(M.systemPattern){let X=new RegExp(M.systemPattern,"i");Q=J.filter((R)=>X.test(R.toLowerCase()))}else Q=[...J];if(Q.length===0)return;let Y=[];if(M.cpuPattern)Y.push(M.cpuPattern);Y.push(...G.variants);for(let X of Y){if(Q.length<=1)break;Q=j9(Q,X)}return Q[0]}import B9 from"path";var P={startingInstallation:($)=>Z(`Starting installation: ${$}`),fetchLatest:($)=>Z(`Getting latest release for ${$}`),fetchByTag:($,I)=>Z(`Fetching release ${$} for ${I}`),assetSelectorCustom:()=>Z("Using custom asset selector"),assetPatternMatch:($)=>Z(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,I)=>Z(`Selecting asset for platform ${$} and architecture ${I}`),determiningDownloadUrl:($,I)=>Z(`Determining download URL. rawBrowserDownloadUrl="${$}", hasCustomHost=${I}`),usingAbsoluteUrl:($)=>Z(`Using absolute browser_download_url directly: "${$}"`),invalidRelativeUrl:($)=>Z(`Invalid asset download URL format: ${$}`),resolvedRelativeUrl:($,I,M)=>Z(`Resolved relative URL. Base: "${$}", Relative Path: "${I}", Result: "${M}"`),finalDownloadUrl:($,I,M)=>Z(`Final download URL determined. Raw: "${$}", Result: "${I}", hasCustomHost=${M}`),downloadUrlError:($,I)=>Z(`Download URL construction failed: Raw: "${$}", hasCustomHost=${I}`),downloadingAsset:($)=>Z(`Downloading asset: ${$}`),downloadingViaGhCli:($)=>Z(`Downloading ${$} via gh release download (authenticated)`),downloadingViaHttp:($)=>Z(`Downloading ${$} via HTTP`),extractingArchive:($)=>Z(`Extracting archive: ${$}`),archiveExtracted:($,I)=>Z(`Archive extracted. fileCount=${$}, executableCount=${I}`),cleaningArchive:($)=>Z(`Cleaning up downloaded archive: ${$}`),invalidUrl:($)=>Z(`Invalid URL: ${$}`),versionResolutionResolved:($,I)=>Z(`Resolved version for ${$}: ${I}`),versionResolutionFailed:($,I)=>Z(`Failed to resolve version for ${$}: ${I}`),versionResolutionException:($)=>Z(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>Z(`Failed to check update for ${$}`),detectingTagPattern:()=>Z("Detecting tag pattern from latest release"),tagPatternDetectionFailed:()=>Z("Failed to detect tag pattern"),tryingCorrectedTag:($,I)=>Z(`Trying corrected tag '${$}' (original: '${I}')`),usingCorrectedTag:($,I)=>Z(`Found release with corrected tag '${$}' (you specified: '${I}')`),availableReleaseTags:()=>Z("Available release tags:"),releaseTagItem:($)=>Z(` - ${$}`),noReleaseTagsAvailable:()=>Z("No release tags available for this repository")};import{minimatch as V9}from"minimatch";function z9($){return/^[dgimsuvy]*$/.test($)}function MQ($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function GQ($){let I=$.lastIndexOf("/");if(I<=0)throw Error('Invalid regex string: missing closing "/"');let M=$.slice(1,I),G=$.slice(I+1);if(!z9(G))throw Error("Invalid regex string: invalid flags");return new RegExp(M,G)}function JQ($){if(!MQ($))return!0;try{return GQ($),!0}catch{return!1}}function QQ($){if(typeof $==="string")return $;return $.toString()}function YQ($,I){if(typeof I==="string"){if(MQ(I))return GQ(I).test($);return V9($,I)}return I.test($)}async function ZQ($,I,M,G,J,Q,Y,X,R,W,q){let U=q.getSubLogger({name:"installFromGitHubRelease"});if(U.debug(P.startingInstallation($)),!I.installParams||!("repo"in I.installParams))return{success:!1,error:"GitHub repository not specified in installParams"};let H=I.installParams,K=H.repo,O=H.version||"latest",[B,j]=K.split("/");if(!B||!j)return{success:!1,error:`Invalid GitHub repository format: ${K}. Expected format: owner/repo`};try{let V=await EM(K,O,H.prerelease??!1,Y,U);if(!V.success)return V;let x=await cG(V.data,H,M,U);if(!x.success)return x;let A=L9(x.data.browser_download_url,R,U);if(!A.success)return A;let T=B9.join(M.stagingDir,x.data.name),k=await k9(A.data,x.data,Q,Y,B,j,V.data.tag_name,T,G,U);if(!k.success)return k;let w={...M,downloadPath:k.data.downloadPath},u=await w9(I,w,W,J,U);if(!u.success)return u;let h=j$(V.data.tag_name),D=await b9(x.data,k.data.downloadPath,$,I,M,w,J,X,W,J,U);if(!D.success)return D;let m=D.data,e=m.length>0?m:o(I.binaries,M.stagingDir),a={method:"github-release",releaseUrl:V.data.html_url,publishedAt:V.data.published_at,releaseName:V.data.name,downloadUrl:A.data,assetName:x.data.name};return{success:!0,binaryPaths:e,version:h,originalTag:V.data.tag_name,metadata:a}}catch(V){return{success:!1,error:V instanceof Error?V.message:String(V)}}}var x9=5;async function EM($,I,M,G,J){let Q=J.getSubLogger({name:"fetchGitHubRelease"}),[Y,X]=$.split("/");if(!Y||!X)return{success:!1,error:`Invalid GitHub repository format: ${$}. Expected format: owner/repo`};if(I==="latest"){if(Q.debug(P.fetchLatest($)),M){let O=(await G.getAllReleases(Y,X,{perPage:1,includePrerelease:!0,limit:1}))[0];if(!O)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:O}}let U=await G.getLatestRelease(Y,X);if(!U)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:U}}Q.debug(P.fetchByTag(I,$));let R=await G.getReleaseByTag(Y,X,I);if(R)return{success:!0,data:R};let W=await D9(Y,X,I,G,Q);if(W)return{success:!0,data:W};return await A9(Y,X,G,Q),{success:!1,error:`Release '${I}' not found for ${$}. Check the available tags above.`}}async function D9($,I,M,G,J){let Q=J.getSubLogger({name:"fetchWithTagPatternDetection"});Q.debug(P.detectingTagPattern());let Y=await G.probeLatestTag($,I);if(!Y)return Q.debug(P.tagPatternDetectionFailed()),null;let X=eJ(Y,M);if(X!==M){Q.debug(P.tryingCorrectedTag(X,M));let R=await G.getReleaseByTag($,I,X);if(R)return Q.info(P.usingCorrectedTag(X,M)),R}return null}async function A9($,I,M,G){let J=G.getSubLogger({name:"showAvailableReleaseTags"}),Q=await M.getLatestReleaseTags($,I,x9);if(Q.length===0){J.error(P.noReleaseTagsAvailable());return}J.info(P.availableReleaseTags());for(let Y of Q)J.info(P.releaseTagItem(Y))}async function cG($,I,M,G){let J;if(I.assetSelector){G.debug(P.assetSelectorCustom());let Y={...M,assets:$.assets,release:$,assetPattern:I.assetPattern};J=I.assetSelector(Y)}else if(I.assetPattern){G.debug(P.assetPatternMatch(QQ(I.assetPattern)));let Y=I.assetPattern,X=$.assets.filter((R)=>YQ(R.name,Y));if(J=XQ(X,M.systemInfo),!J&&X.length>0)J=X[0]}else G.debug(P.assetPlatformMatch(II(M.systemInfo.platform),MI(M.systemInfo.arch))),J=XQ($.assets,M.systemInfo);if(!J)return{success:!1,error:F9($,I,M)};return{success:!0,data:J}}function XQ($,I){let M=$.map((J)=>J.name),G=z0(M,I);if(!G)return;return $.find((J)=>J.name===G)}function F9($,I,M){let G=$.assets.map((R)=>R.name),J=II(M.systemInfo.platform),Q=MI(M.systemInfo.arch),Y="";if(I.assetSelector)Y=`using a custom assetSelector function for ${J}/${Q}.`;else if(I.assetPattern)Y=`for asset pattern: "${I.assetPattern}" for ${J}/${Q}.`;else Y=`for platform "${J}" and architecture "${Q}".`;return[`No suitable asset found in release "${$.tag_name}" ${Y}`,`Available assets in release "${$.tag_name}":`,...G.map((R)=>` - ${R}`)].join(`
73
+ `)}function L9($,I,M){let G=I.github.host,J=Boolean(G);M.debug(P.determiningDownloadUrl($,J));try{let Y=E9($)?T9($,M):S9($,G,M);if(!Y.success)return Y;return M.debug(P.finalDownloadUrl($,Y.data,J)),Y}catch(Q){return M.error(P.invalidUrl($)),M.debug(P.downloadUrlError($,J),Q),{success:!1,error:Q instanceof Error?Q.message:String(Q)}}}function E9($){return URL.canParse($)}function T9($,I){return I.debug(P.usingAbsoluteUrl($)),{success:!0,data:$}}function S9($,I,M){if(!$.startsWith("/"))return M.debug(P.invalidRelativeUrl($)),{success:!1,error:`Invalid asset download URL format: ${$}`};let G=I&&!I.includes("api.github.com")?I:"https://github.com";if(!/^https?:\/\//.test(G))G=`https:${G.startsWith("//")?"":"//"}${G}`;let Q=new URL($,G).toString();return M.debug(P.resolvedRelativeUrl(G,$,Q)),{success:!0,data:Q}}async function k9($,I,M,G,J,Q,Y,X,R,W){if(G.downloadAsset){W.debug(P.downloadingViaGhCli(I.name));try{return await G.downloadAsset(J,Q,Y,I.name,X),{success:!0,data:{downloadPath:X}}}catch(q){W.debug(P.downloadingAsset($),q instanceof Error?q:Error(String(q)))}}W.debug(P.downloadingViaHttp(I.name));try{return await U$(W,$,X,I.name,M,R),{success:!0,data:{downloadPath:X}}}catch(q){return{success:!1,error:q instanceof Error?q.message:String(q)}}}async function w9($,I,M,G,J){let Q=await y$($,I,M,G,J);if(Q.success)return{success:!0,data:void 0};return{success:!1,error:Q.error||"Hook execution failed"}}async function b9($,I,M,G,J,Q,Y,X,R,W,q){if(uI($.name))return await N9($,I,M,G,J,Q,Y,X,R,W,q);else return await JM(Y,M,G,J,I,q),{success:!0,data:[]}}async function N9($,I,M,G,J,Q,Y,X,R,W,q){q.debug(P.extractingArchive($.name));let U=await X.extract(q,I,{targetDir:J.stagingDir});q.debug(P.archiveExtracted(U.extractedFiles.length,U.executables.length));let H={...Q,extractDir:J.stagingDir,extractResult:U},K=await y9(G,H,W,R,q);if(!K.success)return{success:!1,error:K.error};let O=await DI(Y,M,G,J,J.stagingDir,q);if(await Y.exists(I))q.debug(P.cleaningArchive(I)),await Y.rm(I);return{success:!0,data:O}}async function y9($,I,M,G,J){let Q=await MM($,I,G,M,J);if(Q.success)return{success:!0,data:void 0};return{success:!1,error:Q.error||"Hook execution failed"}}import{z as LI}from"zod";var RM=s.extend({repo:LI.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:LI.union([LI.string().refine(JQ,"assetPattern must be a valid glob or a regex string like /.../"),LI.instanceof(RegExp)]).optional(),version:LI.string().optional(),assetSelector:LI.custom(($)=>typeof $==="function","Must be a function").optional(),ghCli:LI.boolean().optional(),prerelease:LI.boolean().optional()});import{z as B0}from"zod";var RQ=t.extend({installationMethod:B0.literal("github-release"),installParams:RM,binaries:B0.array(B0.union([B0.string().min(1),X$])).min(1)});class hG{fs;downloader;githubApiClient;ghCliApiClient;archiveExtractor;projectConfig;hookExecutor;method="github-release";displayName="GitHub Release";version="1.0.0";paramsSchema=RM;toolConfigSchema=RQ;constructor($,I,M,G,J,Q,Y){this.fs=$;this.downloader=I;this.githubApiClient=M;this.ghCliApiClient=G;this.archiveExtractor=J;this.projectConfig=Q;this.hookExecutor=Y}getApiClient($){if($.installParams.ghCli&&this.ghCliApiClient)return this.ghCliApiClient;return this.githubApiClient}async install($,I,M,G,J){let Q=R$(this.fs,$);return await ZQ($,I,M,G,Q,this.downloader,this.getApiClient(I),this.archiveExtractor,this.projectConfig,this.hookExecutor,J)}async resolveVersion($,I,M,G){try{let J=I.installParams,Q=I.version||"latest",Y=await EM(J.repo,Q,J.prerelease??!1,this.getApiClient(I),G);if(!Y.success)return G.debug(P.versionResolutionFailed($,Y.error)),null;let X=FI(Y.data.tag_name);return G.debug(P.versionResolutionResolved($,X)),X}catch(J){return G.debug(P.versionResolutionException($),J),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,I,M,G){try{let Q=I.installParams.repo,[Y,X]=Q.split("/");if(!Y||!X)return{success:!1,error:`Invalid repo format: ${Q}. Expected owner/repo`};let R=await this.getApiClient(I).getLatestRelease(Y,X);if(!R||!R.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let W=I.version||"latest",q=R.tag_name.replace(/^v/,"");if(W==="latest")return{success:!0,hasUpdate:!1,currentVersion:q,latestVersion:q};return{success:!0,hasUpdate:W!==q,currentVersion:W,latestVersion:q}}catch(J){return G.error(P.updateCheckFailed($),J),{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,I){let G=I.installParams.repo,[J,Q]=G.split("/");if(!J||!Q)return null;let Y=I.version||"main";return`https://raw.githubusercontent.com/${J}/${Q}/${Y}/README.md`}}import fI from"path";var L$={installing:($)=>Z(`Installing from dmg: toolName=${$}`),skippingNonMacOS:($)=>Z(`Skipping DMG installation for ${$}: not running on macOS`),downloadingDmg:($)=>Z(`Downloading DMG from: ${$}`),mountingDmg:($)=>Z(`Mounting DMG: ${$}`),dmgMounted:($)=>Z(`DMG mounted at: ${$}`),copyingApp:($)=>Z(`Copying app bundle: ${$}`),symlinkingBinary:($,I)=>Z(`Symlinking binary: ${$} -> ${I}`),unmountingDmg:($)=>Z(`Unmounting DMG: ${$}`),appNotFound:($)=>Z(`No .app bundle found in DMG at: ${$}`),extractingArchive:()=>Z("Extracting archive to find DMG"),archiveExtracted:($)=>Z(`Archive extracted: ${$} files`),dmgFoundInArchive:($)=>Z(`Found DMG in archive: ${$}`),noDmgInArchive:()=>Z("No .dmg file found in archive")};async function WQ($,I,M,G,J,Q,Y,X,R,W,q,U){let H=R$(J,$),K=R.getSubLogger({name:"installFromDmg"});if(K.debug(L$.installing($)),M.systemInfo.platform!==2)return K.info(L$.skippingNonMacOS($)),{success:!0,binaryPaths:[],metadata:{method:"dmg",dmgUrl:v9(I.installParams.source)}};let O=I.installParams;return J$("dmg",$,K,async()=>{await J.ensureDir(M.stagingDir);let j=await C9(O.source,M,G,Q,q,U,K);if(!j.success)return{success:!1,error:j.error};let V={...M,downloadPath:j.data.downloadPath},x=await y$(I,V,X,J,K);if(!x.success)return{success:!1,error:x.error};let A=j.data.downloadPath;if(uI(j.data.downloadName)){K.debug(L$.extractingArchive());let $$=await Y.extract(K,j.data.downloadPath,{targetDir:M.stagingDir});K.debug(L$.archiveExtracted($$.extractedFiles.length));let N=$$.extractedFiles.find((W$)=>W$.endsWith(".dmg"));if(!N)return K.error(L$.noDmgInArchive()),{success:!1,error:"No .dmg file found in extracted archive"};K.debug(L$.dmgFoundInArchive(N)),A=N}let T=Z$({logger:K,skipCommandLog:!0}),k=fI.join(M.stagingDir,".dmg-mount");await J.ensureDir(k),K.debug(L$.mountingDmg(A)),await T`hdiutil attach -nobrowse -noautoopen -mountpoint ${k} ${A}`,K.debug(L$.dmgMounted(k));let w,u;try{let $$=await c9(O.appName,k,J,K);if(!$$)return{success:!1,error:"No .app bundle found in DMG"};w=$$;let N=fI.join(k,w),W$="/Applications";await J.ensureDir(W$);let e$=fI.join(W$,w);if(await J.exists(e$))await J.rm(e$,{recursive:!0,force:!0});K.debug(L$.copyingApp(w)),await W`cp -R ${N} ${e$}`.quiet(),u=e$}finally{K.debug(L$.unmountingDmg(k)),await W`hdiutil detach ${k}`.quiet().noThrow()}if(await H.exists(A))await H.rm(A);if(A!==j.data.downloadPath&&await H.exists(j.data.downloadPath))await H.rm(j.data.downloadPath);if(!u)return{success:!1,error:"App installation path was not resolved"};let D=s$(I.binaries).map(($$)=>O.binaryPath?fI.join(u,O.binaryPath):fI.join(u,"Contents","MacOS",$$.name)),m,e=D[0];if(e)m=await D$({binaryPath:e,args:O.versionArgs,regex:O.versionRegex,shellExecutor:W});let a={method:"dmg",downloadUrl:j.data.sourceUrl,dmgUrl:j.data.sourceUrl};return{success:!0,binaryPaths:D,metadata:a,version:m||(I.version!=="latest"?I.version:void 0)}})}function v9($){if($.type==="url")return $.url;return`github-release:${$.repo}`}function P9($,I,M){if($.ghCli&&M)return M;return I}async function C9($,I,M,G,J,Q,Y){if($.type==="url")return await d9($,I,M,G,Y);return await u9($,I,M,G,J,Q,Y)}async function d9($,I,M,G,J){J.debug(L$.downloadingDmg($.url));let Q=p9($.url,"download.dmg"),Y=fI.join(I.stagingDir,Q);try{return await U$(J,$.url,Y,Q,G,M),{success:!0,data:{downloadPath:Y,downloadName:Q,sourceUrl:$.url}}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}async function u9($,I,M,G,J,Q,Y){if(!J)return{success:!1,error:"GitHub API client is not configured for DMG github-release source"};let X=P9($,J,Q),R=$.version||"latest",W=await EM($.repo,R,$.prerelease??!1,X,Y);if(!W.success)return W;let q=await cG(W.data,$,I,Y);if(!q.success)return q;let U=q.data.name.endsWith(".dmg"),H=uI(q.data.name);if(!U&&!H)return{success:!1,error:`Selected GitHub release asset must be a .dmg or supported archive: ${q.data.name}`};let[K,O]=$.repo.split("/");if(!K||!O)return{success:!1,error:`Invalid GitHub repository format: ${$.repo}. Expected format: owner/repo`};let B=fI.join(I.stagingDir,q.data.name),j=await f9($,q.data,K,O,W.data.tag_name,B,M,G,X,Y);if(!j.success)return j;return{success:!0,data:{downloadPath:B,downloadName:q.data.name,sourceUrl:q.data.browser_download_url}}}async function f9($,I,M,G,J,Q,Y,X,R,W){if($.ghCli&&R.downloadAsset)try{return await R.downloadAsset(M,G,J,I.name,Q),{success:!0,data:void 0}}catch{}try{return await U$(W,I.browser_download_url,Q,I.name,X,Y),{success:!0,data:void 0}}catch(q){return{success:!1,error:q instanceof Error?q.message:String(q)}}}function p9($,I){try{let G=new URL($).pathname.split("/").pop();if(!G)return I;return decodeURIComponent(G)}catch{return I}}async function c9($,I,M,G){if($)return $;let Q=(await M.readdir(I)).find((Y)=>Y.endsWith(".app"));if(!Q)return G.error(L$.appNotFound(I)),null;return Q}import{z as E$}from"zod";var h9=RM.pick({repo:!0,version:!0,assetPattern:!0,assetSelector:!0,ghCli:!0,prerelease:!0}),m9=E$.object({type:E$.literal("url"),url:E$.string().url()}),g9=E$.object({type:E$.literal("github-release")}).extend(h9.shape),n9=E$.discriminatedUnion("type",[m9,g9]),x0=s.extend({source:n9,appName:E$.string().optional(),binaryPath:E$.string().optional(),versionArgs:E$.array(E$.string()).optional(),versionRegex:E$.union([E$.string(),E$.instanceof(RegExp)]).optional()});import{z as i9}from"zod";var qQ=t.extend({installationMethod:i9.literal("dmg"),installParams:x0});var l9="1.0.0";class mG{fs;downloader;archiveExtractor;hookExecutor;shell;githubApiClient;ghCliApiClient;method="dmg";displayName="DMG Installer";version=l9;paramsSchema=x0;toolConfigSchema=qQ;staticValidation=!0;externallyManaged=!0;missingBinaryMessage="Installation completed. This tool was installed as a macOS app bundle in /Applications. Launch it from Spotlight, Launchpad, or the Applications folder.";constructor($,I,M,G,J,Q,Y){this.fs=$;this.downloader=I;this.archiveExtractor=M;this.hookExecutor=G;this.shell=J;this.githubApiClient=Q;this.ghCliApiClient=Y}async validate($){if($.systemInfo.platform!==2)return{valid:!0,warnings:["DMG installer only works on macOS"]};try{return await this.shell`which hdiutil`.quiet(),{valid:!0}}catch{return{valid:!1,errors:["hdiutil not found \u2014 required for DMG installation"]}}}async install($,I,M,G,J){return WQ($,I,M,G,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,J,this.shell,this.githubApiClient,this.ghCliApiClient)}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import a9 from"crypto";class g$ extends Error{originalError;statusCode;constructor($,I,M){super($);this.name="GiteaApiClientError",this.statusCode=I,this.originalError=M,Object.setPrototypeOf(this,g$.prototype)}}function UQ($){return{name:$.name,browser_download_url:$.browser_download_url,size:$.size,content_type:"application/octet-stream",state:"uploaded",download_count:$.download_count,created_at:$.created_at,updated_at:$.created_at}}var d={constructor:{initialized:($)=>Z(`Gitea API client initialized. baseUrl=${$}`),authTokenPresent:()=>Z("API token is configured"),authTokenMissing:()=>Z("No API token configured")},cache:{enabled:($)=>Z(`Cache enabled. TTL=${$}ms`),disabled:()=>Z("Cache is present but disabled"),missing:()=>Z("No cache configured")},request:{performing:($,I)=>Z(`Gitea API ${$} request to ${I}`),emptyResponse:($)=>Z(`Empty response from ${$}`)},releases:{fetchingLatest:($,I)=>Z(`Fetching latest release for ${$}/${I}`),latestNotFound:($,I)=>Z(`Latest release not found for ${$}/${I}`),latestError:($,I)=>Z(`Error fetching latest release for ${$}/${I}`),fetchingByTag:($,I,M)=>Z(`Fetching release by tag ${$} for ${I}/${M}`),tagNotFound:($,I,M)=>Z(`Release tag ${$} not found for ${I}/${M}`),tagError:($,I,M)=>Z(`Error fetching release ${$} for ${I}/${M}`),fetchingAll:($,I)=>Z(`Fetching all releases for ${$}/${I}`),fetchingPage:($,I)=>Z(`Fetching page ${$}: ${I}`),totalFetched:($,I,M)=>Z(`Fetched ${$} releases for ${I}/${M}`),filteredPrereleases:($)=>Z(`After filtering prereleases: ${$} releases`),fetchingLatestTags:($,I,M)=>Z(`Fetching ${M} latest release tags for ${$}/${I}`),fetchedTags:($)=>Z(`Fetched ${$} release tags`),fetchTagsError:($,I)=>Z(`Error fetching release tags for ${$}/${I}`)},errors:{requestFailure:($)=>Z(`Request failure: ${$}`),notFound:($)=>Z(`Resource not found: ${$}`),rateLimit:($)=>Z(`Rate limit exceeded: ${$}`),forbidden:($)=>Z(`Forbidden: ${$}`),client:($,I)=>Z(`Client error ${I}: ${$}`),server:($,I)=>Z(`Server error ${I}: ${$}`),http:($,I)=>Z(`HTTP error ${I}: ${$}`),network:($)=>Z(`Network error: ${$}`),unknown:($)=>Z(`Unknown error: ${$}`)}};function gG($){let I=$.assets.map(UQ);return{id:$.id,tag_name:$.tag_name,name:$.name,draft:$.draft,prerelease:$.prerelease,created_at:$.created_at,published_at:$.published_at,assets:I,body:$.body,html_url:$.html_url}}class nG{baseUrl;token;downloader;cache;cacheEnabled;cacheTtlMs;logger;constructor($,I,M,G,J){this.logger=$.getSubLogger({name:"GiteaApiClient"});let Q=I.replace(/\/+$/,"");this.baseUrl=`${Q}/api/v1`,this.token=J?.token,this.downloader=M,this.cache=G,this.cacheEnabled=J?.cacheEnabled??!0,this.cacheTtlMs=J?.cacheTtlMs??300000;let Y=this.logger.getSubLogger({name:"constructor"});if(Y.debug(d.constructor.initialized(this.baseUrl)),this.token)Y.debug(d.constructor.authTokenPresent());else Y.debug(d.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)Y.debug(d.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)Y.debug(d.cache.disabled());else Y.debug(d.cache.missing())}generateCacheKey($,I){let M=`gitea:${I}:${$}`;if(this.token&&typeof this.token==="string"&&this.token.length>0){let G=a9.createHash("sha256").update(this.token).digest("hex").substring(0,8);M+=`:${G}`}return M}async request($,I="GET"){let M=this.logger.getSubLogger({name:"request"}),G=`${this.baseUrl}${$}`,J=this.generateCacheKey($,I),Q=await this.tryGetFromCache(J,I);if(Q)return Q;M.debug(d.request.performing(I,G));let Y=this.buildRequestHeaders();try{let X=await this.performRequest(G,Y);return await this.tryCacheResponse(J,X,I),X}catch(X){return this.handleRequestError(X,G)}}async tryGetFromCache($,I){if(!this.cache||!this.cacheEnabled||I!=="GET")return null;try{let M=await this.cache.get($);if(M)return M}catch{}return null}buildRequestHeaders(){let $={Accept:"application/json"};if(this.token)$.Authorization=`token ${this.token}`;return $}async performRequest($,I){let M=this.logger.getSubLogger({name:"performRequest"}),G=await this.downloader.download(M,$,{headers:I});if(!G||G.length===0)throw M.debug(d.request.emptyResponse($)),new q$(this.logger,"Empty response received from API",$);let J=G.toString("utf-8");return JSON.parse(J)}async tryCacheResponse($,I,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return;try{await this.cache.set($,I,this.cacheTtlMs)}catch{}}handleRequestError($,I){let M=this.logger.getSubLogger({name:"handleRequestError"});if(M.debug(d.errors.requestFailure(I),$),$ instanceof N$)throw M.debug(d.errors.notFound(I)),Error(`Gitea resource not found: ${I}. Status: ${$.statusCode}`);if($ instanceof BI)throw M.debug(d.errors.rateLimit(I)),new g$(`Gitea API rate limit exceeded for ${I}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof vI)throw M.debug(d.errors.forbidden(I)),new g$(`Gitea API request forbidden for ${I}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof PI)throw M.debug(d.errors.client(I,$.statusCode)),new g$(`Gitea API client error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof CI)throw M.debug(d.errors.server(I,$.statusCode)),new g$(`Gitea API server error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof F$)throw M.debug(d.errors.http(I,$.statusCode)),new g$(`Gitea API HTTP error for ${I}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof q$)throw M.debug(d.errors.network(I)),new g$(`Network error while requesting ${I}: ${$.message}`,void 0,$);if(M.debug(d.errors.unknown(I),$),$ instanceof Error)throw new g$(`Unknown error during Gitea API request to ${I}: ${$.message}`,void 0,$);throw new g$(`Unknown error during Gitea API request to ${I}`)}async getLatestRelease($,I){let M=this.logger.getSubLogger({name:"getLatestRelease"});M.debug(d.releases.fetchingLatest($,I));try{let G=await this.request(`/repos/${$}/${I}/releases/latest`);return gG(G)}catch(G){if(G instanceof Error&&G.message.includes("Gitea resource not found"))return M.debug(d.releases.latestNotFound($,I)),null;throw M.debug(d.releases.latestError($,I),G),G}}async getReleaseByTag($,I,M){let G=this.logger.getSubLogger({name:"getReleaseByTag"});G.debug(d.releases.fetchingByTag(M,$,I));try{let J=await this.request(`/repos/${$}/${I}/releases/tags/${M}`);return gG(J)}catch(J){if(J instanceof Error&&J.message.includes("Gitea resource not found"))return G.debug(d.releases.tagNotFound(M,$,I)),null;throw G.debug(d.releases.tagError(M,$,I),J),J}}async getAllReleases($,I,M){let G=this.logger.getSubLogger({name:"getAllReleases"});G.debug(d.releases.fetchingAll($,I));let J=M?.limit||30,Q=M?.maxResults,Y=1,X=[],R=!0;while(R){let W=`/repos/${$}/${I}/releases?limit=${J}&page=${Y}`;G.debug(d.releases.fetchingPage(Y,W));let q=await this.request(W);if(q.length===0)R=!1;else{let U=q.map(gG);if(X=X.concat(U),Y++,q.length<J)R=!1;if(Q!==void 0&&X.length>=Q)X=X.slice(0,Q),R=!1}}if(G.debug(d.releases.totalFetched(X.length,$,I)),M?.includePrerelease===!1){let W=X.filter((q)=>!q.prerelease);return G.debug(d.releases.filteredPrereleases(W.length)),W}return X}async getLatestReleaseTags($,I,M=5){let G=this.logger.getSubLogger({name:"getLatestReleaseTags"});G.debug(d.releases.fetchingLatestTags($,I,M));try{let Q=(await this.request(`/repos/${$}/${I}/releases?limit=${M}`)).map((Y)=>Y.tag_name);return G.debug(d.releases.fetchedTags(Q.length)),Q}catch(J){return G.debug(d.releases.fetchTagsError($,I),J),[]}}}import t9 from"path";var G$={startingInstallation:($)=>Z(`Starting installation: ${$}`),fetchLatest:($)=>Z(`Getting latest release for ${$}`),fetchByTag:($,I)=>Z(`Fetching release ${$} for ${I}`),assetSelectorCustom:()=>Z("Using custom asset selector"),assetPatternMatch:($)=>Z(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,I)=>Z(`Selecting asset for platform ${$} and architecture ${I}`),downloadingAsset:($)=>Z(`Downloading asset: ${$}`),extractingArchive:($)=>Z(`Extracting archive: ${$}`),archiveExtracted:($,I)=>Z(`Archive extracted. fileCount=${$}, executableCount=${I}`),cleaningArchive:($)=>Z(`Cleaning up downloaded archive: ${$}`),versionResolutionResolved:($,I)=>Z(`Resolved version for ${$}: ${I}`),versionResolutionFailed:($,I)=>Z(`Failed to resolve version for ${$}: ${I}`),versionResolutionException:($)=>Z(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>Z(`Failed to check update for ${$}`),availableReleaseTags:()=>Z("Available release tags:"),releaseTagItem:($)=>Z(` - ${$}`),noReleaseTagsAvailable:()=>Z("No release tags available for this repository")};import{minimatch as r9}from"minimatch";function s9($){return/^[dgimsuvy]*$/.test($)}function HQ($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function KQ($){let I=$.lastIndexOf("/");if(I<=0)throw Error('Invalid regex string: missing closing "/"');let M=$.slice(1,I),G=$.slice(I+1);if(!s9(G))throw Error("Invalid regex string: invalid flags");return new RegExp(M,G)}function _Q($){if(!HQ($))return!0;try{return KQ($),!0}catch{return!1}}function OQ($){if(typeof $==="string")return $;return $.toString()}function jQ($,I){if(typeof I==="string"){if(HQ(I))return KQ(I).test($);return r9($,I)}return I.test($)}var o9=5;async function zQ($,I,M,G,J,Q,Y,X,R,W){let q=W.getSubLogger({name:"installFromGiteaRelease"});if(q.debug(G$.startingInstallation($)),!I.installParams||!("repo"in I.installParams))return{success:!1,error:"Repository not specified in installParams"};let U=I.installParams,H=U.repo,K=U.version||"latest",[O,B]=H.split("/");if(!O||!B)return{success:!1,error:`Invalid repository format: ${H}. Expected format: owner/repo`};try{let j=await iG(H,K,U.prerelease??!1,Y,q);if(!j.success)return j;let V=$7(j.data,U,M,q);if(!V.success)return V;let x=V.data.browser_download_url,A=t9.join(M.stagingDir,V.data.name),T=await M7(x,V.data,Q,A,G,q);if(!T.success)return T;let k={...M,downloadPath:T.data.downloadPath},w=await G7(I,k,R,J,q);if(!w.success)return w;let u=j$(j.data.tag_name),h=await J7(V.data,T.data.downloadPath,$,I,M,k,J,X,R,J,q);if(!h.success)return h;let D=h.data,m=D.length>0?D:o(I.binaries,M.stagingDir),e={method:"gitea-release",releaseUrl:j.data.html_url,publishedAt:j.data.published_at,releaseName:j.data.name,instanceUrl:U.instanceUrl,downloadUrl:x,assetName:V.data.name};return{success:!0,binaryPaths:m,version:u,originalTag:j.data.tag_name,metadata:e}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}}async function iG($,I,M,G,J){let Q=J.getSubLogger({name:"fetchGiteaRelease"}),[Y,X]=$.split("/");if(!Y||!X)return{success:!1,error:`Invalid repository format: ${$}. Expected format: owner/repo`};if(I==="latest"){if(Q.debug(G$.fetchLatest($)),M){let K=(await G.getAllReleases(Y,X,{limit:1,includePrerelease:!0,maxResults:1}))[0];if(!K)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:K}}let q=await G.getLatestRelease(Y,X);if(!q)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:q}}Q.debug(G$.fetchByTag(I,$));let R=await G.getReleaseByTag(Y,X,I);if(R)return{success:!0,data:R};return await e9(Y,X,G,Q),{success:!1,error:`Release '${I}' not found for ${$}. Check the available tags above.`}}async function e9($,I,M,G){let J=G.getSubLogger({name:"showAvailableReleaseTags"}),Q=await M.getLatestReleaseTags($,I,o9);if(Q.length===0){J.error(G$.noReleaseTagsAvailable());return}J.info(G$.availableReleaseTags());for(let Y of Q)J.info(G$.releaseTagItem(Y))}function $7($,I,M,G){let J;if(I.assetSelector){G.debug(G$.assetSelectorCustom());let Y={...M,assets:$.assets,release:$,assetPattern:I.assetPattern};J=I.assetSelector(Y)}else if(I.assetPattern){G.debug(G$.assetPatternMatch(OQ(I.assetPattern)));let Y=I.assetPattern,X=$.assets.filter((R)=>jQ(R.name,Y));if(J=VQ(X,M.systemInfo),!J&&X.length>0)J=X[0]}else G.debug(G$.assetPlatformMatch(II(M.systemInfo.platform),MI(M.systemInfo.arch))),J=VQ($.assets,M.systemInfo);if(!J)return{success:!1,error:I7($,I,M)};return{success:!0,data:J}}function VQ($,I){let M=$.map((J)=>J.name),G=z0(M,I);if(!G)return;return $.find((J)=>J.name===G)}function I7($,I,M){let G=$.assets.map((R)=>R.name),J=II(M.systemInfo.platform),Q=MI(M.systemInfo.arch),Y="";if(I.assetSelector)Y=`using a custom assetSelector function for ${J}/${Q}.`;else if(I.assetPattern)Y=`for asset pattern: "${I.assetPattern}" for ${J}/${Q}.`;else Y=`for platform "${J}" and architecture "${Q}".`;return[`No suitable asset found in release "${$.tag_name}" ${Y}`,`Available assets in release "${$.tag_name}":`,...G.map((R)=>` - ${R}`)].join(`
74
+ `)}async function M7($,I,M,G,J,Q){Q.debug(G$.downloadingAsset($));try{return await U$(Q,$,G,I.name,M,J),{success:!0,data:{downloadPath:G}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:String(Y)}}}async function G7($,I,M,G,J){let Q=await y$($,I,M,G,J);if(Q.success)return{success:!0,data:void 0};return{success:!1,error:Q.error||"Hook execution failed"}}async function J7($,I,M,G,J,Q,Y,X,R,W,q){if(uI($.name))return await Q7($,I,M,G,J,Q,Y,X,R,W,q);return await JM(Y,M,G,J,I,q),{success:!0,data:[]}}async function Q7($,I,M,G,J,Q,Y,X,R,W,q){q.debug(G$.extractingArchive($.name));let U=await X.extract(q,I,{targetDir:J.stagingDir});q.debug(G$.archiveExtracted(U.extractedFiles.length,U.executables.length));let H={...Q,extractDir:J.stagingDir,extractResult:U},K=await Y7(G,H,W,R,q);if(!K.success)return{success:!1,error:K.error};let O=await DI(Y,M,G,J,J.stagingDir,q);if(await Y.exists(I))q.debug(G$.cleaningArchive(I)),await Y.rm(I);return{success:!0,data:O}}async function Y7($,I,M,G,J){let Q=await MM($,I,G,M,J);if(Q.success)return{success:!0,data:void 0};return{success:!1,error:Q.error||"Hook execution failed"}}import{z as RI}from"zod";var D0=s.extend({instanceUrl:RI.string().url("instanceUrl must be a valid URL"),repo:RI.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:RI.union([RI.string().refine(_Q,"assetPattern must be a valid glob or a regex string like /.../"),RI.instanceof(RegExp)]).optional(),version:RI.string().optional(),assetSelector:RI.custom(($)=>typeof $==="function","Must be a function").optional(),prerelease:RI.boolean().optional(),token:RI.string().optional()});import{z as A0}from"zod";var BQ=t.extend({installationMethod:A0.literal("gitea-release"),installParams:D0,binaries:A0.array(A0.union([A0.string().min(1),X$])).min(1)});class lG{fs;downloader;archiveExtractor;hookExecutor;cache;method="gitea-release";displayName="Gitea Release";version="1.0.0";paramsSchema=D0;toolConfigSchema=BQ;constructor($,I,M,G,J){this.fs=$;this.downloader=I;this.archiveExtractor=M;this.hookExecutor=G;this.cache=J}createApiClient($,I){let M=$.installParams;return new nG(I,M.instanceUrl,this.downloader,this.cache,{token:M.token})}async install($,I,M,G,J){let Q=R$(this.fs,$),Y=this.createApiClient(I,J);return await zQ($,I,M,G,Q,this.downloader,Y,this.archiveExtractor,this.hookExecutor,J)}async resolveVersion($,I,M,G){try{let J=I.installParams,Q=I.version||"latest",Y=this.createApiClient(I,G),X=await iG(J.repo,Q,J.prerelease??!1,Y,G);if(!X.success)return G.debug(G$.versionResolutionFailed($,X.error)),null;let R=FI(X.data.tag_name);return G.debug(G$.versionResolutionResolved($,R)),R}catch(J){return G.debug(G$.versionResolutionException($),J),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,I,M,G){try{let Q=I.installParams.repo,[Y,X]=Q.split("/");if(!Y||!X)return{success:!1,error:`Invalid repo format: ${Q}. Expected owner/repo`};let W=await this.createApiClient(I,G).getLatestRelease(Y,X);if(!W||!W.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let q=I.version||"latest",U=W.tag_name.replace(/^v/,"");if(q==="latest")return{success:!0,hasUpdate:!1,currentVersion:U,latestVersion:U};return{success:!0,hasUpdate:q!==U,currentVersion:q,latestVersion:U}}catch(J){return G.error(G$.updateCheckFailed($),J),{success:!1,error:J instanceof Error?J.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,I){let M=I.installParams,G=M.repo,[J,Q]=G.split("/");if(!J||!Q)return null;let Y=M.instanceUrl.replace(/\/+$/,""),X=I.version||"main";return`${Y}/${J}/${Q}/raw/branch/${X}/README.md`}}import xQ from"path";var aG={installing:($)=>Z(`Manual installation: toolName=${$}`),manualInstructions:()=>Z("Manual installation requires user action"),multipleBinariesNotSupported:()=>Z("Manual installation does not support multiple binaries")};async function DQ($,I,M,G,J,Q){let Y=R$(J,$),X=Q.getSubLogger({name:"installManually"});X.debug(aG.installing($));let R=I.installParams;return J$("manual",$,X,async()=>{let q=[];if(R?.binaryPath){let H=w$(I.configFilePath,R.binaryPath,M.projectConfig,M.systemInfo);if(!await Y.exists(H))return{success:!1,error:`Binary not found at ${H}`};await X7(I,$,M,Y,H,X),q=o(I.binaries,M.stagingDir)}return{success:!0,binaryPaths:q,metadata:{method:"manual",manualInstall:!0}}})}async function X7($,I,M,G,J,Q){let Y=Q.getSubLogger({name:"installBinariesManually"}),X=GM($.binaries);for(let R of X){let W=xQ.join(M.stagingDir,R);if(R===I||X.length===1)await G.ensureDir(xQ.dirname(W)),await G.copyFile(J,W),await G.chmod(W,493);else Y.debug(aG.multipleBinariesNotSupported())}}import{z as Z7}from"zod";var F0=s.extend({binaryPath:Z7.string().min(1).optional()});import{z as L0}from"zod";var AQ=t.extend({installationMethod:L0.literal("manual"),installParams:F0.optional(),binaries:L0.array(L0.union([L0.string().min(1),X$])).optional()});var R7="1.0.0";class rG{fs;method="manual";displayName="Manual Installer";version=R7;paramsSchema=F0;toolConfigSchema=AQ;constructor($){this.fs=$}async install($,I,M,G,J){let Q=await DQ($,I,M,G,this.fs,J);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,metadata:Q.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function W7($,I){if(I.platform===0)return!1;if(!oI($.platforms,I.platform))return!1;if($.architectures!==void 0){if(I.arch===0)return!1;if(!eI($.architectures,I.arch))return!1}return!0}function sG($){return{...$,scripts:$.scripts?[...$.scripts]:void 0,functions:$.functions?{...$.functions}:void 0,paths:$.paths?[...$.paths]:void 0}}function q7($){if(!$)return;return{zsh:$.zsh?sG($.zsh):void 0,bash:$.bash?sG($.bash):void 0,powershell:$.powershell?sG($.powershell):void 0}}function U7($){if(!$.shellConfigs)$.shellConfigs={zsh:void 0,bash:void 0,powershell:void 0}}function tG($,I,M){if(!M)return;let G=$[I];if(!G)G={},$[I]=G;if(M.scripts)G.scripts=[...G.scripts||[],...M.scripts];if(M.completions)G.completions=M.completions;if(M.aliases)G.aliases={...G.aliases,...M.aliases};if(M.env)G.env={...G.env,...M.env};if(M.functions)G.functions={...G.functions,...M.functions};if(M.paths)G.paths=[...G.paths||[],...M.paths]}function H7($,I){if(!I)return;U7($);let M=$.shellConfigs;if(!M)return;tG(M,"zsh",I.zsh),tG(M,"bash",I.bash),tG(M,"powershell",I.powershell)}function K7($,I){if(I.binaries!==void 0)$.binaries=I.binaries;if(I.dependencies!==void 0)$.dependencies=I.dependencies;if(I.version!==void 0)$.version=I.version;if(I.updateCheck!==void 0)$.updateCheck=I.updateCheck;if(I.installationMethod!==void 0)$.installationMethod=I.installationMethod;if(I.installParams!==void 0){let M=$.installParams?.hooks,G=I.installParams.hooks;if($.installParams={...$.installParams,...I.installParams},M||G){if($.installParams.hooks={...M,...G},M&&G){for(let J of Object.keys(M))if(J in G)$.installParams.hooks[J]=[...M[J]??[],...G[J]??[]]}}}}function _7($){let I={...$,shellConfigs:q7($.shellConfigs),dependencies:$.dependencies?[...$.dependencies]:void 0},{platformConfigs:M,...G}=I;return G}function I$($,I){if(!$.platformConfigs||$.platformConfigs.length===0)return $;let M=$.platformConfigs.filter((J)=>W7(J,I));if(M.length===0){let{platformConfigs:J,...Q}=$;return Q}let G=_7($);for(let J of M){let Q=J.config;if(H7(G,Q.shellConfigs),Q.symlinks)G.symlinks=[...G.symlinks||[],...Q.symlinks];if(Q.copies)G.copies=[...G.copies||[],...Q.copies];K7(G,Q)}return G}import FQ from"path";function E0($,I){let M=I.trim();if(FQ.isAbsolute(M))return M;return FQ.resolve($,M)}function FI($){if(!$)return $;if($.startsWith("v")||$.startsWith("V"))return $.slice(1);return $}import{randomUUID as O7}from"crypto";import{basename as LQ,extname as j7,join as TM}from"path";var WI={shellCommandStarted:($)=>Z(`Executing shell command: ${$}`),shellCommandFailed:($,I)=>Z(`Shell command failed (exit ${I??"unknown"}): ${$}`),fileCommandFallbackFailed:($)=>Z(`Failed to detect archive format using file command: ${$}`),extractionRequested:($)=>Z(`Extracting archive ${$}`),executableFlagApplied:($)=>Z(`Marked file as executable: ${$}`),executableCheckFailed:($)=>Z(`Failed to inspect file for executable permissions: ${$}`)};class oG{fs;logger;shell;constructor($,I,M){this.fs=I,this.logger=$.getSubLogger({name:"ArchiveExtractor"}),this.shell=M}detectFormatByExtension($){let I=$.toLowerCase();if(I.endsWith(".tar.gz")||I.endsWith(".tgz"))return"tar.gz";if(I.endsWith(".gz"))return"gzip";if(I.endsWith(".tar.bz2")||I.endsWith(".tbz2")||I.endsWith(".tbz"))return"tar.bz2";if(I.endsWith(".tar.xz")||I.endsWith(".txz"))return"tar.xz";if(I.endsWith(".tar.lzma"))return"tar.lzma";if(I.endsWith(".tar"))return"tar";if(I.endsWith(".zip"))return"zip";if(I.endsWith(".rar"))return"rar";if(I.endsWith(".7z"))return"7z";if(I.endsWith(".deb"))return"deb";if(I.endsWith(".rpm"))return"rpm";if(I.endsWith(".dmg"))return"dmg";return null}detectFormatByMimeType($){if($.includes("gzip"))return"tar.gz";if($.includes("zip"))return"zip";if($.includes("x-bzip2"))return"tar.bz2";if($.includes("x-xz"))return"tar.xz";if($.includes("x-tar"))return"tar";if($.includes("x-7z-compressed"))return"7z";if($.includes("x-rar-compressed"))return"rar";if($.includes("x-debian-package"))return"deb";if($.includes("x-rpm"))return"rpm";if($.includes("x-apple-diskimage"))return"dmg";return null}async detectFormatUsingFileCommand($,I){try{I.debug(WI.shellCommandStarted("file"));let J=(await this.shell`file -b --mime-type ${$}`.quiet()).stdout.trim();return this.detectFormatByMimeType(J)}catch(M){return I.debug(WI.fileCommandFallbackFailed($),M),null}}async detectFormat($){let I=this.logger.getSubLogger({name:"detectFormat"}),M=LQ($),G=this.detectFormatByExtension(M);if(G)return G;let J=await this.detectFormatUsingFileCommand($,I);if(J)return J;throw Error(`Unsupported or undetectable archive format for: ${$}`)}isSupported($){return["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"].includes($)}getTarFlagForFormat($){switch($){case"tar.gz":return"-xzf";case"tar.bz2":return"-xjf";case"tar.xz":return"-xJf";case"tar":return"-xf";default:throw Error(`Unsupported tar format: ${$}`)}}async extractArchiveByFormat($,I,M){switch($){case"tar.gz":case"tar.bz2":case"tar.xz":case"tar":{let G=this.getTarFlagForFormat($),J="tar";this.logger.debug(WI.shellCommandStarted("tar")),await this.shell`tar ${G} ${I} -C ${M}`.quiet();break}case"zip":{this.logger.debug(WI.shellCommandStarted("unzip")),await this.shell`unzip -qo ${I} -d ${M}`.quiet();break}case"gzip":{this.logger.debug(WI.shellCommandStarted("gunzip"));let J=LQ(I),Q=J.endsWith(".gz")?J.slice(0,-3):J,Y=TM(M,Q);await this.shell`gunzip -c ${I} > ${Y}`.quiet();break}default:throw Error(`Extraction for format ${$} not implemented.`)}}async extract($,I,M={}){let G=$.getSubLogger({name:"extract"}),{format:J,targetDir:Q=".",detectExecutables:Y=!0}=M;G.debug(WI.extractionRequested(I),M);let X=J||await this.detectFormat(I);if(!this.isSupported(X))throw Error(`Unsupported archive format: ${X}`);await this.fs.ensureDir(Q);let R=O7(),W=TM(Q,`.extract-temp-${R}`);await this.fs.ensureDir(W);try{await this.extractArchiveByFormat(X,I,W);let q=await yI(this.fs,W);for(let K of q){let O=K.substring(W.length+1),B=TM(Q,O),j=TM(B,"..");await this.fs.ensureDir(j),await this.fs.rename(K,B)}await this.fs.rm(W,{recursive:!0,force:!0});let U=q.map((K)=>{let O=K.substring(W.length+1);return TM(Q,O)}),H={extractedFiles:U,executables:[]};if(Y)H.executables=await this.detectAndSetExecutables(U);return H}catch(q){try{await this.fs.rm(W,{recursive:!0,force:!0})}catch{}throw q}}async detectAndSetExecutables($){let I=this.logger.getSubLogger({name:"detectAndSetExecutables"}),M=[];for(let G of $)try{let J=await this.fs.stat(G);if(J.isFile()){let Q=j7(G);if(Q===""||[".sh",".py",".pl",".rb"].includes(Q)){if(!(J.mode&64))I.debug(WI.executableFlagApplied(G)),await this.fs.chmod(G,J.mode|64);M.push(G)}}}catch(J){I.debug(WI.executableCheckFailed(G),J)}return M}}var V7=["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"];function z7($){let I=$.toLowerCase();if(I.endsWith(".tar.gz")||I.endsWith(".tgz"))return"tar.gz";if(I.endsWith(".tar.bz2")||I.endsWith(".tbz2")||I.endsWith(".tbz"))return"tar.bz2";if(I.endsWith(".tar.xz")||I.endsWith(".txz"))return"tar.xz";if(I.endsWith(".tar.lzma"))return"tar.lzma";if(I.endsWith(".tar"))return"tar";if(I.endsWith(".gz"))return"gzip";if(I.endsWith(".zip"))return"zip";if(I.endsWith(".rar"))return"rar";if(I.endsWith(".7z"))return"7z";if(I.endsWith(".deb"))return"deb";if(I.endsWith(".rpm"))return"rpm";if(I.endsWith(".dmg"))return"dmg";return null}function uI($){let I=z7($);if(!I)return!1;return V7.includes(I)}var EI={configurationFieldIgnored:($,I)=>Z(`Configuration field "${$}" ignored: ${I}`),configurationFieldRequired:($,I)=>Z(`Required configuration missing: ${$}${I?`. Example: ${I}`:""}`),configurationFieldInvalid:($,I,M)=>Z(`Invalid ${$}: "${I}" (expected ${M})`),invalidFunctionName:($)=>Z(`Invalid function name: "${$}"`)};import eG from"path";var x$={generationStarted:($,I)=>Z(`Starting completion generation for "${$}" (shell: ${I})`),generationComplete:($,I,M)=>Z(`Generated completion ${$} for ${I} (${M})`),commandExecutionStarted:($,I,M)=>Z(`Executing completion command for "${$}" (shell: ${M}): ${I}`),commandExecutionFailed:($,I,M,G)=>Z(`Completion command failed for "${$}" [${I}] exit ${M}: ${G}`),commandExecutionCompleted:($,I)=>Z(`Completion command succeeded for "${$}" (shell: ${I})`),symlinkCreated:($,I)=>Z(`Symlinked completion: ${$} -> ${I}`),sourceNotFound:($)=>Z(`Completion source file not found: ${$}`),downloadingCompletion:($)=>Z(`Downloading completion from: ${$}`),completionDownloaded:($)=>Z(`Completion downloaded to: ${$}`),completionAlreadyDownloaded:($)=>Z(`Completion already downloaded: ${$}`),extractingCompletionArchive:($)=>Z(`Extracting completion archive: ${$}`),completionArchiveExtracted:($)=>Z(`Completion archive extracted to: ${$}`)};class SM{logger;shell;constructor($,I){this.logger=$.getSubLogger({name:"CompletionCommandExecutor"}),this.shell=I}async executeCompletionCommand($,I,M,G,J){let Q=this.logger.getSubLogger({name:"executeCompletionCommand"}).setPrefix(I);Q.debug(x$.commandExecutionStarted(I,$,M));let Y=J?.map((W)=>eG.dirname(W))??[],X=[...new Set([...Y,G])],R=X.join(eG.delimiter);if(J&&J.length>0){let W=[...new Set(J.map((U)=>eG.basename(U)))];if(!await this.checkAnyBinaryExistsInPath(W,R)){let U=X.join(", ");throw Error(`None of the expected binaries (${W.join(", ")}) found in: ${U}. Skipping completion generation to prevent infinite loop.`)}}try{let W=`cd ${G} && PATH=${R}:$PATH ${$}`,q=await this.shell`sh -c ${W}`.quiet();return Q.debug(x$.commandExecutionCompleted(I,M)),q.stdout}catch(W){let q=W&&typeof W==="object"&&"exitCode"in W?W.exitCode:-1,U=W&&typeof W==="object"&&"stderr"in W?W.stderr.toString():"Unknown error",H=`Completion command failed for ${I}: ${$}`;throw Q.error(x$.commandExecutionFailed(I,$,q,U)),Error(`${H}
75
+ Exit code: ${q}
76
+ Stderr: ${U}`,{cause:W})}}async checkAnyBinaryExistsInPath($,I){for(let M of $)try{let G=`PATH=${I} command -v ${M}`;return await this.shell`sh -c ${G}`.quiet(),!0}catch{}return!1}}import{minimatch as B7}from"minimatch";import P$ from"path";var x7=["tar.gz","tar.xz","tar.bz2","zip","tar","tar.lzma","7z"];class $6{logger;commandExecutor;fs;downloader;archiveExtractor;constructor($,I,M,G,J){this.logger=$.getSubLogger({name:"CompletionGenerator"}),this.fs=I,this.commandExecutor=G||new SM(this.logger,M),this.downloader=J?.downloader,this.archiveExtractor=J?.archiveExtractor}async prepareUrlCompletionSource($,I,M){if(!$.url)throw Error(`URL not provided for ${I}`);await this.downloadCompletionFromUrl($.url,M.toolInstallDir,I);let G=$.source||this.getFilenameFromUrl($.url),J=P$.isAbsolute(G)?G:P$.join(M.toolInstallDir,G);if(!await this.fs.exists(J))throw this.logger.warn(x$.sourceNotFound(J)),Error(`Completion source file not found: ${J}`);return J}async generateCompletionFile($,I,M,G){this.logger.getSubLogger({name:"generateCompletionFile"}).setPrefix(I).debug(x$.generationStarted(I,M));let Q=$.url?await this.prepareUrlCompletionSource($,I,G):$.source;if($.cmd)return this.generateFromCommand($,I,M,G);if(Q){let Y={...$,source:Q};return this.generateFromSource(Y,I,M,G)}throw Error(`Invalid completion config for ${I}: either 'cmd', 'source', or 'url' must be provided`)}async downloadCompletionFromUrl($,I,M){let G=this.logger.getSubLogger({name:"downloadCompletionFromUrl"}).setPrefix(M);if(!this.downloader)throw Error("Downloader not provided - cannot download completion from URL");G.info(x$.downloadingCompletion($)),await this.fs.ensureDir(I);let J=this.getFilenameFromUrl($),Q=P$.join(I,J);if(await this.fs.exists(Q)){G.debug(x$.completionAlreadyDownloaded(Q));return}if(await this.downloader.downloadToFile(G,$,Q),G.debug(x$.completionDownloaded(Q)),this.detectArchiveFormat(J))await this.extractCompletionArchive(Q,I,M)}async extractCompletionArchive($,I,M){let G=this.logger.getSubLogger({name:"extractCompletionArchive"}).setPrefix(M);if(!this.archiveExtractor)throw Error("Archive extractor not provided - cannot extract completion archive");G.debug(x$.extractingCompletionArchive($)),await this.archiveExtractor.extract(G,$,{targetDir:I}),G.debug(x$.completionArchiveExtracted(I))}getFilenameFromUrl($){let M=new URL($).pathname;return P$.basename(M)||"completion-download"}detectArchiveFormat($){let I=$.toLowerCase();for(let M of x7)if(I.endsWith(`.${M}`))return M;return null}async generateAndWriteCompletionFile($){let{config:I,toolName:M,shellType:G,context:J,fs:Q}=$,Y=await this.generateCompletionFile(I,M,G,J);if(await Q.ensureDir(P$.dirname(Y.targetPath)),Y.generatedBy==="source"&&Y.sourcePath){if(await Q.exists(Y.targetPath))await Q.rm(Y.targetPath);await Q.symlink(Y.sourcePath,Y.targetPath),this.logger.debug(x$.symlinkCreated(Y.sourcePath,Y.targetPath))}else await Q.writeFile(Y.targetPath,Y.content);return Y}async generateFromCommand($,I,M,G){if(!$.cmd)throw Error(`Command not provided for ${I}`);let J=await this.commandExecutor.executeCompletionCommand($.cmd,I,M,G.toolInstallDir,G.binaryPaths),Q=this.generateCompletionFilename($,I,M),Y=this.resolveTargetPath(M,G);return{content:J,filename:Q,targetPath:P$.join(Y,Q),generatedBy:"command"}}async generateFromSource($,I,M,G){if(!$.source)throw Error(`Source not provided for ${I}`);let J=await this.resolveSourcePath($.source,G.configFilePath);if(!await this.fs.exists(J))throw this.logger.warn(x$.sourceNotFound(J)),Error(`Completion source file not found: ${J}`);let Q=this.generateCompletionFilename($,I,M),Y=this.resolveTargetPath(M,G);return{content:"",filename:Q,targetPath:P$.join(Y,Q),generatedBy:"source",sourcePath:J}}async resolveSourcePath($,I){if(P$.isAbsolute($))return $;let M=I?P$.dirname(I):void 0;if(!M)throw Error(`Cannot resolve relative path '${$}' without configFilePath`);if($.includes("*")||$.includes("?")||$.includes("[")){let J=(await yI(this.fs,M,M)).find((Q)=>B7(Q,$));if(J)return P$.join(M,J);throw Error(`No files matching pattern '${$}' found in toolDir: ${M}`)}return E0(M,$)}generateCompletionFilename($,I,M){let G=$.bin??I;switch(M){case"zsh":return`_${G}`;case"bash":return`${G}.bash`;case"powershell":return`${G}.ps1`;default:return`${G}.${M}`}}resolveTargetPath($,I){return P$.join(I.shellScriptsDir,$,"completions")}}var EQ=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;class WM{headerWidth;indentSize;onceScriptDir;constructor($){this.headerWidth=$.headerWidth??80,this.indentSize=$.indentSize??2,this.onceScriptDir=$.onceScriptDir}comment($){return`# ${$}`}commentBlock($){return $.map((I)=>this.comment(I)).join(`
77
+ `)}formatFileHeader($){let I=[this.headerLine("="),this.comment("THIS FILE IS AUTOMATICALLY GENERATED BY THE DOTFILES MANAGEMENT TOOL"),this.comment("DO NOT EDIT THIS FILE DIRECTLY - YOUR CHANGES WILL BE OVERWRITTEN"),this.headerLine("="),""];if($?.sourceFile)I.push(this.comment(`Dotfiles directory: ${$.sourceFile}`)),I.push("");return I.join(`
78
+ `)}formatSectionHeader($){return this.headerLine("=",$)}formatChildBlockHeader($){return this.headerLine("=")}formatFileFooter(){return this.headerLine("=","End of Generated File")}headerLine($,I){let M=this.headerWidth;if(!I)return this.comment($.repeat(M-2));let G=` ${I} `,J=Math.max(0,M-1-G.length),Q=$.repeat(Math.floor(J/2)),Y=$.repeat(Math.ceil(J/2));return this.comment(`${Q}${G}${Y}`)}generateSourceFunctionName($){return`__source_${$.replace(/[^a-zA-Z0-9]/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}`}}class qM extends WM{generateOnceScriptContent($,I){let M=["# Generated once script - will self-delete after execution"];return M.push($),M.push(`rm "${I}"`),M.join(`
79
+ `)}}class TI extends Error{blockId;constructor($,I){super(`Block "${$}": ${I}`);this.blockId=$;this.name="BlockValidationError"}}class qI extends Error{emissionKind;field;constructor($,I,M){super(`${$}.${I}: ${M}`);this.emissionKind=$;this.field=I;this.name="EmissionValidationError"}}var TQ=/^[a-zA-Z_][a-zA-Z0-9_]*$/,SQ=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;function D7($,I,M){if(!TQ.test(M))throw new qI($,I,`"${M}" is not a valid identifier (must match ${TQ.source})`)}function I6($,I,M){if(!SQ.test(M))throw new qI($,I,`"${M}" is not a valid name (must match ${SQ.source})`)}function T0($,I,M){if(M.trim().length===0)throw new qI($,I,"cannot be empty")}function kQ($,I,M){if(Object.keys(M).length===0)throw new qI($,I,"must have at least one entry")}function wQ($){kQ("environment","variables",$);for(let I of Object.keys($))D7("environment",`variables.${I}`,I)}function bQ($){kQ("alias","aliases",$);for(let I of Object.keys($))I6("alias",`aliases.${I}`,I)}function kM($){return wQ($),{kind:"environment",variables:$}}function wM($){return bQ($),{kind:"alias",aliases:$}}function UM($,I){return I6("function","name",$),T0("function","body",I),{kind:"function",name:$,body:I}}function UI($,I){return T0("script","content",$),{kind:"script",content:$,timing:I}}function bM($){let I=$.directories&&$.directories.length>0,M=$.files&&$.files.length>0,G=$.commands&&$.commands.length>0;if(!I&&!M&&!G)throw new qI("completion","config","at least one of directories, files, or commands must be provided");return{kind:"completion",directories:$.directories,files:$.files,commands:$.commands}}function S0($,I){return T0("path","directory",$),{kind:"path",directory:$,position:I?.position??"prepend",deduplicate:I?.deduplicate??!0}}function T$($,I){return{...$,source:I}}function M6($,I){return{...$,priority:I}}function pI($){return $.kind==="environment"}function cI($){return $.kind==="alias"}function hI($){return $.kind==="function"}function n$($){return $.kind==="script"}function mI($){return $.kind==="sourceFile"}function gI($){return $.kind==="source"}function nI($){return $.kind==="sourceFunction"}function HI($){return $.kind==="completion"}function iI($){return $.kind==="path"}var A7=new Set(["environment","path","completion"]);function G6($){return A7.has($.kind)}class k0{sections=new Map;sectionOrder=[];addSection($,I){if(this.sections.has($))throw new TI($,"section already exists");if(I.priority<0)throw new TI($,"priority must be non-negative");return this.sections.set($,{id:$,options:I,emissions:[],children:new Map,childInsertionOrder:[]}),this.sectionOrder.push($),this}addEmission($,I){if(G6($))this.addHoistedEmission($);else this.addNonHoistedEmission($,I);return this}addEmissionToSection($,I){let M=this.sections.get(I);if(!M)throw new TI(I,"section does not exist");return M.emissions.push($),this}build(){let $=[];for(let I of this.sectionOrder){let M=this.sections.get(I);if(!M)continue;let G=this.buildBlock(M);$.push(G)}return $.toSorted((I,M)=>I.priority-M.priority)}addHoistedEmission($){let I=this.findHoistTarget($.kind);if(!I)throw new TI("unknown",`no section accepts hoisted emission kind "${$.kind}"`);I.emissions.push($)}addNonHoistedEmission($,I){let M=this.findChildrenSection();if(!M)throw new TI("unknown","no section allows children for non-hoisted emissions");if(I){let G=M.children.get(I);if(!G)G={id:I,emissions:[],sourceFile:$.source},M.children.set(I,G),M.childInsertionOrder.push(I);G.emissions.push($)}else M.emissions.push($)}findHoistTarget($){for(let I of this.sections.values())if(I.options.hoistKinds?.includes($))return I;return}findChildrenSection(){for(let $ of this.sections.values())if($.options.allowChildren)return $;return}buildBlock($){let M=this.deduplicateCompletions($.emissions).toSorted((J,Q)=>(J.priority??0)-(Q.priority??0)),G=[];for(let J of $.childInsertionOrder){let Q=$.children.get(J);if(!Q)continue;let Y=Q.emissions.toSorted((X,R)=>(X.priority??0)-(R.priority??0));G.push({id:Q.id,title:Q.id,priority:G.length,emissions:Y,metadata:Q.sourceFile?{sourceFile:Q.sourceFile}:void 0})}return{id:$.id,title:$.options.title,priority:$.options.priority,emissions:M,children:G.length>0?G:void 0,metadata:$.options.metadata,isFileHeader:$.options.isFileHeader,isFileFooter:$.options.isFileFooter}}deduplicateCompletions($){let I=[],M=[];for(let R of $)if(HI(R))I.push(R);else M.push(R);if(I.length<=1)return $;let G=new Set,J=new Set,Q=new Set,Y;for(let R of I){if(R.directories)for(let W of R.directories)G.add(W);if(R.files)for(let W of R.files)J.add(W);if(R.commands)for(let W of R.commands)Q.add(W);if(R.priority!==void 0)Y=Y===void 0?R.priority:Math.min(Y,R.priority)}let X={kind:"completion",directories:G.size>0?[...G]:void 0,files:J.size>0?[...J]:void 0,commands:Q.size>0?[...Q]:void 0,priority:Y};return[...M,X]}}var NQ=1,lI=3;class w0{render($,I){let M=$.toSorted((R,W)=>R.priority-W.priority),G=[],J=[],Q=NQ,Y=[];for(let R of M)this.collectOnceScripts(R,Y);let X=-1;if(Y.length>0)for(let R=M.length-1;R>=0;R--){let W=M[R];if(W&&W.priority<400){X=R;break}}for(let[R,W]of M.entries()){let q=this.renderBlock(W,I,J,Q);if(q.length>0){if(G.length>0)G.push("");G.push(...q)}if(Q=J.length+1,R===X&&Y.length>0)G.push(""),G.push(I.formatOnceScriptInitializer())}return{content:G.join(`
80
+ `),fileExtension:I.fileExtension,onceScripts:J}}collectOnceScripts($,I){for(let M of $.emissions)if(n$(M)&&M.timing==="once")I.push({emission:M,blockPriority:$.priority});for(let M of $.children??[])this.collectOnceScripts(M,I)}renderBlock($,I,M,G){let J=[],Q=G;if($.isFileHeader)return J.push(I.formatFileHeader($.metadata)),J;if($.isFileFooter)return J.push(I.formatFileFooter()),J;let Y=$.emissions.length>0,X=($.children?.length??0)>0;if(!Y&&!X)return J;if($.title)J.push(I.formatSectionHeader($.title));let R;for(let W of $.emissions){if(W.source&&W.source!==R)J.push(I.comment(W.source)),R=W.source;if(n$(W)&&W.timing==="once"){let q=I.formatOnceScript(W,Q);M.push({filename:q.filename,content:q.content,executable:!0}),Q++}else J.push(I.formatEmission(W))}for(let W of $.children??[]){if(W.emissions.length===0)continue;J.push(""),J.push(I.formatChildBlockHeader(W));let q;for(let U of W.emissions){if(U.source&&U.source!==q)J.push(I.comment(U.source)),q=U.source;if(n$(U)&&U.timing==="once"){let H=I.formatOnceScript(U,Q);M.push({filename:H.filename,content:H.content,executable:!0}),Q++}else J.push(I.formatEmission(U))}}return J}}class b0 extends qM{fileExtension=".bash";formatEmission($){if(pI($))return this.formatEnvironment($);if(cI($))return this.formatAlias($);if(hI($))return this.formatFunction($);if(n$($))return this.formatScript($);if(gI($))return this.formatSource($);if(mI($))return this.formatSourceFile($);if(nI($))return this.formatSourceFunction($);if(HI($))return this.formatCompletion($);if(iI($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,I){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let G=`once-${I.toString().padStart(lI,"0")}.bash`,J=`${this.onceScriptDir}/${G}`,Q=c($.content);return{content:this.generateOnceScriptContent(Q,J),filename:G}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
81
81
  # Execute once scripts (runs only once per script)
82
82
  shopt -s nullglob
83
83
  for once_script in "${this.onceScriptDir}"/*.bash; do
84
84
  [[ -f "$once_script" ]] && source "$once_script"
85
85
  done
86
86
  shopt -u nullglob
87
- `)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`export ${J}=${JSON.stringify(Q)}`);return M.join(`
88
- `)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`alias ${J}='${Q.replace(/'/g,"'\\''")}'`);return M.join(`
89
- `)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
90
- `).map((Y)=>`${J}${Y}`).join(`
91
- `);return[`${$.name}() {`,Q,"}"].join(`
92
- `)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
93
- `).map((G)=>`${Q}${G}`).join(`
94
- `);return[`${J}() {`,Y,"}",`source <(${J})`,`unset -f ${J}`].join(`
95
- `)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let M=[];if($.files)for(let J of $.files)M.push(`[[ -f "${J}" ]] && source "${J}"`);return M.join(`
96
- `)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="${M}:$PATH"`,"fi"].join(`
97
- `);return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="$PATH:${M}"`,"fi"].join(`
98
- `)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}class wJ extends Z0{fileExtension=".ps1";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.ps1`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
87
+ `)}formatEnvironment($){let I=[];for(let[M,G]of Object.entries($.variables))I.push(`export ${M}=${JSON.stringify(G)}`);return I.join(`
88
+ `)}formatAlias($){let I=[];for(let[M,G]of Object.entries($.aliases))I.push(`alias ${M}='${G.replace(/'/g,"'\\''")}'`);return I.join(`
89
+ `)}formatFunction($){let I=c($.body),M=" ".repeat(this.indentSize),G=I.split(`
90
+ `).map((J)=>`${M}${J}`).join(`
91
+ `);return[`${$.name}() {`,G,"}"].join(`
92
+ `)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let I=c($.content),M=$.functionName,G=" ".repeat(this.indentSize),J=I.split(`
93
+ `).map((Q)=>`${G}${Q}`).join(`
94
+ `);return[`${M}() {`,J,"}",`source <(${M})`,`unset -f ${M}`].join(`
95
+ `)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let I=[];if($.files)for(let M of $.files)I.push(`[[ -f "${M}" ]] && source "${M}"`);return I.join(`
96
+ `)}formatPath($){let I=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${I}:"* ]]; then`,` export PATH="${I}:$PATH"`,"fi"].join(`
97
+ `);return[`if [[ ":$PATH:" != *":${I}:"* ]]; then`,` export PATH="$PATH:${I}"`,"fi"].join(`
98
+ `)}if($.position==="prepend")return`export PATH="${I}:$PATH"`;return`export PATH="$PATH:${I}"`}}class N0 extends WM{fileExtension=".ps1";formatEmission($){if(pI($))return this.formatEnvironment($);if(cI($))return this.formatAlias($);if(hI($))return this.formatFunction($);if(n$($))return this.formatScript($);if(gI($))return this.formatSource($);if(mI($))return this.formatSourceFile($);if(nI($))return this.formatSourceFunction($);if(HI($))return this.formatCompletion($);if(iI($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,I){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let G=`once-${I.toString().padStart(lI,"0")}.ps1`,J=`${this.onceScriptDir}/${G}`,Q=c($.content);return{content:this.generateOnceScriptContent(Q,J),filename:G}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
99
99
  # Execute once scripts (runs only once per script)
100
100
  Get-ChildItem -Path "${this.onceScriptDir}/*.ps1" -ErrorAction SilentlyContinue | ForEach-Object {
101
101
  if (Test-Path $_.FullName) {
102
102
  & $_.FullName
103
103
  }
104
104
  }
105
- `)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`$env:${J} = ${JSON.stringify(Q)}`);return M.join(`
106
- `)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`Set-Alias -Name ${J} -Value '${Q.replace(/'/g,"''")}'`);return M.join(`
107
- `)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
108
- `).map((Y)=>`${J}${Y}`).join(`
109
- `);return[`function ${$.name} {`,Q,"}"].join(`
110
- `)}formatScript($){return c($.content)}formatSourceFile($){return`. "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
111
- `).map((G)=>`${Q}${G}`).join(`
112
- `);return[`function ${J} {`,Y,"}",`Invoke-Expression (& ${J})`,`Remove-Item Function:\\${J} -ErrorAction SilentlyContinue`].join(`
113
- `)}formatSourceFunction($){return`Invoke-Expression (& ${$.functionName})`}formatCompletion($){let M=[];if($.files)for(let J of $.files)M.push(`if (Test-Path "${J}") { . "${J}" }`);return M.join(`
114
- `)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return`if ($env:PATH -notlike "*${M}*") { $env:PATH = "${M};$env:PATH" }`;return`if ($env:PATH -notlike "*${M}*") { $env:PATH = "$env:PATH;${M}" }`}if($.position==="prepend")return`$env:PATH = "${M};$env:PATH"`;return`$env:PATH = "$env:PATH;${M}"`}generateOnceScriptContent($,M){let J=["# Generated once script - will self-delete after execution"];return J.push($),J.push(`Remove-Item "${M}"`),J.join(`
115
- `)}}class bJ extends W0{fileExtension=".zsh";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.zsh`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
105
+ `)}formatEnvironment($){let I=[];for(let[M,G]of Object.entries($.variables))I.push(`$env:${M} = ${JSON.stringify(G)}`);return I.join(`
106
+ `)}formatAlias($){let I=[];for(let[M,G]of Object.entries($.aliases))I.push(`Set-Alias -Name ${M} -Value '${G.replace(/'/g,"''")}'`);return I.join(`
107
+ `)}formatFunction($){let I=c($.body),M=" ".repeat(this.indentSize),G=I.split(`
108
+ `).map((J)=>`${M}${J}`).join(`
109
+ `);return[`function ${$.name} {`,G,"}"].join(`
110
+ `)}formatScript($){return c($.content)}formatSourceFile($){return`. "${$.path}"`}formatSource($){let I=c($.content),M=$.functionName,G=" ".repeat(this.indentSize),J=I.split(`
111
+ `).map((Q)=>`${G}${Q}`).join(`
112
+ `);return[`function ${M} {`,J,"}",`Invoke-Expression (& ${M})`,`Remove-Item Function:\\${M} -ErrorAction SilentlyContinue`].join(`
113
+ `)}formatSourceFunction($){return`Invoke-Expression (& ${$.functionName})`}formatCompletion($){let I=[];if($.files)for(let M of $.files)I.push(`if (Test-Path "${M}") { . "${M}" }`);return I.join(`
114
+ `)}formatPath($){let I=$.directory;if($.deduplicate){if($.position==="prepend")return`if ($env:PATH -notlike "*${I}*") { $env:PATH = "${I};$env:PATH" }`;return`if ($env:PATH -notlike "*${I}*") { $env:PATH = "$env:PATH;${I}" }`}if($.position==="prepend")return`$env:PATH = "${I};$env:PATH"`;return`$env:PATH = "$env:PATH;${I}"`}generateOnceScriptContent($,I){let M=["# Generated once script - will self-delete after execution"];return M.push($),M.push(`Remove-Item "${I}"`),M.join(`
115
+ `)}}class y0 extends qM{fileExtension=".zsh";formatEmission($){if(pI($))return this.formatEnvironment($);if(cI($))return this.formatAlias($);if(hI($))return this.formatFunction($);if(n$($))return this.formatScript($);if(gI($))return this.formatSource($);if(mI($))return this.formatSourceFile($);if(nI($))return this.formatSourceFunction($);if(HI($))return this.formatCompletion($);if(iI($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,I){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let G=`once-${I.toString().padStart(lI,"0")}.zsh`,J=`${this.onceScriptDir}/${G}`,Q=c($.content);return{content:this.generateOnceScriptContent(Q,J),filename:G}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
116
116
  # Execute once scripts (runs only once per script)
117
117
  for once_script in "${this.onceScriptDir}"/*.zsh(N); do
118
118
  [[ -f "$once_script" ]] && source "$once_script"
119
119
  done
120
- `)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`export ${J}=${JSON.stringify(Q)}`);return M.join(`
121
- `)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`alias ${J}='${Q.replace(/'/g,"'\\''")}'`);return M.join(`
122
- `)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
123
- `).map((Y)=>`${J}${Y}`).join(`
124
- `);return[`${$.name}() {`,Q,"}"].join(`
125
- `)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
126
- `).map((G)=>`${Q}${G}`).join(`
127
- `);return[`${J}() {`,Y,"}",`source <(${J})`,`unset -f ${J}`].join(`
128
- `)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let M=[];if(M.push("typeset -U fpath"),$.directories)for(let J of $.directories)M.push(`fpath=(${JSON.stringify(J)} $fpath)`);if($.files)for(let J of $.files)M.push(`source "${J}"`);return M.join(`
129
- `)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="${M}:$PATH"`,"fi"].join(`
130
- `);return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="$PATH:${M}"`,"fi"].join(`
131
- `)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}function Q6($,M){switch($){case"zsh":return new bJ(M);case"bash":return new SJ(M);case"powershell":return new wJ(M);default:throw Error(`Unsupported shell type: ${$}`)}}import NJ from"path";function Y6($,M){return`# ${M}`}function O1($,M,J){if(!J)return Y6($,M.repeat(78));let Y=` ${J} `,G=Math.max(0,79-Y.length),X=M.repeat(Math.floor(G/2)),Z=M.repeat(Math.ceil(G/2));return Y6($,`${X}${Y}${Z}`)}function N9($,M){switch($){case"zsh":case"bash":return`source "${M}"`;case"powershell":return`. "${M}"`;default:throw Error(`Unsupported shell type: ${$}`)}}function v9($){return[Y6($,"Generated via dotfiles generator - do not modify"),O1($,"-")].join(`
132
- `)}class G6{fileSystem;homeDir;constructor($,M){this.fileSystem=$,this.homeDir=M}async updateProfiles($){let M=[];for(let J of $){let Q=await this.updateProfile(J);M.push(Q)}return M}getProfilePath($){switch($){case"zsh":return NJ.join(this.homeDir,".zshrc");case"bash":return NJ.join(this.homeDir,".bashrc");case"powershell":return NJ.join(this.homeDir,".config/powershell/profile.ps1");default:throw Error(`Unsupported shell type: ${$}`)}}async hasSourceLine($,M){try{let J=await this.fileSystem.readFile($);return this.getSourcePatterns(M).some((Y)=>J.includes(Y))}catch(J){return!1}}async updateProfile($){let M=$.profilePath??this.getProfilePath($.shellType),J=await this.fileSystem.exists(M),Q={shellType:$.shellType,profilePath:M,fileExists:J,wasUpdated:!1,wasAlreadyPresent:!1};if(!J&&$.onlyIfExists)return Q;let Y="";if(J)try{Y=await this.fileSystem.readFile(M)}catch(H){Y=""}let G=N9($.shellType,$.generatedScriptPath),Z=`${v9($.shellType)}
133
- ${G}`,q="# Generated via dotfiles generator - do not modify";if(Y.includes(q)){let H=this.replaceGeneratedBlocks(Y,Z);if(H!==Y)await this.fileSystem.writeFile(M,H),Q.wasUpdated=!0;else Q.wasAlreadyPresent=!0;return Q}if(this.getSourcePatterns($.generatedScriptPath).some((H)=>Y.includes(H)))return Q.wasAlreadyPresent=!0,Q;if(Y&&!Y.endsWith(`
120
+ `)}formatEnvironment($){let I=[];for(let[M,G]of Object.entries($.variables))I.push(`export ${M}=${JSON.stringify(G)}`);return I.join(`
121
+ `)}formatAlias($){let I=[];for(let[M,G]of Object.entries($.aliases))I.push(`alias ${M}='${G.replace(/'/g,"'\\''")}'`);return I.join(`
122
+ `)}formatFunction($){let I=c($.body),M=" ".repeat(this.indentSize),G=I.split(`
123
+ `).map((J)=>`${M}${J}`).join(`
124
+ `);return[`${$.name}() {`,G,"}"].join(`
125
+ `)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let I=c($.content),M=$.functionName,G=" ".repeat(this.indentSize),J=I.split(`
126
+ `).map((Q)=>`${G}${Q}`).join(`
127
+ `);return[`${M}() {`,J,"}",`source <(${M})`,`unset -f ${M}`].join(`
128
+ `)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let I=[];if(I.push("typeset -U fpath"),$.directories)for(let M of $.directories)I.push(`fpath=(${JSON.stringify(M)} $fpath)`);if($.files)for(let M of $.files)I.push(`source "${M}"`);return I.join(`
129
+ `)}formatPath($){let I=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${I}:"* ]]; then`,` export PATH="${I}:$PATH"`,"fi"].join(`
130
+ `);return[`if [[ ":$PATH:" != *":${I}:"* ]]; then`,` export PATH="$PATH:${I}"`,"fi"].join(`
131
+ `)}if($.position==="prepend")return`export PATH="${I}:$PATH"`;return`export PATH="$PATH:${I}"`}}function J6($,I){switch($){case"zsh":return new y0(I);case"bash":return new b0(I);case"powershell":return new N0(I);default:throw Error(`Unsupported shell type: ${$}`)}}import v0 from"path";function Q6($,I){return`# ${I}`}function F7($,I,M){if(!M)return Q6($,I.repeat(78));let J=` ${M} `,Q=Math.max(0,79-J.length),Y=I.repeat(Math.floor(Q/2)),X=I.repeat(Math.ceil(Q/2));return Q6($,`${Y}${J}${X}`)}function vQ($,I){switch($){case"zsh":case"bash":return`source "${I}"`;case"powershell":return`. "${I}"`;default:throw Error(`Unsupported shell type: ${$}`)}}function PQ($){return[Q6($,"Generated via dotfiles generator - do not modify"),F7($,"-")].join(`
132
+ `)}class Y6{fileSystem;homeDir;constructor($,I){this.fileSystem=$,this.homeDir=I}async updateProfiles($){let I=[];for(let M of $){let G=await this.updateProfile(M);I.push(G)}return I}getProfilePath($){switch($){case"zsh":return v0.join(this.homeDir,".zshrc");case"bash":return v0.join(this.homeDir,".bashrc");case"powershell":return v0.join(this.homeDir,".config/powershell/profile.ps1");default:throw Error(`Unsupported shell type: ${$}`)}}async hasSourceLine($,I){try{let M=await this.fileSystem.readFile($);return this.getSourcePatterns(I).some((J)=>M.includes(J))}catch(M){return!1}}async updateProfile($){let I=$.profilePath??this.getProfilePath($.shellType),M=await this.fileSystem.exists(I),G={shellType:$.shellType,profilePath:I,fileExists:M,wasUpdated:!1,wasAlreadyPresent:!1};if(!M&&$.onlyIfExists)return G;let J="";if(M)try{J=await this.fileSystem.readFile(I)}catch(H){J=""}let Q=vQ($.shellType,$.generatedScriptPath),X=`${PQ($.shellType)}
133
+ ${Q}`,R="# Generated via dotfiles generator - do not modify";if(J.includes(R)){let H=this.replaceGeneratedBlocks(J,X);if(H!==J)await this.fileSystem.writeFile(I,H),G.wasUpdated=!0;else G.wasAlreadyPresent=!0;return G}if(this.getSourcePatterns($.generatedScriptPath).some((H)=>J.includes(H)))return G.wasAlreadyPresent=!0,G;if(J&&!J.endsWith(`
134
+ `))J+=`
135
+ `;let q=`${J}
136
+ ${X}
137
+ `,U=v0.dirname(I);return await this.fileSystem.ensureDir(U),await this.fileSystem.writeFile(I,q),G.wasUpdated=!0,G}replaceGeneratedBlocks($,I){let G="# Generated via dotfiles generator - do not modify".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),J=new RegExp(`${G}[\\s\\S]*?^\\s*(?:source|\\.)\\s+["'].*?["'].*?$`,"gm"),Q=$.split(J),Y=Q[0]||"";if(Y&&!Y.endsWith(`
134
138
  `))Y+=`
135
- `;let U=`${Y}
136
- ${Z}
137
- `,K=NJ.dirname(M);return await this.fileSystem.ensureDir(K),await this.fileSystem.writeFile(M,U),Q.wasUpdated=!0,Q}replaceGeneratedBlocks($,M){let Q="# Generated via dotfiles generator - do not modify".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Y=new RegExp(`${Q}[\\s\\S]*?^\\s*(?:source|\\.)\\s+["'].*?["'].*?$`,"gm"),G=$.split(Y),X=G[0]||"";if(X&&!X.endsWith(`
138
- `))X+=`
139
- `;X+=`${M}
140
- `;for(let Z=1;Z<G.length;Z++){let q=G[Z];if(q)X+=q}return X}getSourcePatterns($){return[`source "${$}"`,`source '${$}'`,`source ${$}`,`. "${$}"`,`. '${$}'`,`. ${$}`]}}import k0 from"path";var v$={constructor:{initialized:()=>W("ShellInitGenerator initialized")},generate:{parsedToolCount:($)=>W(`Resolved ${$} tool configurations for shell init generation`),resolvedOutputPath:($)=>W(`Shell init output path resolved to ${$}`),shellTypeFailure:($)=>W(`Shell init generation failed for ${$}`),writeFailure:($)=>W(`Failed to write shell init artifact ${$}`)},profiles:{starting:($)=>W(`Updating ${$} shell profile entries`),skipped:($)=>W(`Skipping profile update for ${$} as it is not configured`)},cleanup:{onceScriptRemoved:($)=>W(`Removed stale once script ${$}`),failure:($)=>W(`Failed to clean shell init once directory ${$}`)}};import j1 from"path";import X6 from"path";class iM{projectConfig;constructor($){this.projectConfig=$}extractEmissions($){let M=[],J=$.configFilePath,Q=this.getShellConfig($);if(Q?.env){let Y=L0(Q.env);M.push(J?x$(Y,J):Y)}if(Q?.aliases){let Y=x0(Q.aliases);M.push(J?x$(Y,J):Y)}if(Q?.functions)for(let[Y,G]of Object.entries(Q.functions)){let X=q0(Y,G);M.push(J?x$(X,J):X)}if(Q?.scripts)for(let Y of Q.scripts){let G=this.createScriptEmission(Y);if(G)M.push(J?x$(G,J):G)}if(Q?.completions){let Y=this.resolveCompletionConfig(Q.completions);if(Y){let G=this.createCompletionEmission(Y);if(G)M.push(J?x$(G,J):G)}}if(Q?.paths){let Y=new Set;for(let G of Q.paths){let X=this.resolvePathInput(G);if(X&&!Y.has(X)){Y.add(X);let Z=xJ(X);M.push(J?x$(Z,J):Z)}}}return M}createScriptEmission($){let M=e0($);if(r0($))return IM(M,"once");else if(t0($))return IM(M,"always");else if(o0($))return IM(M,"raw");return}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({files:[M]});return}resolveCompletionConfig($){if(typeof $==="function")return{source:"callback"};if(typeof $==="string")return{source:$};return $}resolvePathInput($){if(typeof $==="function"){let M=$(void 0);if(M instanceof Promise)return;return M}return $}hasEmissions($){let M=this.getShellConfig($);if(!M)return!1;return Boolean(M.env&&Object.keys(M.env).length>0||M.aliases&&Object.keys(M.aliases).length>0||M.functions&&Object.keys(M.functions).length>0||M.scripts&&M.scripts.length>0||M.paths&&M.paths.length>0||M.completions)}generateFileContent($){return this.renderContent($).content}getDefaultOutputPath(){return X6.join(this.projectConfig.paths.shellScriptsDir,`main${this.fileExtension}`)}getAdditionalFiles($){return this.renderContent($).onceScripts.map((J)=>({content:J.content,outputPath:X6.join(this.projectConfig.paths.shellScriptsDir,".once",J.filename)}))}createFormatterConfig(){return{onceScriptDir:X6.join(this.projectConfig.paths.shellScriptsDir,".once")}}renderContent($){let M=this.createFormatterConfig(),J=Q6(this.shellType,M),Q=new kJ,Y=new TJ().addSection("header",{priority:0,isFileHeader:!0,metadata:{sourceFile:this.projectConfig.paths.dotfilesDir}}).addSection("cli",{title:"Dotfiles CLI",priority:50}).addSection("path",{title:"PATH Modifications",priority:100,hoistKinds:["path"]}).addSection("environment",{title:"Environment Variables",priority:200,hoistKinds:["environment"]}).addSection("main",{title:"Tool-Specific Initializations",priority:300,allowChildren:!0}).addSection("completions",{title:"Shell Completions Setup",priority:500,hoistKinds:["completion"]}).addSection("footer",{priority:999,isFileFooter:!0}),G=M6(xJ(this.projectConfig.paths.targetDir,{deduplicate:!0}),-1);Y.addEmission(G);let X=sM(),Z=this.projectConfig.configFilePath?.replaceAll('"',"\\\""),q=Z?` --config "${Z}"`:"",I=`${X}${q} "$@"`,U=q0("dotfiles",I);Y.addEmissionToSection(U,"cli");for(let[H,_]of $)for(let O of _)Y.addEmission(O,H);let K=Y.build();return Q.render(K,J)}}class Z6 extends iM{shellType="bash";fileExtension=".bash";getShellConfig($){return $.shellConfigs?.bash}getCompletionDir(){return j1.join(this.projectConfig.paths.shellScriptsDir,"bash","completions")}}import V1 from"path";class W6 extends iM{shellType="powershell";fileExtension=".ps1";getShellConfig($){return $.shellConfigs?.powershell}getCompletionDir(){return V1.join(this.projectConfig.paths.shellScriptsDir,"powershell","completions")}}import z1 from"path";class q6 extends iM{shellType="zsh";fileExtension=".zsh";getShellConfig($){return $.shellConfigs?.zsh}getCompletionDir(){return z1.join(this.projectConfig.paths.shellScriptsDir,"zsh","completions")}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({directories:[M]});return}}var B1=new Map([["zsh",($)=>new q6($)],["bash",($)=>new Z6($)],["powershell",($)=>new W6($)]]);function y9($,M){let J=B1.get($);if(!J)throw Error(`Unsupported shell type: ${$}`);return J(M)}class I6{fs;projectConfig;logger;constructor($,M,J){this.logger=$.getSubLogger({name:"ShellInitGenerator"}),this.logger.getSubLogger({name:"constructor"}).debug(v$.constructor.initialized()),this.fs=M,this.projectConfig=J}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=M?.shellTypes??["zsh"],Y=new Map,G=null,X=$?Object.keys($).length:0;J.debug(v$.generate.parsedToolCount(X));for(let I of Q){let U=await this.generateForShellType(I,$,M);if(U){if(Y.set(I,U.outputPath),G===null)G=U.outputPath}}if(Y.size===0)return null;let Z={files:Y,primaryPath:G};if(M?.updateProfileFiles??!0)Z.profileUpdates=await this.updateProfileFiles(Y);return Z}async generateForShellType($,M,J){let Q=this.logger.getSubLogger({name:"generateForShellType"});try{let Y=y9($,this.projectConfig),G=J?.outputPath??Y.getDefaultOutputPath();Q.debug(v$.generate.resolvedOutputPath(G));let X=this.extractToolEmissions(M,Y,J),Z=Y.generateFileContent(X);await this.cleanupOnceScriptsDirectory($);let q=Y.getAdditionalFiles(X);return await this.writeShellFiles(G,Z,q)?{outputPath:G}:null}catch(Y){return Q.debug(v$.generate.shellTypeFailure($),Y),null}}extractToolEmissions($,M,J){let Q=new Map;for(let Y in $){let G=$[Y];if(!G)continue;let X=J?.systemInfo?Y$(G,J.systemInfo):G,Z=M.extractEmissions(X),q=J?.pluginShellInit?.[Y]?.[M.shellType];if(q){let I=this.convertPluginShellInit(q,X.configFilePath);Z.push(...I)}if(Z.length>0)Q.set(Y,Z)}return Q}convertPluginShellInit($,M){let J=[],Q=M;if($.environmentVariables){let Y=L0($.environmentVariables);J.push(Q?x$(Y,Q):Y)}if($.aliases){let Y=x0($.aliases);J.push(Q?x$(Y,Q):Y)}if($.scripts)for(let Y of $.scripts){let G=e0(Y),X;if(r0(Y))X=IM(G,"once");else if(t0(Y))X=IM(G,"always");else if(o0(Y))X=IM(G,"raw");if(X)J.push(Q?x$(X,Q):X)}if($.functions)for(let[Y,G]of Object.entries($.functions)){let X=q0(Y,G);J.push(Q?x$(X,Q):X)}return J}async writeShellFiles($,M,J){let Q=this.logger.getSubLogger({name:"writeShellFiles"});try{await this.fs.ensureDir(k0.dirname($)),await this.fs.writeFile($,M);for(let Y of J)await this.writeAdditionalFile(Y);return!0}catch(Y){return Q.debug(v$.generate.writeFailure($),Y),!1}}async writeAdditionalFile($){let M=this.logger.getSubLogger({name:"writeAdditionalFile"});try{await this.fs.ensureDir(k0.dirname($.outputPath)),await this.fs.writeFile($.outputPath,$.content)}catch(J){M.debug(v$.generate.writeFailure($.outputPath),J)}}async updateProfileFiles($){let M=this.logger.getSubLogger({name:"updateProfileFiles"}),J=new G6(this.fs,this.projectConfig.paths.homeDir),Q=this.projectConfig.features.shellInstall;if(!Q)return M.debug(v$.profiles.skipped("all")),[];let Y=[];for(let[G,X]of $){let Z;if(G==="zsh")Z=Q?.zsh;else if(G==="bash")Z=Q?.bash;else if(G==="powershell")Z=Q?.powershell;if(!Z){M.debug(v$.profiles.skipped(G));continue}if(Z?.startsWith("~/"))Z=k0.join(this.projectConfig.paths.homeDir,Z.slice(2));else if(Z==="~")Z=this.projectConfig.paths.homeDir;Y.push({shellType:G,generatedScriptPath:X,onlyIfExists:!0,projectConfigPath:this.projectConfig.configFilePath,profilePath:Z})}return M.debug(v$.profiles.starting(Y.length)),await J.updateProfiles(Y)}async cleanupOnceScriptsDirectory($){let M=this.logger.getSubLogger({name:"cleanupOnceScriptsDirectory"}),J=k0.join(this.projectConfig.paths.shellScriptsDir,".once");try{if(!await this.fs.exists(J))return;let Y=this.getShellExtension($),G=await this.fs.readdir(J);for(let X of G)if(X.endsWith(`.${Y}`)){let Z=k0.join(J,X);await this.fs.rm(Z),M.debug(v$.cleanup.onceScriptRemoved(Z))}}catch(Q){M.debug(v$.cleanup.failure(J),Q)}}getShellExtension($){switch($){case"zsh":return"zsh";case"bash":return"bash";case"powershell":return"ps1";default:throw Error(`Unsupported shell type: ${$}`)}}}import D1 from"path";class U6{storage;shellType;context;logger;toolName;sourceFileCounter=0;sourceCounter=0;constructor($,M,J,Q,Y){this.storage=$,this.shellType=M,this.context=J,this.logger=Q.getSubLogger({name:"ShellConfigurator"}).setPrefix(Y),this.toolName=Y}env($){return this.storage.env={...this.storage.env,...$},this}aliases($){return this.storage.aliases={...this.storage.aliases,...$},this}sourceFile($){let M=this.resolvePath($),J=this.generateSourceFileFunctionName(),Q=this.createSourceFileFunctionBody(M);this.storage.functions[J]=Q;let Y=this.createSourceFunctionCommand(J),G=this.createUnsetFunctionCommand(J);return this.storage.scripts.push(n$(Y)),this.storage.scripts.push(n$(G)),this}sourceFunction($){let M=this.createSourceFunctionCommand($);return this.storage.scripts.push(n$(M)),this}source($){let M=this.generateSourceFunctionName();this.storage.functions[M]=$;let J=this.createSourceFunctionCommand(M),Q=this.createUnsetFunctionCommand(M);return this.storage.scripts.push(n$(J)),this.storage.scripts.push(n$(Q)),this}completions($){return this.storage.completions=$,this}once($){return this.storage.scripts.push(TY($)),this}always($){return this.storage.scripts.push(kY($)),this}functions($){let M=this.validateFunctionNames($);return this.storage.functions={...this.storage.functions,...M},this}path($){return this.storage.paths.push($),this}validateFunctionNames($){let M={};for(let[J,Q]of Object.entries($)){if(!J||!F9.test(J)){this.logger.error(WM.invalidFunctionName(J));continue}M[J]=Q}return M}generateSourceFileFunctionName(){let $=this.sourceFileCounter++;return`__dotfiles_source_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}generateSourceFunctionName(){let $=this.sourceCounter++;return`__dotfiles_source_inline_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}createSourceFileFunctionBody($){let M=JSON.stringify($);if(this.shellType==="powershell")return`if (Test-Path ${M}) { Get-Content ${M} -Raw }`;return`[[ -f ${M} ]] && cat ${M}`}createUnsetFunctionCommand($){if(this.shellType==="powershell")return`Remove-Item Function:\\${$} -ErrorAction SilentlyContinue`;return`unset -f ${$}`}createSourceFunctionCommand($){if(this.shellType==="powershell")return`. (${$})`;return`source <(${$})`}resolvePath($){let M=$.trim();if(M.length===0){let Q=WM.configurationFieldInvalid("shell source path",$,"non-empty value");throw this.logger.error(Q),Error(Q)}if(D1.isAbsolute(M))return this.normalizePath(M);if(!this.context){let Q=WM.configurationFieldRequired("tool context",`Please ensure createInstallFunction receives tool context before using shell.sourceFile() for "${this.toolName}"`);throw this.logger.error(Q),Error(Q)}let J=FJ(this.context.toolDir,M);return this.normalizePath(J)}normalizePath($){if(this.shellType==="powershell")return $.replace(/\//gu,"\\");return $.replace(/\\/gu,"/")}}class S0{logger;toolName;binaries=[];versionNum="latest";currentInstallationMethod;currentInstallParams;dependencies=[];isDisabled=!1;hostnamePattern;internalShellConfigs={zsh:{scripts:[],aliases:{},env:{},functions:{},paths:[]},bash:{scripts:[],aliases:{},env:{},functions:{},paths:[]},powershell:{scripts:[],aliases:{},env:{},functions:{},paths:[]}};context;symlinkPairs=[];copyPairs=[];updateCheckConfig;platformConfigEntries=[];isPlatformScope;bin($,M){let J=M||`*/${$}`;return this.binaries.push({name:$,pattern:J}),this}version($){return this.versionNum=$,this}install($,M){return this.currentInstallationMethod=$,this.currentInstallParams=M,this}hook($,M){if(!this.currentInstallParams)return this.logger.warn(WM.configurationFieldIgnored("hook",`hook() called for tool "${this.toolName}" before install(). Hook will not be set as install() was not called first.`)),this;let J=this.currentInstallParams.hooks||{},Q=J[$]||[];return Q.push(M),J[$]=Q,this.currentInstallParams.hooks=J,this}zsh($){return this.configureShell("zsh",$)}bash($){return this.configureShell("bash",$)}powershell($){return this.configureShell("powershell",$)}buildShellConfigs(){let $=["zsh","bash","powershell"],M={},J=!1;for(let Q of $){let Y=this.internalShellConfigs[Q],G=Y.scripts.length>0,X=Object.keys(Y.aliases).length>0,Z=Object.keys(Y.env).length>0,q=Object.keys(Y.functions).length>0,I=Y.paths.length>0,U=Y.completions!==void 0;if(G||X||Z||q||I||U)M[Q]={...G&&{scripts:Y.scripts},...X&&{aliases:Y.aliases},...Z&&{env:Y.env},...q&&{functions:Y.functions},...I&&{paths:Y.paths},...U&&{completions:Y.completions}},J=!0}return J?M:void 0}symlink($,M){return this.symlinkPairs.push({source:$,target:M}),this}copy($,M){return this.copyPairs.push({source:$,target:M}),this}dependsOn(...$){for(let M of $){let J=M.trim();if(J.length===0){let Q=WM.configurationFieldInvalid("dependency",M,"non-empty string");this.logger.warn(Q);continue}if(!this.dependencies.includes(J))this.dependencies.push(J)}return this}platform($,M,J){let Q,Y;if(typeof M==="function")Y=M,Q=void 0;else{if(Q=M,typeof J!=="function"){let q=WM.configurationFieldRequired("configure callback",`platform() called for tool "${this.toolName}" with architectures but without a configure callback`);throw this.logger.error(q),Error(q)}Y=J}let G=new S0(this.logger,this.toolName,!0);G.setContext(this.context),Y((...q)=>{if(q.length===0)return G;let[I,U]=q;return G.install(I,U),G});let Z=G.buildPlatformConfig();return this.platformConfigEntries.push({platforms:$,architectures:Q,config:Z}),this}disable(){return this.isDisabled=!0,this}hostname($){if($ instanceof RegExp)this.hostnamePattern=$.source;else this.hostnamePattern=$;return this}updateCheck($){return this.updateCheckConfig=$,this}build(){let $=this.buildBaseConfig();if(this.hasInstallationMethod())return this.buildInstallableToolConfig($);return this.validateConfigurationOnly($),this.buildConfigurationOnlyTool($)}buildBaseConfig(){return{name:this.toolName,binaries:this.binaries.length>0?this.binaries.map(($)=>$.pattern===`*/${$.name}`?$.name:$):void 0,version:this.versionNum,disabled:this.isDisabled?!0:void 0,hostname:this.hostnamePattern,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0,platformConfigs:this.isPlatformScope?void 0:this.platformConfigEntries.length>0?this.platformConfigEntries:void 0}}buildPlatformConfig(){let $={binaries:this.binaries.length>0?this.binaries.map((M)=>M.pattern===`*/${M.name}`?M.name:M):void 0,version:this.versionNum!=="latest"?this.versionNum:void 0,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0};if(this.hasInstallationMethod())$.installationMethod=this.currentInstallationMethod,$.installParams=this.currentInstallParams;return Object.keys($).forEach((M)=>{if($[M]===void 0)delete $[M]}),$}hasInstallationMethod(){return Boolean(this.currentInstallationMethod&&this.currentInstallParams)}buildInstallableToolConfig($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:this.currentInstallationMethod,installParams:this.currentInstallParams}}validateConfigurationOnly($){if(!(($.binaries&&$.binaries.length>0?$.binaries:[]).length>0||$.shellConfigs||$.symlinks||$.copies||$.platformConfigs&&$.platformConfigs.length>0)){let Q=WM.configurationFieldRequired("tool definition",`Tool "${$.name}" must define at least binaries, shell init scripts (zsh/bash/powershell), symlinks, or platformConfigs`);throw this.logger.error(Q),Error(Q)}}buildConfigurationOnlyTool($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:"manual",installParams:{}}}constructor($,M,J=!1){this.logger=$.getSubLogger({name:"IToolConfigBuilder"}),this.toolName=M,this.isPlatformScope=J}setContext($){this.context=$}get shellConfigs(){return this.internalShellConfigs}configureShell($,M){let J=this.internalShellConfigs[$],Q=new U6(J,$,this.context,this.logger,this.toolName),Y=M(Q);if(this.isPromise(Y))return Y.then(()=>this);return this}isPromise($){if($===null||$===void 0)return!1;if(typeof $!=="object"&&typeof $!=="function")return!1;return typeof $.then==="function"}}function P9($,M,J){let Q=null,Y=()=>{if(!Q)Q=new S0($,M);return Q.setContext(J),Q};function G(X,Z){let q=Y();if(X){let I={};q.currentInstallationMethod=X,q.currentInstallParams=Z??I}return q}return G}import vJ from"path";var p={configurationProcessing:()=>W("config processing"),platformOverrides:($,M)=>W(`platform overrides: ${$} ${M}`),configurationValidationFailed:($)=>W(`Configuration validation failed:
139
+ `;Y+=`${I}
140
+ `;for(let X=1;X<Q.length;X++){let R=Q[X];if(R)Y+=R}return Y}getSourcePatterns($){return[`source "${$}"`,`source '${$}'`,`source ${$}`,`. "${$}"`,`. '${$}'`,`. ${$}`]}}import NM from"path";var C$={constructor:{initialized:()=>Z("ShellInitGenerator initialized")},generate:{parsedToolCount:($)=>Z(`Resolved ${$} tool configurations for shell init generation`),resolvedOutputPath:($)=>Z(`Shell init output path resolved to ${$}`),shellTypeFailure:($)=>Z(`Shell init generation failed for ${$}`),writeFailure:($)=>Z(`Failed to write shell init artifact ${$}`)},profiles:{starting:($)=>Z(`Updating ${$} shell profile entries`),skipped:($)=>Z(`Skipping profile update for ${$} as it is not configured`)},cleanup:{onceScriptRemoved:($)=>Z(`Removed stale once script ${$}`),failure:($)=>Z(`Failed to clean shell init once directory ${$}`)}};import L7 from"path";import X6 from"path";class aI{projectConfig;constructor($){this.projectConfig=$}extractEmissions($){let I=[],M=$.configFilePath,G=this.getShellConfig($);if(G?.env){let J=kM(G.env);I.push(M?T$(J,M):J)}if(G?.aliases){let J=wM(G.aliases);I.push(M?T$(J,M):J)}if(G?.functions)for(let[J,Q]of Object.entries(G.functions)){let Y=UM(J,Q);I.push(M?T$(Y,M):Y)}if(G?.scripts)for(let J of G.scripts){let Q=this.createScriptEmission(J);if(Q)I.push(M?T$(Q,M):Q)}if(G?.completions){let J=this.resolveCompletionConfig(G.completions);if(J){let Q=this.createCompletionEmission(J);if(Q)I.push(M?T$(Q,M):Q)}}if(G?.paths){let J=new Set;for(let Q of G.paths){let Y=this.resolvePathInput(Q);if(Y&&!J.has(Y)){J.add(Y);let X=S0(Y);I.push(M?T$(X,M):X)}}}return I}createScriptEmission($){let I=G0($);if($0($))return UI(I,"once");else if(I0($))return UI(I,"always");else if(M0($))return UI(I,"raw");return}createCompletionEmission($){let I=this.getCompletionDir();if($.cmd||$.source)return bM({files:[I]});return}resolveCompletionConfig($){if(typeof $==="function")return{source:"callback"};if(typeof $==="string")return{source:$};return $}resolvePathInput($){if(typeof $==="function"){let I=$(void 0);if(I instanceof Promise)return;return I}return $}hasEmissions($){let I=this.getShellConfig($);if(!I)return!1;return Boolean(I.env&&Object.keys(I.env).length>0||I.aliases&&Object.keys(I.aliases).length>0||I.functions&&Object.keys(I.functions).length>0||I.scripts&&I.scripts.length>0||I.paths&&I.paths.length>0||I.completions)}generateFileContent($){return this.renderContent($).content}getDefaultOutputPath(){return X6.join(this.projectConfig.paths.shellScriptsDir,`main${this.fileExtension}`)}getAdditionalFiles($){return this.renderContent($).onceScripts.map((M)=>({content:M.content,outputPath:X6.join(this.projectConfig.paths.shellScriptsDir,".once",M.filename)}))}createFormatterConfig(){return{onceScriptDir:X6.join(this.projectConfig.paths.shellScriptsDir,".once")}}renderContent($){let I=this.createFormatterConfig(),M=J6(this.shellType,I),G=new w0,J=new k0().addSection("header",{priority:0,isFileHeader:!0,metadata:{sourceFile:this.projectConfig.paths.dotfilesDir}}).addSection("cli",{title:"Dotfiles CLI",priority:50}).addSection("path",{title:"PATH Modifications",priority:100,hoistKinds:["path"]}).addSection("environment",{title:"Environment Variables",priority:200,hoistKinds:["environment"]}).addSection("main",{title:"Tool-Specific Initializations",priority:300,allowChildren:!0}).addSection("completions",{title:"Shell Completions Setup",priority:500,hoistKinds:["completion"]}).addSection("footer",{priority:999,isFileFooter:!0}),Q=M6(S0(this.projectConfig.paths.targetDir,{deduplicate:!0}),-1);J.addEmission(Q);let Y=tI(),X=this.projectConfig.configFilePath?.replaceAll('"',"\\\""),R=X?` --config "${X}"`:"",W=`${Y}${R} "$@"`,q=UM("dotfiles",W);J.addEmissionToSection(q,"cli");for(let[H,K]of $)for(let O of K)J.addEmission(O,H);let U=J.build();return G.render(U,M)}}class Z6 extends aI{shellType="bash";fileExtension=".bash";getShellConfig($){return $.shellConfigs?.bash}getCompletionDir(){return L7.join(this.projectConfig.paths.shellScriptsDir,"bash","completions")}}import E7 from"path";class R6 extends aI{shellType="powershell";fileExtension=".ps1";getShellConfig($){return $.shellConfigs?.powershell}getCompletionDir(){return E7.join(this.projectConfig.paths.shellScriptsDir,"powershell","completions")}}import T7 from"path";class W6 extends aI{shellType="zsh";fileExtension=".zsh";getShellConfig($){return $.shellConfigs?.zsh}getCompletionDir(){return T7.join(this.projectConfig.paths.shellScriptsDir,"zsh","completions")}createCompletionEmission($){let I=this.getCompletionDir();if($.cmd||$.source)return bM({directories:[I]});return}}var S7=new Map([["zsh",($)=>new W6($)],["bash",($)=>new Z6($)],["powershell",($)=>new R6($)]]);function CQ($,I){let M=S7.get($);if(!M)throw Error(`Unsupported shell type: ${$}`);return M(I)}class q6{fs;projectConfig;logger;constructor($,I,M){this.logger=$.getSubLogger({name:"ShellInitGenerator"}),this.logger.getSubLogger({name:"constructor"}).debug(C$.constructor.initialized()),this.fs=I,this.projectConfig=M}async generate($,I){let M=this.logger.getSubLogger({name:"generate"}),G=I?.shellTypes??["zsh"],J=new Map,Q=null,Y=$?Object.keys($).length:0;M.debug(C$.generate.parsedToolCount(Y));for(let W of G){let q=await this.generateForShellType(W,$,I);if(q){if(J.set(W,q.outputPath),Q===null)Q=q.outputPath}}if(J.size===0)return null;let X={files:J,primaryPath:Q};if(I?.updateProfileFiles??!0)X.profileUpdates=await this.updateProfileFiles(J);return X}async generateForShellType($,I,M){let G=this.logger.getSubLogger({name:"generateForShellType"});try{let J=CQ($,this.projectConfig),Q=M?.outputPath??J.getDefaultOutputPath();G.debug(C$.generate.resolvedOutputPath(Q));let Y=this.extractToolEmissions(I,J,M),X=J.generateFileContent(Y);await this.cleanupOnceScriptsDirectory($);let R=J.getAdditionalFiles(Y);return await this.writeShellFiles(Q,X,R)?{outputPath:Q}:null}catch(J){return G.debug(C$.generate.shellTypeFailure($),J),null}}extractToolEmissions($,I,M){let G=new Map;for(let J in $){let Q=$[J];if(!Q)continue;let Y=M?.systemInfo?I$(Q,M.systemInfo):Q,X=I.extractEmissions(Y),R=M?.pluginShellInit?.[J]?.[I.shellType];if(R){let W=this.convertPluginShellInit(R,Y.configFilePath);X.push(...W)}if(X.length>0)G.set(J,X)}return G}convertPluginShellInit($,I){let M=[],G=I;if($.environmentVariables){let J=kM($.environmentVariables);M.push(G?T$(J,G):J)}if($.aliases){let J=wM($.aliases);M.push(G?T$(J,G):J)}if($.scripts)for(let J of $.scripts){let Q=G0(J),Y;if($0(J))Y=UI(Q,"once");else if(I0(J))Y=UI(Q,"always");else if(M0(J))Y=UI(Q,"raw");if(Y)M.push(G?T$(Y,G):Y)}if($.functions)for(let[J,Q]of Object.entries($.functions)){let Y=UM(J,Q);M.push(G?T$(Y,G):Y)}return M}async writeShellFiles($,I,M){let G=this.logger.getSubLogger({name:"writeShellFiles"});try{await this.fs.ensureDir(NM.dirname($)),await this.fs.writeFile($,I);for(let J of M)await this.writeAdditionalFile(J);return!0}catch(J){return G.debug(C$.generate.writeFailure($),J),!1}}async writeAdditionalFile($){let I=this.logger.getSubLogger({name:"writeAdditionalFile"});try{await this.fs.ensureDir(NM.dirname($.outputPath)),await this.fs.writeFile($.outputPath,$.content)}catch(M){I.debug(C$.generate.writeFailure($.outputPath),M)}}async updateProfileFiles($){let I=this.logger.getSubLogger({name:"updateProfileFiles"}),M=new Y6(this.fs,this.projectConfig.paths.homeDir),G=this.projectConfig.features.shellInstall;if(!G)return I.debug(C$.profiles.skipped("all")),[];let J=[];for(let[Q,Y]of $){let X;if(Q==="zsh")X=G?.zsh;else if(Q==="bash")X=G?.bash;else if(Q==="powershell")X=G?.powershell;if(!X){I.debug(C$.profiles.skipped(Q));continue}if(X?.startsWith("~/"))X=NM.join(this.projectConfig.paths.homeDir,X.slice(2));else if(X==="~")X=this.projectConfig.paths.homeDir;J.push({shellType:Q,generatedScriptPath:Y,onlyIfExists:!0,projectConfigPath:this.projectConfig.configFilePath,profilePath:X})}return I.debug(C$.profiles.starting(J.length)),await M.updateProfiles(J)}async cleanupOnceScriptsDirectory($){let I=this.logger.getSubLogger({name:"cleanupOnceScriptsDirectory"}),M=NM.join(this.projectConfig.paths.shellScriptsDir,".once");try{if(!await this.fs.exists(M))return;let J=this.getShellExtension($),Q=await this.fs.readdir(M);for(let Y of Q)if(Y.endsWith(`.${J}`)){let X=NM.join(M,Y);await this.fs.rm(X),I.debug(C$.cleanup.onceScriptRemoved(X))}}catch(G){I.debug(C$.cleanup.failure(M),G)}}getShellExtension($){switch($){case"zsh":return"zsh";case"bash":return"bash";case"powershell":return"ps1";default:throw Error(`Unsupported shell type: ${$}`)}}}import k7 from"path";class U6{storage;shellType;context;logger;toolName;sourceFileCounter=0;sourceCounter=0;constructor($,I,M,G,J){this.storage=$,this.shellType=I,this.context=M,this.logger=G.getSubLogger({name:"ShellConfigurator"}).setPrefix(J),this.toolName=J}env($){return this.storage.env={...this.storage.env,...$},this}aliases($){return this.storage.aliases={...this.storage.aliases,...$},this}sourceFile($){let I=this.resolvePath($),M=this.generateSourceFileFunctionName(),G=this.createSourceFileFunctionBody(I);this.storage.functions[M]=G;let J=this.createSourceFunctionCommand(M),Q=this.createUnsetFunctionCommand(M);return this.storage.scripts.push(a$(J)),this.storage.scripts.push(a$(Q)),this}sourceFunction($){let I=this.createSourceFunctionCommand($);return this.storage.scripts.push(a$(I)),this}source($){let I=this.generateSourceFunctionName();this.storage.functions[I]=$;let M=this.createSourceFunctionCommand(I),G=this.createUnsetFunctionCommand(I);return this.storage.scripts.push(a$(M)),this.storage.scripts.push(a$(G)),this}completions($){return this.storage.completions=$,this}once($){return this.storage.scripts.push(kJ($)),this}always($){return this.storage.scripts.push(wJ($)),this}functions($){let I=this.validateFunctionNames($);return this.storage.functions={...this.storage.functions,...I},this}path($){return this.storage.paths.push($),this}validateFunctionNames($){let I={};for(let[M,G]of Object.entries($)){if(!M||!EQ.test(M)){this.logger.error(EI.invalidFunctionName(M));continue}I[M]=G}return I}generateSourceFileFunctionName(){let $=this.sourceFileCounter++;return`__dotfiles_source_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}generateSourceFunctionName(){let $=this.sourceCounter++;return`__dotfiles_source_inline_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}createSourceFileFunctionBody($){let I=JSON.stringify($);if(this.shellType==="powershell")return`if (Test-Path ${I}) { Get-Content ${I} -Raw }`;return`[[ -f ${I} ]] && cat ${I}`}createUnsetFunctionCommand($){if(this.shellType==="powershell")return`Remove-Item Function:\\${$} -ErrorAction SilentlyContinue`;return`unset -f ${$}`}createSourceFunctionCommand($){if(this.shellType==="powershell")return`. (${$})`;return`source <(${$})`}resolvePath($){let I=$.trim();if(I.length===0){let G=EI.configurationFieldInvalid("shell source path",$,"non-empty value");throw this.logger.error(G),Error(G)}if(k7.isAbsolute(I))return this.normalizePath(I);if(!this.context){let G=EI.configurationFieldRequired("tool context",`Please ensure createInstallFunction receives tool context before using shell.sourceFile() for "${this.toolName}"`);throw this.logger.error(G),Error(G)}let M=E0(this.context.toolDir,I);return this.normalizePath(M)}normalizePath($){if(this.shellType==="powershell")return $.replace(/\//gu,"\\");return $.replace(/\\/gu,"/")}}class yM{logger;toolName;binaries=[];versionNum="latest";currentInstallationMethod;currentInstallParams;dependencies=[];isDisabled=!1;hostnamePattern;internalShellConfigs={zsh:{scripts:[],aliases:{},env:{},functions:{},paths:[]},bash:{scripts:[],aliases:{},env:{},functions:{},paths:[]},powershell:{scripts:[],aliases:{},env:{},functions:{},paths:[]}};context;symlinkPairs=[];copyPairs=[];updateCheckConfig;platformConfigEntries=[];isPlatformScope;bin($,I){let M=I||`*/${$}`;return this.binaries.push({name:$,pattern:M}),this}version($){return this.versionNum=$,this}install($,I){this.currentInstallationMethod=$;let M=this.currentInstallParams?.hooks;if(this.currentInstallParams={...I},M)this.currentInstallParams.hooks=M;return this}hook($,I){if(!this.currentInstallParams)this.currentInstallParams={};let M=this.currentInstallParams.hooks||{},G=M[$]||[];return G.push(I),M[$]=G,this.currentInstallParams.hooks=M,this}zsh($){return this.configureShell("zsh",$)}bash($){return this.configureShell("bash",$)}powershell($){return this.configureShell("powershell",$)}buildShellConfigs(){let $=["zsh","bash","powershell"],I={},M=!1;for(let G of $){let J=this.internalShellConfigs[G],Q=J.scripts.length>0,Y=Object.keys(J.aliases).length>0,X=Object.keys(J.env).length>0,R=Object.keys(J.functions).length>0,W=J.paths.length>0,q=J.completions!==void 0;if(Q||Y||X||R||W||q)I[G]={...Q&&{scripts:J.scripts},...Y&&{aliases:J.aliases},...X&&{env:J.env},...R&&{functions:J.functions},...W&&{paths:J.paths},...q&&{completions:J.completions}},M=!0}return M?I:void 0}symlink($,I){return this.symlinkPairs.push({source:$,target:I}),this}copy($,I){return this.copyPairs.push({source:$,target:I}),this}dependsOn(...$){for(let I of $){let M=I.trim();if(M.length===0){let G=EI.configurationFieldInvalid("dependency",I,"non-empty string");this.logger.warn(G);continue}if(!this.dependencies.includes(M))this.dependencies.push(M)}return this}platform($,I,M){let G,J;if(typeof I==="function")J=I,G=void 0;else{if(G=I,typeof M!=="function"){let R=EI.configurationFieldRequired("configure callback",`platform() called for tool "${this.toolName}" with architectures but without a configure callback`);throw this.logger.error(R),Error(R)}J=M}let Q=new yM(this.logger,this.toolName,!0);Q.setContext(this.context),J((...R)=>{if(R.length===0)return Q;let[W,q]=R;return Q.install(W,q),Q});let X=Q.buildPlatformConfig();return this.platformConfigEntries.push({platforms:$,architectures:G,config:X}),this}disable(){return this.isDisabled=!0,this}hostname($){if($ instanceof RegExp)this.hostnamePattern=$.source;else this.hostnamePattern=$;return this}updateCheck($){return this.updateCheckConfig=$,this}build(){let $=this.buildBaseConfig();if(this.hasInstallationMethod())return this.buildInstallableToolConfig($);return this.validateConfigurationOnly($),this.buildConfigurationOnlyTool($)}buildBaseConfig(){return{name:this.toolName,binaries:this.binaries.length>0?this.binaries.map(($)=>$.pattern===`*/${$.name}`?$.name:$):void 0,version:this.versionNum,disabled:this.isDisabled?!0:void 0,hostname:this.hostnamePattern,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0,platformConfigs:this.isPlatformScope?void 0:this.platformConfigEntries.length>0?this.platformConfigEntries:void 0}}buildPlatformConfig(){let $={binaries:this.binaries.length>0?this.binaries.map((I)=>I.pattern===`*/${I.name}`?I.name:I):void 0,version:this.versionNum!=="latest"?this.versionNum:void 0,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0};if(this.hasInstallationMethod())$.installationMethod=this.currentInstallationMethod,$.installParams=this.currentInstallParams;return Object.keys($).forEach((I)=>{if($[I]===void 0)delete $[I]}),$}hasInstallationMethod(){return Boolean(this.currentInstallationMethod&&this.currentInstallParams)}buildInstallableToolConfig($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:this.currentInstallationMethod,installParams:this.currentInstallParams}}validateConfigurationOnly($){if(!(($.binaries&&$.binaries.length>0?$.binaries:[]).length>0||$.shellConfigs||$.symlinks||$.copies||$.platformConfigs&&$.platformConfigs.length>0)){let G=EI.configurationFieldRequired("tool definition",`Tool "${$.name}" must define at least binaries, shell init scripts (zsh/bash/powershell), symlinks, or platformConfigs`);throw this.logger.error(G),Error(G)}}buildConfigurationOnlyTool($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:"manual",installParams:{}}}constructor($,I,M=!1){this.logger=$.getSubLogger({name:"IToolConfigBuilder"}),this.toolName=I,this.isPlatformScope=M}setContext($){this.context=$}get shellConfigs(){return this.internalShellConfigs}configureShell($,I){let M=this.internalShellConfigs[$],G=new U6(M,$,this.context,this.logger,this.toolName),J=I(G);if(this.isPromise(J))return J.then(()=>this);return this}isPromise($){if($===null||$===void 0)return!1;if(typeof $!=="object"&&typeof $!=="function")return!1;return typeof $.then==="function"}}function dQ($,I,M){let G=null,J=()=>{if(!G)G=new yM($,I);return G.setContext(M),G};function Q(Y,X){let R=J();if(Y){let W={};R.currentInstallationMethod=Y,R.currentInstallParams=X??W}return R}return Q}import P0 from"path";var p={configurationProcessing:()=>Z("config processing"),platformOverrides:($,I)=>Z(`platform overrides: ${$} ${I}`),configurationValidationFailed:($)=>Z(`Configuration validation failed:
141
141
  ${$.join(`
142
- `)}`),configurationParseError:($,M,J)=>W(`Failed to parse ${M} configuration ${$}: ${J}`),configurationLoadFailed:($)=>W(`Failed to load configuration: ${$}`),configurationLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigLoadingStarted:($)=>W(`tool config loading: ${$}`),singleToolConfigLoadingStarted:($,M)=>W(`single tool config load: ${$} in ${M}`),toolConfigDirectoryScan:($)=>W(`Directory scan: ${$}`),toolConfigLoadingCompleted:()=>W("tool config loading completed"),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsReadFailed:($)=>W(`Failed to read ${$}`),loadingTypeScriptConfiguration:()=>W("Loading TypeScript configuration"),binarySearchStarted:($,M)=>W(`Searching for tool providing binary '${$}' in ${M}`),binaryNotFound:($)=>W(`No tool provides binary '${$}'`),binaryFoundInTool:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),multipleBinaryProviders:($,M)=>W(`Multiple tools provide binary '${$}': ${M.join(", ")}`)};function A1($){if(typeof $!=="object"||$===null)return!1;return"name"in $}function E1($){return typeof $==="function"}function K6($){if(A1($))return $;return null}async function F1($,M,J,Q,Y,G,X){let Z=vJ.dirname(Q),q=R0(Y,G,J,Z,X,M),I=P9(M,J,q),U=await $(I,q);if(U&&typeof U==="object"&&"name"in U)return K6(U);if(U&&typeof U==="object"&&"build"in U&&typeof U.build==="function"){let K=U.build();return K6(K)}return M.error(p.configurationParseError(Q,"ToolConfig","Invalid return from configuration function")),null}function L1($,M,J,Q){let Y=K6($);if(Y){if(Y.name!==Q)M.warn(p.configurationFieldInvalid("tool config object name",Y.name,`filename: ${Q}`),J)}return Y}async function x1($,M,J,Q,Y,G){try{let X=await import(M);if(!X.default)return $.error(p.configurationParseError(M,"ToolConfig","no default export")),null;let Z,q=X.default;if(E1(q))Z=await F1(q,$,J,M,Q,Y,G);else Z=L1(q,$,M,J);if(Z)Z.configFilePath=M;return Z}catch(X){let Z=X instanceof Error?X.message:JSON.stringify(X);return $.error(p.configurationLoadFailed(vJ.relative(Q.configFileDir,M)),Z),null}}function T1($,M,J,Q){if(M?.name)Q[M.name]=M,$.debug(p.configurationLoaded(J,1),M.name);else if(M)$.warn(p.configurationFieldInvalid("tool config","missing name","valid name property"),J);else $.error(p.configurationParseError(J,"ToolConfig","Could not derive valid configuration"))}async function C9($,M,J){let Q=[];try{let Y=await $.readdir(M);for(let G of Y){let X=vJ.join(M,G);try{if((await $.stat(X)).isDirectory()){let q=await C9($,X,J);Q.push(...q)}else if(G.endsWith(".tool.ts")){let q=vJ.basename(G,".tool.ts");Q.push({filePath:X,toolName:q})}}catch(Z){J.debug(p.fsReadFailed(X),Z)}}}catch(Y){J.debug(p.fsReadFailed(M),Y)}return Q}async function yJ($,M,J,Q,Y,G){let X=$.getSubLogger({name:"loadToolConfigs"}),Z={};if(G)X.debug(p.singleToolConfigLoadingStarted(G,M));else X.debug(p.toolConfigLoadingStarted(M));try{if(!await J.exists(M))return X.debug(p.fsItemNotFound("tool configs directory",M)),{};X.trace(p.toolConfigDirectoryScan(M));let q=await C9(J,M,X),I=G?q.filter(({toolName:U})=>U===G):q;for(let{filePath:U,toolName:K}of I){let H=await x1(X,U,K,Q,Y,J);T1(X,H,U,Z)}}catch(q){return X.error(p.fsReadFailed(M),q),{}}return Z}async function H6($,M,J,Q,Y,G){return(await yJ($,J,Q,Y,G,M))[M]}function k1($){if(typeof $==="string")return $;return $.name}async function S1($,M,J,Q,Y,G){let X=$.getSubLogger({name:"findToolByBinary",context:M});X.debug(p.binarySearchStarted(M,J));let Z=await yJ(X,J,Q,Y,G),q=[];for(let[K,H]of Object.entries(Z)){if(!H.binaries)continue;if(H.binaries.some((O)=>k1(O)===M))q.push(K)}if(q.length===0)return X.debug(p.binaryNotFound(M)),{success:!1,error:`No tool provides binary '${M}'`};if(q.length>1)return X.debug(p.multipleBinaryProviders(M,q)),{success:!1,error:`Multiple tools provide the binary '${M}': ${q.join(", ")}. Please specify the tool name instead.`,matchingTools:q};let I=q[0];if(!I)return{success:!1,error:`No tool provides binary '${M}'`};return X.debug(p.binaryFoundInTool(M,I)),{success:!0,toolName:I}}async function d9($,M,J,Q,Y,G){let X=$.getSubLogger({name:"loadToolConfigByBinary"}),Z=await S1(X,M,J,Q,Y,G);if(!Z.success){if(Z.matchingTools)return{error:Z.error};return}return await H6(X,Z.toolName,J,Q,Y,G)}class _6{async loadSingleToolConfig($,M,J,Q,Y,G){return H6($,M,J,Q,Y,G)}async loadToolConfigByBinary($,M,J,Q,Y,G){return d9($,M,J,Q,Y,G)}async loadToolConfigs($,M,J,Q,Y){return yJ($,M,J,Q,Y)}}function w1($){return $}import g1 from"path";import R6 from"path";import{z as b1}from"zod";function xM($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function lM($){if(xM($))return $;return{}}function PJ($,M){let J={...$};for(let Q of Object.keys(M)){let Y=M[Q];if(Y===void 0)continue;let G=$[Q];if(xM(Y)&&xM(G)){J[Q]=PJ(G,Y);continue}J[Q]=Y}return J}function N1($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";default:return"unknown"}}function v1($){switch($){case 1:return"x86_64";case 2:return"arm64";default:return"unknown"}}function y1($,M,J){let Q=$.getSubLogger({name:"applyPlatformOverrides"}),Y=M.platform;if(!Array.isArray(Y)){let U={...M};return delete U.platform,U}let G=N1(J.platform),X=v1(J.arch);Q.debug(p.platformOverrides(G,X));let Z={macos:2,linux:1,windows:4}[G]??0,q={x86_64:1,arm64:2}[X]??0,I=PJ({},M);for(let U of Y){if(!xM(U))continue;let{match:K,config:H}=U;if(!Array.isArray(K)||!xM(H))continue;if(K.some((O)=>{if(!xM(O))return!1;let{os:B,arch:j}=O,V=typeof B==="string"?{macos:2,linux:1,windows:4}[B]??0:0,D=typeof j==="string"?{x86_64:1,arm64:2}[j]??0:0,A=typeof B!=="string"||rM(V,Z),T=typeof j!=="string"||tM(D,q);return A&&T}))I=PJ(I,H)}return delete I.platform,I}function P1($,M){let J=$.split("."),Q=M;for(let Y of J){if(!xM(Q))return;if(!(Y in Q))return;Q=Q[Y]}if(typeof Q==="string")return Q;return}function C1($,M,J){let Q=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g;return $.replace(Q,(G,X)=>{if(X.includes("."))return P1(X,J)??G;return M[X]??G})}function u9($){let M=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,J=[];for(let Y of $.matchAll(M)){let G=Y[1];if(typeof G!=="string")continue;J.push(`{${G}}`)}return[...new Set(J)].toSorted((Y,G)=>Y.localeCompare(G))}function p9($,M,J){let Y=$,G=new Set([Y]);for(let q=0;q<20;q++){let I=C1(Y,M,J);if(I===Y)return Y;if(G.has(I)){let U=u9(I),K=U.length>0?` Possible cyclic/unresolved tokens: ${U.join(", ")}.`:"";throw Error(`String token substitution did not converge due to a cycle.${K}`)}G.add(I),Y=I}let X=u9(Y),Z=X.length>0?` Remaining tokens after 20 iterations: ${X.join(", ")}.`:"";throw Error(`String token substitution did not converge after 20 iterations.${Z}`)}function O6($,M,J){if(typeof $==="string")return p9($,M,J);if(Array.isArray($))return $.map((Y)=>O6(Y,M,J));if(xM($)){let Q={};for(let[Y,G]of Object.entries($))Q[Y]=O6(G,M,J);return Q}return $}function d1($,M){let Q=$,Y="";for(let G=0;G<20;G++){let X=JSON.stringify(Q);if(X===Y)break;Y=X;let Z=O6(Q,M,Q);Q=lM(Z)}return Q}function u1($,M){let J=$.paths,Q=lM(J),Y={};for(let[X,Z]of Object.entries(Q)){if(typeof Z==="string"){Y[X]=n(M,Z);continue}Y[X]=Z}return{...$,paths:Y}}function f1($,M){let J=$.paths,Q=lM(J),Y={};for(let[X,Z]of Object.entries(Q)){if(typeof Z!=="string"){Y[X]=Z;continue}Y[X]=R6.isAbsolute(Z)?Z:R6.resolve(M,Z)}return{...$,paths:Y}}function p1($){let M=$.paths,J=lM(M);for(let Q of Object.values(J)){if(typeof Q!=="string")continue;if(Q.startsWith("~"))throw Error("Configuration contains unsupported tilde path in paths.*")}}function c1($,M,J){let Q=$.paths,G=lM(Q).homeDir,Z=p9(typeof G==="string"?G:"{HOME}",M,$);return n(J,Z)}function f9($,M){let J={...$};for(let[Q,Y]of Object.entries(M))J[Q]=Y;return J}function h1($,M,J,Q,Y,G){let X=$.getSubLogger({name:"processConfig"});X.debug(p.configurationProcessing(),M);let Z=PJ(J,Q),q=y1($,Z,Y),I=R6.dirname(M),U={...q,configFilePath:M,configFileDir:I},K=f9(G,{HOME:Y.homeDir,configFileDir:I}),H=c1(U,K,Y.homeDir),_={...lM(U.paths),homeDir:H},O={...U,paths:_},B=f9(G,{HOME:H,configFileDir:I}),j=d1(O,B),V=u1(j,H);p1(V);let D=f1(V,I),A=ZQ.extend(GY.shape).safeParse(D);if(!A.success){let T=b1.prettifyError(A.error);throw X.error(p.configurationValidationFailed([T])),Error(`Project configuration is invalid.
143
- ${T}`)}return A.data}async function m1($){return ZQ.parse({})}async function c9($,M,J={},Q={platform:2,arch:2,homeDir:"/Users/testuser",hostname:"test-host"},Y={},G){let X=G.userConfigPath,Z=await m1(M),q=lM(J);return h1($,X,Z,q,Q,Y)}function h9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n1($){if(!h9($))return!1;return"default"in $}function i1($){return typeof $==="function"}function l1($){return $ instanceof Promise}function a1($){let M={};return Object.assign(M,$),M}async function m9($,M,J,Q,Y){let G=$.getSubLogger({name:"loadTsConfig"});if(!await M.exists(J))G.error(p.fsItemNotFound("Config file",J)),N(1);let X={};try{let Z=await import(J);if(!n1(Z)||!Z.default)G.error(p.configurationParseError(J,"TypeScript","no default export")),N(1);let I={configFileDir:g1.dirname(J),systemInfo:Q},U=Z.default,K=i1(U)?U(I):U,H=l1(K)?await K:K;if(h9(H))X=a1(H);else G.error(p.configurationParseError(J,"TypeScript","default export must be an object, function or Promise")),N(1)}catch(Z){G.error(p.configurationParseError(J,"TypeScript",Z instanceof Error?Z.message:String(Z))),N(1)}return c9(G,M,X,Q,Y,{userConfigPath:J})}async function g9($,M,J,Q,Y){let G=$.getSubLogger({name:"loadConfig"});if(J.endsWith(".ts"))return G.debug(p.loadingTypeScriptConfiguration()),m9(G,M,J,Q,Y);throw Error(`Unsupported configuration file type: ${J}. Configuration must use .ts extension.`)}var w0=604800000,n9="https://raw.githubusercontent.com",i9="README.md";var C={fetchingReadme:($,M,J)=>W(`Fetching README for ${$}/${M}@${J}`),readmeFetched:($,M,J,Q)=>W(`README fetched for ${$}/${M}@${J} (${Q} characters)`),readmeNotFound:($,M,J,Q)=>W(`README not found for ${$}/${M}@${J} at ${Q}`),readmeCacheHit:($,M,J)=>W(`README cache hit for ${$}/${M}@${J}`),readmeCacheMiss:($,M,J)=>W(`README cache miss for ${$}/${M}@${J}`),readmeCached:($,M,J,Q)=>W(`README cached for ${$}/${M}@${J} with TTL ${Q}ms`),generatingCombinedReadme:($)=>W(`Generating combined README for ${$} tools`),combinedReadmeGenerated:($,M)=>W(`Combined README generated for ${$} tools (${M} characters)`),fetchingInstalledTools:()=>W("Fetching installed GitHub tools from registry"),installedToolsFound:($)=>W(`Found ${$} GitHub tools in registry`),githubToolsExtracted:($)=>W(`Extracted ${$} GitHub tools from configurations`),clearingExpiredCache:()=>W("Clearing expired README cache entries"),cacheCleared:($)=>W(`Cleared ${$} expired README cache entries`),fetchError:($,M,J,Q)=>W(`Error fetching README for ${$}/${M}@${J}: ${Q}`),cacheError:($,M,J)=>W(`Cache ${$} error for ${M}: ${J}`),urlConstruction:($)=>W(`Constructed README URL: ${$}`),serviceInitialized:()=>W("README service initialized"),serviceDestroyed:()=>W("README service destroyed"),writingReadmeToPath:($,M,J)=>W(`Writing README for ${$}@${M} to ${J}`),readmeWritten:($,M,J,Q)=>W(`README written for ${$}@${M} to ${J} (${Q} characters)`),readmeWriteError:($,M,J,Q)=>W(`Error writing README for ${$}@${M} to ${J}: ${Q}`),readmeNotAvailableForWrite:($,M)=>W(`README not available for ${$}@${M}, skipping write`),catalogGeneration:{started:($)=>W(`Starting catalog generation at ${$}`),completed:($,M)=>W(`Catalog generated at ${$} (${M} characters)`),failed:($,M)=>W(`Failed to generate catalog at ${$}: ${M}`),noGitHubTools:()=>W("No GitHub tools installed. Run the generate command to install tools before generating a catalog.")}};class j6{logger;cache;defaultTtl;constructor($,M,J=w0){this.logger=$.getSubLogger({name:"ReadmeCache"}),this.cache=M,this.defaultTtl=J}async get($){try{let M=await this.cache.get($);if(M)this.logger.debug(C.readmeCacheHit(M.owner,M.repo,M.version));return M}catch(M){return this.logger.error(C.cacheError("get",$,M instanceof Error?M.message:String(M))),null}}async set($,M,J=this.defaultTtl){try{await this.cache.set($,M,J),this.logger.debug(C.readmeCached(M.owner,M.repo,M.version,J))}catch(Q){this.logger.error(C.cacheError("set",$,Q instanceof Error?Q.message:String(Q)))}}async has($){try{return await this.cache.has($)}catch(M){return this.logger.error(C.cacheError("has",$,M instanceof Error?M.message:String(M))),!1}}async delete($){try{await this.cache.delete($)}catch(M){this.logger.error(C.cacheError("delete",$,M instanceof Error?M.message:String(M)))}}async clearExpired(){try{this.logger.debug(C.clearingExpiredCache()),await this.cache.clearExpired(),this.logger.debug(C.cacheCleared(0))}catch($){this.logger.error(C.cacheError("clearExpired","all",$ instanceof Error?$.message:String($)))}}generateCacheKey($,M,J){return`readme:${$}/${M}:${J}`}}import s1 from"path";class V6{logger;downloader;registry;fileSystem;catalogFileSystem;readmeCache;pluginRegistry;constructor($,M,J,Q,Y,G,X){this.logger=$.getSubLogger({name:"ReadmeService"}),this.downloader=M,this.registry=J,this.fileSystem=Q,this.catalogFileSystem=Y,this.pluginRegistry=X;let Z=new MM(this.logger,Q,{enabled:!0,defaultTtl:w0,cacheDir:G,storageStrategy:"json"});this.readmeCache=new j6(this.logger,Z),this.logger.debug(C.serviceInitialized())}async fetchReadmeForVersion($,M,J,Q){let Y=this.readmeCache.generateCacheKey($,M,J),G=await this.readmeCache.get(Y);if(G)return G;this.logger.debug(C.readmeCacheMiss($,M,J));let X=this.constructReadmeUrl($,M,J);this.logger.debug(C.urlConstruction(X));try{this.logger.debug(C.fetchingReadme($,M,J));let Z=await this.downloader.download(this.logger,X);if(!Z)return this.logger.debug(C.readmeNotFound($,M,J,X)),null;let q=Z.toString("utf-8"),I={content:q,toolName:Q,owner:$,repo:M,version:J,sourceUrl:X,fetchedAt:Date.now()};return this.logger.debug(C.readmeFetched($,M,J,q.length)),await this.readmeCache.set(Y,I,w0),I}catch(Z){return this.logger.error(C.fetchError($,M,J,"Download failed"),Z),null}}async getCachedReadme($,M,J){let Q=this.readmeCache.generateCacheKey($,M,J);return await this.readmeCache.get(Q)}async generateCombinedReadme($={}){let M=await this.getGitHubTools();this.logger.debug(C.generatingCombinedReadme(M.length));let J={title:$.title||"Installed Tools",includeTableOfContents:$.includeTableOfContents??!0,includeVersions:$.includeVersions??!0},Q=[];if(Q.push(`# ${J.title}
144
- `),M.length===0)return Q.push(`No GitHub tools are currently installed.
145
- `),Q.join(`
146
- `);if(J.includeTableOfContents)this.addTableOfContents(Q,M,J.includeVersions);await this.addToolSections(Q,M,J);let Y=Q.join(`
147
- `);return this.logger.debug(C.combinedReadmeGenerated(M.length,Y.length)),Y}addTableOfContents($,M,J){$.push(`## Table of Contents
148
- `);for(let Q of M){let Y=J?` (${Q.version})`:"";$.push(`- [${Q.toolName}${Y}](#${Q.toolName.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addToolSections($,M,J){for(let Q of M){let Y=Q.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(!Y)continue;let[,G,X]=Y;if(!G||!X)continue;let Z=Q.originalTag||Q.configuredVersion||Q.version,q=Z==="latest"?"main":Z,I=await this.fetchReadmeForVersion(G,X,q,Q.toolName),U=J.includeVersions?` (${Q.version})`:"";if($.push(`## ${Q.toolName}${U}
149
- `),I)this.addToolWithReadme($,Q,I);else this.addToolWithoutReadme($,G,X)}}addToolWithReadme($,M,J){$.push(J.content);let Q=M.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(Q){let[,Y,G]=Q;$.push(`
150
- **Source:** [${Y}/${G}](https://github.com/${Y}/${G})
151
- `)}}addToolWithoutReadme($,M,J){$.push(`**Repository:** [${M}/${J}](https://github.com/${M}/${J})
142
+ `)}`),configurationParseError:($,I,M)=>Z(`Failed to parse ${I} configuration ${$}: ${M}`),configurationLoadFailed:($)=>Z(`Failed to load configuration: ${$}`),configurationLoaded:($,I)=>Z(`Configuration loaded from ${$} (${I} tools configured)`),toolConfigLoadingStarted:($)=>Z(`tool config loading: ${$}`),singleToolConfigLoadingStarted:($,I)=>Z(`single tool config load: ${$} in ${I}`),toolConfigDirectoryScan:($)=>Z(`Directory scan: ${$}`),toolConfigLoadingCompleted:()=>Z("tool config loading completed"),configurationFieldInvalid:($,I,M)=>Z(`Invalid ${$}: "${I}" (expected ${M})`),fsItemNotFound:($,I)=>Z(`${$} not found: ${I}`),fsReadFailed:($)=>Z(`Failed to read ${$}`),loadingTypeScriptConfiguration:()=>Z("Loading TypeScript configuration"),binarySearchStarted:($,I)=>Z(`Searching for tool providing binary '${$}' in ${I}`),binaryNotFound:($)=>Z(`No tool provides binary '${$}'`),binaryFoundInTool:($,I)=>Z(`Binary '${$}' is provided by tool '${I}'`),multipleBinaryProviders:($,I)=>Z(`Multiple tools provide binary '${$}': ${I.join(", ")}`)};function w7($){if(typeof $!=="object"||$===null)return!1;return"name"in $}function b7($){return typeof $==="function"}function H6($){if(w7($))return $;return null}async function N7($,I,M,G,J,Q,Y){let X=P0.dirname(G),R=zM(J,Q,M,X,Y,I),W=dQ(I,M,R),q=await $(W,R);if(q&&typeof q==="object"&&"name"in q)return H6(q);if(q&&typeof q==="object"&&"build"in q&&typeof q.build==="function"){let U=q.build();return H6(U)}return I.error(p.configurationParseError(G,"ToolConfig","Invalid return from configuration function")),null}function y7($,I,M,G){let J=H6($);if(J){if(J.name!==G)I.warn(p.configurationFieldInvalid("tool config object name",J.name,`filename: ${G}`),M)}return J}async function v7($,I,M,G,J,Q){try{let Y=await import(I);if(!Y.default)return $.error(p.configurationParseError(I,"ToolConfig","no default export")),null;let X,R=Y.default;if(b7(R))X=await N7(R,$,M,I,G,J,Q);else X=y7(R,$,I,M);if(X)X.configFilePath=I;return X}catch(Y){let X=Y instanceof Error?Y.message:JSON.stringify(Y);return $.error(p.configurationLoadFailed(P0.relative(G.configFileDir,I)),X),null}}function P7($,I,M,G){if(I?.name)G[I.name]=I,$.debug(p.configurationLoaded(M,1),I.name);else if(I)$.warn(p.configurationFieldInvalid("tool config","missing name","valid name property"),M);else $.error(p.configurationParseError(M,"ToolConfig","Could not derive valid configuration"))}async function uQ($,I,M){let G=[];try{let J=await $.readdir(I);for(let Q of J){let Y=P0.join(I,Q);try{if((await $.stat(Y)).isDirectory()){let R=await uQ($,Y,M);G.push(...R)}else if(Q.endsWith(".tool.ts")){let R=P0.basename(Q,".tool.ts");G.push({filePath:Y,toolName:R})}}catch(X){M.debug(p.fsReadFailed(Y),X)}}}catch(J){M.debug(p.fsReadFailed(I),J)}return G}async function C0($,I,M,G,J,Q){let Y=$.getSubLogger({name:"loadToolConfigs"}),X={};if(Q)Y.debug(p.singleToolConfigLoadingStarted(Q,I));else Y.debug(p.toolConfigLoadingStarted(I));try{if(!await M.exists(I))return Y.debug(p.fsItemNotFound("tool configs directory",I)),{};Y.trace(p.toolConfigDirectoryScan(I));let R=await uQ(M,I,Y),W=Q?R.filter(({toolName:q})=>q===Q):R;for(let{filePath:q,toolName:U}of W){let H=await v7(Y,q,U,G,J,M);P7(Y,H,q,X)}}catch(R){return Y.error(p.fsReadFailed(I),R),{}}return X}async function K6($,I,M,G,J,Q){return(await C0($,M,G,J,Q,I))[I]}function C7($){if(typeof $==="string")return $;return $.name}async function d7($,I,M,G,J,Q){let Y=$.getSubLogger({name:"findToolByBinary",context:I});Y.debug(p.binarySearchStarted(I,M));let X=await C0(Y,M,G,J,Q),R=[];for(let[U,H]of Object.entries(X)){if(!H.binaries)continue;if(H.binaries.some((O)=>C7(O)===I))R.push(U)}if(R.length===0)return Y.debug(p.binaryNotFound(I)),{success:!1,error:`No tool provides binary '${I}'`};if(R.length>1)return Y.debug(p.multipleBinaryProviders(I,R)),{success:!1,error:`Multiple tools provide the binary '${I}': ${R.join(", ")}. Please specify the tool name instead.`,matchingTools:R};let W=R[0];if(!W)return{success:!1,error:`No tool provides binary '${I}'`};return Y.debug(p.binaryFoundInTool(I,W)),{success:!0,toolName:W}}async function fQ($,I,M,G,J,Q){let Y=$.getSubLogger({name:"loadToolConfigByBinary"}),X=await d7(Y,I,M,G,J,Q);if(!X.success){if(X.matchingTools)return{error:X.error};return}return await K6(Y,X.toolName,M,G,J,Q)}class _6{async loadSingleToolConfig($,I,M,G,J,Q){return K6($,I,M,G,J,Q)}async loadToolConfigByBinary($,I,M,G,J,Q){return fQ($,I,M,G,J,Q)}async loadToolConfigs($,I,M,G,J){return C0($,I,M,G,J)}}function u7($){return $}import o7 from"path";import O6 from"path";import{z as f7}from"zod";function SI($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function rI($){if(SI($))return $;return{}}function d0($,I){let M={...$};for(let G of Object.keys(I)){let J=I[G];if(J===void 0)continue;let Q=$[G];if(SI(J)&&SI(Q)){M[G]=d0(Q,J);continue}M[G]=J}return M}function p7($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";default:return"unknown"}}function c7($){switch($){case 1:return"x86_64";case 2:return"arm64";default:return"unknown"}}function h7($,I,M){let G=$.getSubLogger({name:"applyPlatformOverrides"}),J=I.platform;if(!Array.isArray(J)){let q={...I};return delete q.platform,q}let Q=p7(M.platform),Y=c7(M.arch);G.debug(p.platformOverrides(Q,Y));let X={macos:2,linux:1,windows:4}[Q]??0,R={x86_64:1,arm64:2}[Y]??0,W=d0({},I);for(let q of J){if(!SI(q))continue;let{match:U,config:H}=q;if(!Array.isArray(U)||!SI(H))continue;if(U.some((O)=>{if(!SI(O))return!1;let{os:B,arch:j}=O,V=typeof B==="string"?{macos:2,linux:1,windows:4}[B]??0:0,x=typeof j==="string"?{x86_64:1,arm64:2}[j]??0:0,A=typeof B!=="string"||oI(V,X),T=typeof j!=="string"||eI(x,R);return A&&T}))W=d0(W,H)}return delete W.platform,W}function m7($,I){let M=$.split("."),G=I;for(let J of M){if(!SI(G))return;if(!(J in G))return;G=G[J]}if(typeof G==="string")return G;return}function g7($,I,M){let G=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g;return $.replace(G,(Q,Y)=>{if(Y.includes("."))return m7(Y,M)??Q;return I[Y]??Q})}function pQ($){let I=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,M=[];for(let J of $.matchAll(I)){let Q=J[1];if(typeof Q!=="string")continue;M.push(`{${Q}}`)}return[...new Set(M)].toSorted((J,Q)=>J.localeCompare(Q))}function hQ($,I,M){let J=$,Q=new Set([J]);for(let R=0;R<20;R++){let W=g7(J,I,M);if(W===J)return J;if(Q.has(W)){let q=pQ(W),U=q.length>0?` Possible cyclic/unresolved tokens: ${q.join(", ")}.`:"";throw Error(`String token substitution did not converge due to a cycle.${U}`)}Q.add(W),J=W}let Y=pQ(J),X=Y.length>0?` Remaining tokens after 20 iterations: ${Y.join(", ")}.`:"";throw Error(`String token substitution did not converge after 20 iterations.${X}`)}function j6($,I,M){if(typeof $==="string")return hQ($,I,M);if(Array.isArray($))return $.map((J)=>j6(J,I,M));if(SI($)){let G={};for(let[J,Q]of Object.entries($))G[J]=j6(Q,I,M);return G}return $}function n7($,I){let G=$,J="";for(let Q=0;Q<20;Q++){let Y=JSON.stringify(G);if(Y===J)break;J=Y;let X=j6(G,I,G);G=rI(X)}return G}function i7($,I){let M=$.paths,G=rI(M),J={};for(let[Y,X]of Object.entries(G)){if(typeof X==="string"){J[Y]=n(I,X);continue}J[Y]=X}return{...$,paths:J}}function l7($,I){let M=$.paths,G=rI(M),J={};for(let[Y,X]of Object.entries(G)){if(typeof X!=="string"){J[Y]=X;continue}J[Y]=O6.isAbsolute(X)?X:O6.resolve(I,X)}return{...$,paths:J}}function a7($){let I=$.paths,M=rI(I);for(let G of Object.values(M)){if(typeof G!=="string")continue;if(G.startsWith("~"))throw Error("Configuration contains unsupported tilde path in paths.*")}}function r7($,I,M){let G=$.paths,Q=rI(G).homeDir,X=hQ(typeof Q==="string"?Q:"{HOME}",I,$);return n(M,X)}function cQ($,I){let M={...$};for(let[G,J]of Object.entries(I))M[G]=J;return M}function s7($,I,M,G,J,Q){let Y=$.getSubLogger({name:"processConfig"});Y.debug(p.configurationProcessing(),I);let X=d0(M,G),R=h7($,X,J),W=O6.dirname(I),q={...R,configFilePath:I,configFileDir:W},U=cQ(Q,{HOME:J.homeDir,configFileDir:W}),H=r7(q,U,J.homeDir),K={...rI(q.paths),homeDir:H},O={...q,paths:K},B=cQ(Q,{HOME:H,configFileDir:W}),j=n7(O,B),V=i7(j,H);a7(V);let x=l7(V,W),A=ZG.extend(XJ.shape).safeParse(x);if(!A.success){let T=f7.prettifyError(A.error);throw Y.error(p.configurationValidationFailed([T])),Error(`Project configuration is invalid.
143
+ ${T}`)}return A.data}async function t7($){return ZG.parse({})}async function mQ($,I,M={},G={platform:2,arch:2,homeDir:"/Users/testuser",hostname:"test-host"},J={},Q){let Y=Q.userConfigPath,X=await t7(I),R=rI(M);return s7($,Y,X,R,G,J)}function gQ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e7($){if(!gQ($))return!1;return"default"in $}function $X($){return typeof $==="function"}function IX($){return $ instanceof Promise}function MX($){let I={};return Object.assign(I,$),I}async function nQ($,I,M,G,J){let Q=$.getSubLogger({name:"loadTsConfig"});if(!await I.exists(M))Q.error(p.fsItemNotFound("Config file",M)),y(1);let Y={};try{let X=await import(M);if(!e7(X)||!X.default)Q.error(p.configurationParseError(M,"TypeScript","no default export")),y(1);let W={configFileDir:o7.dirname(M),systemInfo:G},q=X.default,U=$X(q)?q(W):q,H=IX(U)?await U:U;if(gQ(H))Y=MX(H);else Q.error(p.configurationParseError(M,"TypeScript","default export must be an object, function or Promise")),y(1)}catch(X){Q.error(p.configurationParseError(M,"TypeScript",X instanceof Error?X.message:String(X))),y(1)}return mQ(Q,I,Y,G,J,{userConfigPath:M})}async function iQ($,I,M,G,J){let Q=$.getSubLogger({name:"loadConfig"});if(M.endsWith(".ts"))return Q.debug(p.loadingTypeScriptConfiguration()),nQ(Q,I,M,G,J);throw Error(`Unsupported configuration file type: ${M}. Configuration must use .ts extension.`)}var vM=604800000,lQ="https://raw.githubusercontent.com",aQ="README.md";var C={fetchingReadme:($,I,M)=>Z(`Fetching README for ${$}/${I}@${M}`),readmeFetched:($,I,M,G)=>Z(`README fetched for ${$}/${I}@${M} (${G} characters)`),readmeNotFound:($,I,M,G)=>Z(`README not found for ${$}/${I}@${M} at ${G}`),readmeCacheHit:($,I,M)=>Z(`README cache hit for ${$}/${I}@${M}`),readmeCacheMiss:($,I,M)=>Z(`README cache miss for ${$}/${I}@${M}`),readmeCached:($,I,M,G)=>Z(`README cached for ${$}/${I}@${M} with TTL ${G}ms`),generatingCombinedReadme:($)=>Z(`Generating combined README for ${$} tools`),combinedReadmeGenerated:($,I)=>Z(`Combined README generated for ${$} tools (${I} characters)`),fetchingInstalledTools:()=>Z("Fetching installed GitHub tools from registry"),installedToolsFound:($)=>Z(`Found ${$} GitHub tools in registry`),githubToolsExtracted:($)=>Z(`Extracted ${$} GitHub tools from configurations`),clearingExpiredCache:()=>Z("Clearing expired README cache entries"),cacheCleared:($)=>Z(`Cleared ${$} expired README cache entries`),fetchError:($,I,M,G)=>Z(`Error fetching README for ${$}/${I}@${M}: ${G}`),cacheError:($,I,M)=>Z(`Cache ${$} error for ${I}: ${M}`),urlConstruction:($)=>Z(`Constructed README URL: ${$}`),serviceInitialized:()=>Z("README service initialized"),serviceDestroyed:()=>Z("README service destroyed"),writingReadmeToPath:($,I,M)=>Z(`Writing README for ${$}@${I} to ${M}`),readmeWritten:($,I,M,G)=>Z(`README written for ${$}@${I} to ${M} (${G} characters)`),readmeWriteError:($,I,M,G)=>Z(`Error writing README for ${$}@${I} to ${M}: ${G}`),readmeNotAvailableForWrite:($,I)=>Z(`README not available for ${$}@${I}, skipping write`),catalogGeneration:{started:($)=>Z(`Starting catalog generation at ${$}`),completed:($,I)=>Z(`Catalog generated at ${$} (${I} characters)`),failed:($,I)=>Z(`Failed to generate catalog at ${$}: ${I}`),noGitHubTools:()=>Z("No GitHub tools installed. Run the generate command to install tools before generating a catalog.")}};class V6{logger;cache;defaultTtl;constructor($,I,M=vM){this.logger=$.getSubLogger({name:"ReadmeCache"}),this.cache=I,this.defaultTtl=M}async get($){try{let I=await this.cache.get($);if(I)this.logger.debug(C.readmeCacheHit(I.owner,I.repo,I.version));return I}catch(I){return this.logger.error(C.cacheError("get",$,I instanceof Error?I.message:String(I))),null}}async set($,I,M=this.defaultTtl){try{await this.cache.set($,I,M),this.logger.debug(C.readmeCached(I.owner,I.repo,I.version,M))}catch(G){this.logger.error(C.cacheError("set",$,G instanceof Error?G.message:String(G)))}}async has($){try{return await this.cache.has($)}catch(I){return this.logger.error(C.cacheError("has",$,I instanceof Error?I.message:String(I))),!1}}async delete($){try{await this.cache.delete($)}catch(I){this.logger.error(C.cacheError("delete",$,I instanceof Error?I.message:String(I)))}}async clearExpired(){try{this.logger.debug(C.clearingExpiredCache()),await this.cache.clearExpired(),this.logger.debug(C.cacheCleared(0))}catch($){this.logger.error(C.cacheError("clearExpired","all",$ instanceof Error?$.message:String($)))}}generateCacheKey($,I,M){return`readme:${$}/${I}:${M}`}}import GX from"path";class z6{logger;downloader;registry;fileSystem;catalogFileSystem;readmeCache;pluginRegistry;constructor($,I,M,G,J,Q,Y){this.logger=$.getSubLogger({name:"ReadmeService"}),this.downloader=I,this.registry=M,this.fileSystem=G,this.catalogFileSystem=J,this.pluginRegistry=Y;let X=new JI(this.logger,G,{enabled:!0,defaultTtl:vM,cacheDir:Q,storageStrategy:"json"});this.readmeCache=new V6(this.logger,X),this.logger.debug(C.serviceInitialized())}async fetchReadmeForVersion($,I,M,G){let J=this.readmeCache.generateCacheKey($,I,M),Q=await this.readmeCache.get(J);if(Q)return Q;this.logger.debug(C.readmeCacheMiss($,I,M));let Y=this.constructReadmeUrl($,I,M);this.logger.debug(C.urlConstruction(Y));try{this.logger.debug(C.fetchingReadme($,I,M));let X=await this.downloader.download(this.logger,Y);if(!X)return this.logger.debug(C.readmeNotFound($,I,M,Y)),null;let R=X.toString("utf-8"),W={content:R,toolName:G,owner:$,repo:I,version:M,sourceUrl:Y,fetchedAt:Date.now()};return this.logger.debug(C.readmeFetched($,I,M,R.length)),await this.readmeCache.set(J,W,vM),W}catch(X){return this.logger.error(C.fetchError($,I,M,"Download failed"),X),null}}async getCachedReadme($,I,M){let G=this.readmeCache.generateCacheKey($,I,M);return await this.readmeCache.get(G)}async generateCombinedReadme($={}){let I=await this.getGitHubTools();this.logger.debug(C.generatingCombinedReadme(I.length));let M={title:$.title||"Installed Tools",includeTableOfContents:$.includeTableOfContents??!0,includeVersions:$.includeVersions??!0},G=[];if(G.push(`# ${M.title}
144
+ `),I.length===0)return G.push(`No GitHub tools are currently installed.
145
+ `),G.join(`
146
+ `);if(M.includeTableOfContents)this.addTableOfContents(G,I,M.includeVersions);await this.addToolSections(G,I,M);let J=G.join(`
147
+ `);return this.logger.debug(C.combinedReadmeGenerated(I.length,J.length)),J}addTableOfContents($,I,M){$.push(`## Table of Contents
148
+ `);for(let G of I){let J=M?` (${G.version})`:"";$.push(`- [${G.toolName}${J}](#${G.toolName.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addToolSections($,I,M){for(let G of I){let J=G.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(!J)continue;let[,Q,Y]=J;if(!Q||!Y)continue;let X=G.originalTag||G.configuredVersion||G.version,R=X==="latest"?"main":X,W=await this.fetchReadmeForVersion(Q,Y,R,G.toolName),q=M.includeVersions?` (${G.version})`:"";if($.push(`## ${G.toolName}${q}
149
+ `),W)this.addToolWithReadme($,G,W);else this.addToolWithoutReadme($,Q,Y)}}addToolWithReadme($,I,M){$.push(M.content);let G=I.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(G){let[,J,Q]=G;$.push(`
150
+ **Source:** [${J}/${Q}](https://github.com/${J}/${Q})
151
+ `)}}addToolWithoutReadme($,I,M){$.push(`**Repository:** [${I}/${M}](https://github.com/${I}/${M})
152
152
  `),$.push(`*README not available*
153
- `)}async getGitHubTools(){this.logger.debug(C.fetchingInstalledTools());try{let M=(await this.registry.getAllToolInstallations()).filter((J)=>{return J.downloadUrl?.includes("github.com")||J.downloadUrl?.includes("api.github.com")});return this.logger.debug(C.installedToolsFound(M.length)),M}catch($){return this.logger.error(C.fetchError("registry","tools","unknown","Failed to get installed tools"),$),[]}}async clearExpiredCache(){await this.readmeCache.clearExpired()}async writeReadmeToPath($,M,J,Q,Y){try{let G=await this.fetchReadmeForVersion(Q,Y,J,M);if(!G)return this.logger.debug(C.readmeNotAvailableForWrite(M,J)),null;let Z=`${`${$}/${M}`}/${J}`,q=`${Z}/README.md`;return this.logger.debug(C.writingReadmeToPath(M,J,q)),await this.fileSystem.ensureDir(Z),await this.fileSystem.writeFile(q,G.content),this.logger.debug(C.readmeWritten(M,J,q,G.content.length)),q}catch(G){let X=`${$}/${M}/${J}/README.md`;return this.logger.error(C.readmeWriteError(M,J,X,"Write operation failed"),G),null}}constructReadmeUrl($,M,J){return`${n9}/${$}/${M}/${J}/${i9}`}async generateCatalogFromConfigs($,M,J={}){try{if(this.logger.debug(C.catalogGeneration.started($)),(await this.getGitHubTools()).length===0)return this.logger.warn(C.catalogGeneration.noGitHubTools()),null;let Y=await this.generateCatalogContentFromConfigs(M,J),G=s1.dirname($);return await this.fileSystem.ensureDir(G),await this.catalogFileSystem.writeFile($,Y),this.logger.debug(C.catalogGeneration.completed($,Y.length)),$}catch(Q){return this.logger.error(C.catalogGeneration.failed($,"Catalog generation failed"),Q),null}}async generateCatalogContentFromConfigs($,M={}){let J={title:M.title||"Tool Catalog",includeTableOfContents:M.includeTableOfContents??!0,includeVersions:M.includeVersions??!0},Q=[];Q.push(`# ${J.title}
154
- `);let Y=this.filterGitHubConfigs($);if(this.logger.debug(C.githubToolsExtracted(Y.length)),J.includeTableOfContents)this.addCatalogTableOfContents(Q,Y,J.includeVersions);return await this.addCatalogToolSections(Q,Y,J),Q.join(`
155
- `)}filterGitHubConfigs($){return Object.entries($).filter(([,M])=>{return this.pluginRegistry.get(M.installationMethod)?.supportsReadme?.()===!0})}addCatalogTableOfContents($,M,J){$.push(`## Table of Contents
156
- `);for(let[Q,Y]of M){let G=J?` (${Y.version||"main"})`:"";$.push(`- [${Q}${G}](#${Q.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addCatalogToolSections($,M,J){for(let[Q,Y]of M){if(Y.installationMethod!=="github-release")continue;let X=Y.installParams.repo,[Z,q]=X.split("/");if(!Z||!q)continue;let I=Y.version||"main",U=I==="latest"?"main":I,K=await this.fetchReadmeForVersion(Z,q,U,Q),H=J.includeVersions?` (${I})`:"";if($.push(`## ${Q}${H}
157
- `),K)this.addCatalogToolWithReadme($,K,X);else this.addCatalogToolWithoutReadme($,X)}}addCatalogToolWithReadme($,M,J){$.push(M.content),$.push(`
158
- **Source:** [${J}](https://github.com/${J})
159
- `)}addCatalogToolWithoutReadme($,M){$.push(`**Repository:** [${M}](https://github.com/${M})
153
+ `)}async getGitHubTools(){this.logger.debug(C.fetchingInstalledTools());try{let I=(await this.registry.getAllToolInstallations()).filter((M)=>{return M.downloadUrl?.includes("github.com")||M.downloadUrl?.includes("api.github.com")});return this.logger.debug(C.installedToolsFound(I.length)),I}catch($){return this.logger.error(C.fetchError("registry","tools","unknown","Failed to get installed tools"),$),[]}}async clearExpiredCache(){await this.readmeCache.clearExpired()}async writeReadmeToPath($,I,M,G,J){try{let Q=await this.fetchReadmeForVersion(G,J,M,I);if(!Q)return this.logger.debug(C.readmeNotAvailableForWrite(I,M)),null;let X=`${`${$}/${I}`}/${M}`,R=`${X}/README.md`;return this.logger.debug(C.writingReadmeToPath(I,M,R)),await this.fileSystem.ensureDir(X),await this.fileSystem.writeFile(R,Q.content),this.logger.debug(C.readmeWritten(I,M,R,Q.content.length)),R}catch(Q){let Y=`${$}/${I}/${M}/README.md`;return this.logger.error(C.readmeWriteError(I,M,Y,"Write operation failed"),Q),null}}constructReadmeUrl($,I,M){return`${lQ}/${$}/${I}/${M}/${aQ}`}async generateCatalogFromConfigs($,I,M={}){try{if(this.logger.debug(C.catalogGeneration.started($)),(await this.getGitHubTools()).length===0)return this.logger.warn(C.catalogGeneration.noGitHubTools()),null;let J=await this.generateCatalogContentFromConfigs(I,M),Q=GX.dirname($);return await this.fileSystem.ensureDir(Q),await this.catalogFileSystem.writeFile($,J),this.logger.debug(C.catalogGeneration.completed($,J.length)),$}catch(G){return this.logger.error(C.catalogGeneration.failed($,"Catalog generation failed"),G),null}}async generateCatalogContentFromConfigs($,I={}){let M={title:I.title||"Tool Catalog",includeTableOfContents:I.includeTableOfContents??!0,includeVersions:I.includeVersions??!0},G=[];G.push(`# ${M.title}
154
+ `);let J=this.filterGitHubConfigs($);if(this.logger.debug(C.githubToolsExtracted(J.length)),M.includeTableOfContents)this.addCatalogTableOfContents(G,J,M.includeVersions);return await this.addCatalogToolSections(G,J,M),G.join(`
155
+ `)}filterGitHubConfigs($){return Object.entries($).filter(([,I])=>{return this.pluginRegistry.get(I.installationMethod)?.supportsReadme?.()===!0})}addCatalogTableOfContents($,I,M){$.push(`## Table of Contents
156
+ `);for(let[G,J]of I){let Q=M?` (${J.version||"main"})`:"";$.push(`- [${G}${Q}](#${G.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addCatalogToolSections($,I,M){for(let[G,J]of I){if(J.installationMethod!=="github-release")continue;let Y=J.installParams.repo,[X,R]=Y.split("/");if(!X||!R)continue;let W=J.version||"main",q=W==="latest"?"main":W,U=await this.fetchReadmeForVersion(X,R,q,G),H=M.includeVersions?` (${W})`:"";if($.push(`## ${G}${H}
157
+ `),U)this.addCatalogToolWithReadme($,U,Y);else this.addCatalogToolWithoutReadme($,Y)}}addCatalogToolWithReadme($,I,M){$.push(I.content),$.push(`
158
+ **Source:** [${M}](https://github.com/${M})
159
+ `)}addCatalogToolWithoutReadme($,I){$.push(`**Repository:** [${I}](https://github.com/${I})
160
160
  `),$.push(`*README not available*
161
- `)}}import{randomUUID as z6}from"crypto";import J4 from"path";var v={constructor:{initialized:()=>W("Initializing GeneratorOrchestrator")},autoInstall:{completed:($)=>W(`Auto-installed: ${$}`)},generateAll:{parsedOptions:($)=>W(`Parsed ${$} tool configuration entries`),toolDisabled:($)=>W(`Skipping disabled tool: ${$}`),toolHostnameMismatch:($,M,J)=>W(`Skipping tool "${$}": hostname "${J}" does not match pattern "${M}"`),dependenciesValidationStarted:($)=>W(`Validating tool dependencies (${$} tools)`),dependenciesOrderResolved:($)=>W(`Dependency order resolved: ${$}`),missingDependency:($,M,J,Q)=>W(`Missing dependency: tool "${$}" requires binary "${M}" but no tool provides it for platform ${J}/${Q}.`),ambiguousDependency:($,M,J)=>W(`Ambiguous dependency: binary "${$}" is provided by multiple tools (${M}). Tool "${J}" cannot determine which to use.`),circularDependency:($)=>W(`Circular dependency detected between tools: ${$}`),shimGenerate:()=>W("Generating shims with resolved options"),shimGenerationComplete:($)=>W(`Shim generation completed with ${$} paths recorded`),shellGenerate:()=>W("Generating shell initialization files with resolved options"),shellInitComplete:($)=>W(`Shell initialization generation complete; primary path: ${$}`),completionGenerated:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),completionGeneratedAtPath:($)=>W(`Generated completion at ${$}`),completionGenerationFailed:($,M)=>W(`Failed to generate completion for ${$} (${M})`),completionSkippedNotInstalled:($,M)=>W(`Skipping completion generation for ${$} (${M}) - tool not installed yet`),symlinkGenerationComplete:($)=>W(`Symlink generation completed with ${$} operations recorded`),copyGenerationComplete:($)=>W(`Copy generation completed with ${$} operations recorded`)},cleanup:{started:($)=>W(`Cleaning up artifacts for disabled tool: ${$}`),noFilesToCleanup:($)=>W(`No tracked artifacts found to clean up for: ${$}`),filesFound:($,M)=>W(`Found ${M} artifacts to clean up for: ${$}`),fileDeleted:($,M)=>W(`Removed ${M}: ${$}`),deleteError:($,M)=>W(`Failed to delete: ${$}`),completed:($,M)=>W(`Cleanup completed for ${$}: ${M} files removed`)},orphanCleanup:{found:($)=>W(`Found ${$} orphaned tool${$===1?"":"s"} with no configuration`),cleaningUp:()=>W("Cleaning up orphaned tool")},staleSymlinkCleanup:{removing:($,M)=>W(`Removing stale symlink ${$} for tool: ${M}`)},staleCopyCleanup:{removing:($,M)=>W(`Removing stale copy ${$} for tool: ${M}`)}};function r1($,M){let J=new Set;if(M.binaries&&M.binaries.length>0)for(let Y of M.binaries)if(typeof Y==="string")J.add(Y);else J.add(Y.name);if(J.size===0)J.add($);return[...J]}function t1($){if(!$.dependencies||$.dependencies.length===0)return[];let M=new Set;for(let Q of $.dependencies){let Y=Q.trim();if(Y.length>0)M.add(Y)}return[...M]}function l9($,M,J){let Q=J.get(M)??Number.MAX_SAFE_INTEGER,Y=$.findIndex((G)=>{return(J.get(G)??Number.MAX_SAFE_INTEGER)>Q});if(Y===-1)Y=$.length;$.splice(Y,0,M)}function o1($,M){let J=new Map,Q=new Map,Y=!1;for(let[X,Z]of Object.entries($)){if(!Z)continue;let q=Y$(Z,M),I=r1(X,q),U=t1(q),K={providedBinaries:I,dependencies:U};if(J.set(X,K),U.length>0)Y=!0;for(let H of I){let _=Q.get(H);if(_)_.add(X);else{let O=new Set([X]);Q.set(H,O)}}}return{metadataByTool:J,binaryProviders:Q,hasDependencies:Y}}function e1($,M,J,Q,Y){let G=Q.get(J);if(!G||G.size===0)throw $.error(v.generateAll.missingDependency(M,J,o$(Y.platform),e$(Y.arch))),Error("Dependency validation failed");if(G.size>1){let Z=[...G];throw $.error(v.generateAll.ambiguousDependency(J,Z.join(", "),M)),Error("Dependency validation failed")}let[X]=G;if(!X)throw $.error(v.generateAll.missingDependency(M,J,o$(Y.platform),e$(Y.arch))),Error("Dependency validation failed");return X}function $4($,M,J,Q,Y){let G=new Map,X=new Map;for(let q of M)G.set(q,new Set),X.set(q,0);for(let q of M){let I=J.get(q);if(!I)continue;for(let U of I.dependencies){let K=e1($,q,U,Q,Y);if(K===q)continue;let H=G.get(K);if(H)H.add(q);let _=X.get(q)??0;X.set(q,_+1)}}return{adjacency:G,inDegree:X}}function M4($,M,J){let Q=[];for(let G of $)if((M.inDegree.get(G)??0)===0)l9(Q,G,J);let Y=[];while(Q.length>0){let G=Q.shift();if(!G)continue;Y.push(G);let X=M.adjacency.get(G);if(!X)continue;for(let Z of X){let q=(M.inDegree.get(Z)??0)-1;if(M.inDegree.set(Z,q),q===0)l9(Q,Z,J)}}return Y}function a9($,M,J){let Q=$.getSubLogger({name:"orderToolConfigsByDependencies"}),Y=Object.keys(M);if(Q.debug(v.generateAll.dependenciesValidationStarted(Y.length)),Y.length===0)return M;let G=new Map;Y.forEach((H,_)=>{G.set(H,_)});let{metadataByTool:X,binaryProviders:Z,hasDependencies:q}=o1(M,J);if(!q)return M;let I=$4(Q,Y,X,Z,J),U=M4(Y,I,G);if(U.length!==Y.length){let H=Y.filter((_)=>(I.inDegree.get(_)??0)>0);throw Q.error(v.generateAll.circularDependency(H.join(", "))),Error("Dependency validation failed")}Q.debug(v.generateAll.dependenciesOrderResolved(U.join(" -> ")));let K={};for(let H of U){let _=M[H];if(!_)throw Error(`Tool configuration missing for "${H}" after dependency ordering.`);K[H]=_}return K}var s9=new Set(["shim","symlink","copy","completion"]);class B6{logger;shimGenerator;shellInitGenerator;symlinkGenerator;copyGenerator;completionGenerator;systemInfo;projectConfig;fileRegistry;fs;completionTrackedFs;constructor($,M,J,Q,Y,G,X,Z,q,I,U){this.logger=$.getSubLogger({name:"GeneratorOrchestrator"}),this.logger.getSubLogger({name:"constructor"}).debug(v.constructor.initialized()),this.shimGenerator=M,this.shellInitGenerator=J,this.symlinkGenerator=Q,this.copyGenerator=Y,this.completionGenerator=G,this.systemInfo=X,this.projectConfig=Z,this.fileRegistry=q,this.fs=I,this.completionTrackedFs=U}matchesHostname($){let M=this.systemInfo.hostname;if($.startsWith("/")&&$.lastIndexOf("/")>0){let J=$.lastIndexOf("/"),Q=$.slice(1,J),Y=$.slice(J+1);try{return new RegExp(Q,Y).test(M)}catch{return M===$}}try{return new RegExp($).test(M)}catch{return M===$}}async generateAll($,M){let J=this.logger.getSubLogger({name:"generateAll"}),Q={};for(let[A,T]of Object.entries($)){if(T.disabled){J.warn(v.generateAll.toolDisabled(A)),await this.cleanupToolArtifacts(A);continue}if(T.hostname&&!this.matchesHostname(T.hostname)){J.warn(v.generateAll.toolHostnameMismatch(A,T.hostname,this.systemInfo.hostname)),await this.cleanupToolArtifacts(A);continue}Q[A]=T}await this.cleanupOrphanedTools($);let Y=a9(this.logger,Q,this.systemInfo),G=Object.keys(Y).length;J.debug(v.generateAll.parsedOptions(G));let X=await this.runAutoInstalls(Y,M?.installer),Z={overwrite:!0,overwriteConflicts:M?.overwrite};J.debug(v.generateAll.shimGenerate());let I=(await this.shimGenerator.generate(Y,Z))?.length??0;J.debug(v.generateAll.shimGenerationComplete(I));let U={shellTypes:["zsh","bash","powershell"],systemInfo:this.systemInfo,pluginShellInit:X};J.debug(v.generateAll.shellGenerate());let H=(await this.shellInitGenerator.generate(Y,U))?.primaryPath??"null";J.debug(v.generateAll.shellInitComplete(H));let _={overwrite:!0,backup:!0},O=await this.symlinkGenerator.generate(Y,_),B=O?.length??0;J.debug(v.generateAll.symlinkGenerationComplete(B));let j={overwrite:!0,backup:!0},V=await this.copyGenerator.generate(Y,j),D=V?.length??0;J.debug(v.generateAll.copyGenerationComplete(D)),await this.cleanupStaleSymlinks(Y,O),await this.cleanupStaleCopies(Y,V)}async runAutoInstalls($,M){let J=this.logger.getSubLogger({name:"runAutoInstalls"}),Q={};if(!M)return Q;for(let[Y,G]of Object.entries($)){if(G.installParams?.auto!==!0)continue;let q=await M.install(Y,G);if(!q.success)continue;if(q.installationMethod!=="already-installed")J.info(v.autoInstall.completed(Y));if(q.shellInit)Q[Y]=q.shellInit}return Q}async generateCompletionsForTool($,M,J,Q){let Y=this.logger.getSubLogger({name:"generateCompletionsForTool"}).setPrefix($),G=Y$(M,this.systemInfo),X=["zsh","bash","powershell"],Z=J??G.version;for(let q of X){let U=G.shellConfigs?.[q]?.completions;if(!U)continue;try{let K=J4.join(this.projectConfig.paths.binariesDir,$,"current"),H={version:Z},_=await t$(H,U),O=this.normalizeCompletionConfig(_);if(!O.cmd&&!O.source&&!O.url)continue;let B={...H,homeDir:this.projectConfig.paths.homeDir,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,toolInstallDir:K,toolName:$,configFilePath:M.configFilePath,binaryPaths:Q},j=this.completionTrackedFs.withContext({toolName:$}),V=await this.completionGenerator.generateAndWriteCompletionFile({config:O,toolName:$,shellType:q,context:B,fs:j});Y.info(v.generateAll.completionGeneratedAtPath(V.targetPath))}catch{Y.warn(v.generateAll.completionGenerationFailed($,q))}}}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin&&{bin:$.bin}};if("url"in $)return{url:$.url,...$.source&&{source:$.source},...$.bin&&{bin:$.bin}};return{source:$.source,...$.bin&&{bin:$.bin}}}async cleanupOrphanedTools($){let M=this.logger.getSubLogger({name:"cleanupOrphanedTools"}),J=await this.fileRegistry.getRegisteredTools(),Q=new Set(Object.keys($)),Y=[];for(let G of J){if(G==="system"||Q.has(G))continue;if((await this.fileRegistry.getFileStatesForTool(G)).some((q)=>s9.has(q.fileType)))Y.push(G)}if(Y.length===0)return;M.warn(v.orphanCleanup.found(Y.length));for(let G of Y)M.getSubLogger({name:"cleanupOrphanedTools",context:G}).warn(v.orphanCleanup.cleaningUp()),await this.cleanupToolArtifacts(G)}async cleanupToolArtifacts($){let M=this.logger.getSubLogger({name:"cleanupToolArtifacts",context:$});M.debug(v.cleanup.started($));let Q=(await this.fileRegistry.getFileStatesForTool($)).filter((G)=>s9.has(G.fileType));if(Q.length===0){M.debug(v.cleanup.noFilesToCleanup($));return}M.debug(v.cleanup.filesFound($,Q.length));let Y=Q.toSorted((G,X)=>X.filePath.length-G.filePath.length);for(let G of Y)try{if(G.fileType==="symlink"?await this.fs.lstat(G.filePath).then(()=>!0,()=>!1):await this.fs.exists(G.filePath)){if(G.lastOperation==="mkdir")await this.fs.rmdir(G.filePath);else await this.fs.rm(G.filePath,{recursive:G.fileType==="copy",force:!0});M.warn(v.cleanup.fileDeleted(G.filePath,G.fileType))}await this.fileRegistry.recordOperation({toolName:$,operationType:"rm",filePath:G.filePath,fileType:G.fileType,operationId:z6()})}catch(X){M.debug(v.cleanup.deleteError(G.filePath,X))}M.debug(v.cleanup.completed($,Q.length))}async cleanupStaleSymlinks($,M){let J=this.logger.getSubLogger({name:"cleanupStaleSymlinks"}),Q=new Set(M.filter((G)=>G.success).map((G)=>G.targetPath)),Y=this.projectConfig.paths.binariesDir;for(let G of Object.keys($)){let Z=(await this.fileRegistry.getFileStatesForTool(G)).filter((q)=>q.fileType==="symlink"&&q.lastOperation==="symlink"&&!q.filePath.startsWith(Y));for(let q of Z){if(Q.has(q.filePath))continue;J.warn(v.staleSymlinkCleanup.removing(q.filePath,G));try{try{await this.fs.lstat(q.filePath),await this.fs.rm(q.filePath)}catch{}await this.fileRegistry.recordOperation({toolName:G,operationType:"rm",filePath:q.filePath,fileType:"symlink",operationId:z6()})}catch(I){J.debug(v.cleanup.deleteError(q.filePath,I))}}}}async cleanupStaleCopies($,M){let J=this.logger.getSubLogger({name:"cleanupStaleCopies"}),Q=new Set(M.filter((Y)=>Y.success).map((Y)=>Y.targetPath));for(let Y of Object.keys($)){let X=(await this.fileRegistry.getFileStatesForTool(Y)).filter((Z)=>Z.fileType==="copy"&&Z.lastOperation==="cp");for(let Z of X){if(Q.has(Z.filePath))continue;J.warn(v.staleCopyCleanup.removing(Z.filePath,Y));try{if(await this.fs.exists(Z.filePath))await this.fs.rm(Z.filePath,{recursive:!0,force:!0});await this.fileRegistry.recordOperation({toolName:Y,operationType:"rm",filePath:Z.filePath,fileType:"copy",operationId:z6()})}catch(q){J.debug(v.cleanup.deleteError(Z.filePath,q))}}}}}import Q4 from"path";var b0={installing:($)=>W(`Installing from curl-binary: toolName=${$}`),downloadingBinary:($)=>W(`Downloading binary from: ${$}`),binaryDownloaded:()=>W("Binary downloaded successfully"),settingPermissions:()=>W("Setting binary executable permissions")};async function r9($,M,J,Q,Y,G,X,Z,q){let I=q$(Y,$),U=Z.getSubLogger({name:"installFromCurlBinary"});if(U.debug(b0.installing($)),!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let K=M.installParams,H=K.url;return Q$("curl-binary",$,U,async()=>{U.debug(b0.downloadingBinary(H));let O=Q4.join(J.stagingDir,$);await K$(U,H,O,$,G,Q),U.debug(b0.binaryDownloaded());let B={...J,downloadPath:O},j=await w$(M,B,X,Y,U);if(!j.success)return{success:!1,error:j.error};U.debug(b0.settingPermissions()),await M0(I,$,M,J,O,U);let V=e(M.binaries,J.stagingDir),D,A=V[0];if(A)D=await A$({binaryPath:A,args:K.versionArgs,regex:K.versionRegex,shellExecutor:q});return{success:!0,binaryPaths:V,metadata:{method:"curl-binary",downloadUrl:H,binaryUrl:H},version:D||(M.version!=="latest"?M.version:void 0)}})}import{z as CJ}from"zod";var dJ=r.extend({url:CJ.string().url(),versionArgs:CJ.array(CJ.string()).optional(),versionRegex:CJ.string().optional()});import{z as uJ}from"zod";var t9=t.extend({installationMethod:uJ.literal("curl-binary"),installParams:dJ,binaries:uJ.array(uJ.union([uJ.string().min(1),Z$])).min(1)});var Y4="1.0.0";class D6{fs;downloader;hookExecutor;shell;method="curl-binary";displayName="Curl Binary Installer";version=Y4;paramsSchema=dJ;toolConfigSchema=t9;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,Y){let G=await r9($,M,J,Q,this.fs,this.downloader,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import G4 from"path";var KM={installing:($)=>W(`Installing from npm: package=${$}`),executingCommand:($)=>W(`Executing command: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for npm package ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for npm package ${$}`),updateCheckFailed:()=>W("Failed to check update for npm tool")};async function o9($,M,J,Q,Y,G,X){let Z=Y.getSubLogger({name:"installFromNpm"});if(!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.package||$,U=q.version,K=U?`${I}@${U}`:I;Z.debug(KM.installing(I));let H=q.packageManager==="bun";return Q$("npm",$,Z,async()=>{let O=X??W$({logger:Z,skipCommandLog:!0});if(H)await Z4(K,Z,O);else await W4(K,Z,O);let B=await X4(H,O),j=e(M.binaries,B),V;if(q.versionArgs&&q.versionRegex){let T=j[0];if(T)V=await A$({binaryPath:T,args:q.versionArgs,regex:q.versionRegex,shellExecutor:G})}else if(H){let T=j[0];if(T)V=await A$({binaryPath:T,args:["--version"],regex:"(\\d+\\.\\d+\\.\\d+)",shellExecutor:G})}else V=await q4(I,G);let D={method:"npm",packageName:I};return{success:!0,binaryPaths:j,version:V?j$(V):void 0,metadata:D}})}async function X4($,M){if($)return(await M`bun pm bin -g`.quiet()).stdout.toString().trim();let J=await M`npm prefix -g`.quiet();return G4.join(J.stdout.toString().trim(),"bin")}async function Z4($,M,J){let Q=`bun install -g ${$}`;M.debug(KM.executingCommand(Q)),await J`bun install -g ${$}`}async function W4($,M,J){let Q=`npm install -g ${$}`;M.debug(KM.executingCommand(Q)),await J`npm install -g ${$}`}async function q4($,M){try{return(await M`npm view ${$} version`.quiet().noThrow()).stdout.toString().trim()||void 0}catch{return}}import{z as I0}from"zod";var fJ=r.extend({package:I0.string().min(1).optional(),version:I0.string().optional(),versionArgs:I0.array(I0.string()).optional(),versionRegex:I0.string().optional(),packageManager:I0.enum(["npm","bun"]).optional()});import{z as pJ}from"zod";var e9=t.extend({installationMethod:pJ.literal("npm"),installParams:fJ,binaries:pJ.array(pJ.union([pJ.string().min(1),Z$])).min(1)});var I4="1.0.0";class A6{shell;method="npm";displayName="npm Installer";version=I4;externallyManaged=!0;paramsSchema=fJ;toolConfigSchema=e9;constructor($){this.shell=$}async install($,M,J,Q,Y){let G=await o9($,M,J,Q,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}async resolveVersion($,M,J,Q){let Y=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return Y.debug(KM.versionFetchFailed(X)),null;let I=EM(q);return Y.debug(KM.versionFetched(X,I)),I}catch(G){return Y.debug(KM.versionFetchFailed($),G),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){let Y=Q.getSubLogger({name:"checkUpdate",context:$});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return{success:!1,error:`Could not fetch latest version for npm package: ${X}`};let I=M.version||"latest";if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:q,latestVersion:q};return{success:!0,hasUpdate:I!==q,currentVersion:I,latestVersion:q}}catch(G){return Y.error(KM.updateCheckFailed(),G),{success:!1,error:G instanceof Error?G.message:"Unknown error"}}}supportsReadme(){return!1}}import N0 from"path";var m$={installing:($)=>W(`Installing zsh plugin: ${$}`),cloning:($,M)=>W(`Cloning ${$} to ${M}`),updating:($)=>W(`Updating existing plugin at ${$}`),cloneSuccess:($)=>W(`Cloned plugin: ${$}`),updateSuccess:($)=>W(`Updated plugin: ${$}`),cloneFailed:($)=>W(`Failed to clone: ${$}`),updateFailed:($)=>W(`Failed to update: ${$}`),versionDetected:($)=>W(`Detected version: ${$}`),sourceFileDetected:($)=>W(`Detected source file: ${$}`),sourceFileNotFound:($)=>W(`Specified source file not found: ${$}`),noParamsProvided:()=>W("No install parameters provided"),invalidParams:()=>W("Either repo or url must be specified")};async function $G($,M,J,Q,Y,G,X){let Z=Q.getSubLogger({name:"installFromZshPlugin"});Z.debug(m$.installing($));let q=M.installParams;if(!q)return{success:!1,error:"No install parameters provided"};if(!q.repo&&!q.url)return{success:!1,error:"Either repo or url must be specified"};return Q$("zsh-plugin",$,Z,async()=>{let U=q.url??`https://github.com/${q.repo}.git`,K=E6(q.pluginName,q.repo,q.url),H=N0.join(J.stagingDir,K),_=await Y.exists(H),O=X??W$({logger:Z,skipCommandLog:!0});if(_)Z.debug(m$.updating(H)),await H4(H,O),Z.info(m$.updateSuccess(K));else Z.debug(m$.cloning(U,H)),await K4(U,H,O),Z.info(m$.cloneSuccess(K));let B=await U4(H,K,q.source,Y,Z);if(!B)return{success:!1,error:`Could not detect plugin source file in ${H}. Specify 'source' parameter explicitly.`};let j=await _4(H,G,Z),V=N0.join(J.currentDir,K,B);return{success:!0,binaryPaths:[],version:j,metadata:{method:"zsh-plugin",pluginName:K,gitUrl:U,pluginPath:H,sourceFile:B},shellInit:{zsh:{scripts:[n$(`source "${V}"`)]}}}})}function E6($,M,J){if($)return $;if(M)return M.split("/")[1]??M;if(J){let Q=new URL(J).pathname;return N0.basename(Q,".git")}throw Error("Cannot determine plugin name")}async function U4($,M,J,Q,Y){let G=Y.getSubLogger({name:"detectSourceFile"});if(J){let Z=N0.join($,J);if(await Q.exists(Z))return G.debug(m$.sourceFileDetected(J)),J;G.warn(m$.sourceFileNotFound(J));return}let X=[`${M}.plugin.zsh`,`${M}.zsh`,"init.zsh","plugin.zsh",`${M}.zsh-theme`];for(let Z of X){let q=N0.join($,Z);if(await Q.exists(q))return G.debug(m$.sourceFileDetected(Z)),Z}return}async function K4($,M,J){await J`git clone --depth 1 ${$} ${M}`}async function H4($,M){await M`git -C ${$} pull --ff-only`}async function _4($,M,J){let Q=J.getSubLogger({name:"getGitVersion"});try{let Y=await M`git -C ${$} describe --tags --abbrev=0`.quiet().noThrow();if(Y.code===0){let X=Y.stdout.trim();return Q.debug(m$.versionDetected(X)),X}let G=await M`git -C ${$} rev-parse --short HEAD`.quiet().noThrow();if(G.code===0){let X=G.stdout.trim();return Q.debug(m$.versionDetected(X)),X}return}catch{return}}import{z as v0}from"zod";var cJ=r.extend({repo:v0.string().regex(/^[^/]+\/[^/]+$/,"Must be in user/repo format").optional(),url:v0.string().url().optional(),pluginName:v0.string().min(1).optional(),source:v0.string().min(1).optional(),auto:v0.boolean().default(!0)}).refine(($)=>$.repo||$.url,{message:"Either repo or url must be specified"});import{z as F6}from"zod";var MG=t.extend({installationMethod:F6.literal("zsh-plugin"),installParams:cJ,binaries:F6.array(F6.string().min(1)).default([])});import R4 from"path";var O4="1.0.0";class L6{fs;shell;method="zsh-plugin";displayName="Zsh Plugin Installer";version=O4;paramsSchema=cJ;toolConfigSchema=MG;externallyManaged=!1;constructor($,M){this.fs=$;this.shell=M}async install($,M,J,Q,Y){let G=await $G($,M,J,Y,this.fs,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata,shellInit:G.shellInit}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}getShellInit($,M,J){let Q=M.installParams;if(!Q)return;let Y=E6(Q.pluginName,Q.repo,Q.url),G=Q.source??`${Y}.plugin.zsh`,X=R4.join(J,Y,G);return{zsh:{scripts:[n$(`source "${X}"`)]}}}}import x6 from"path";var _$={constructor:{initialized:()=>W("ShimGenerator initialized")},generate:{missingToolConfig:($)=>W(`Skipping shim generation for ${$} because configuration is missing`)},generateForTool:{started:($,M)=>W(`Generating shims for ${$} using ${M}`),skippedExternallyManaged:($,M)=>W(`Skipping shim generation for ${$} (externally managed via ${M})`),skippedNoBinaries:($)=>W(`Skipping shim generation for ${$} (no binaries defined)`),skippedAlreadyInstalled:($)=>W(`Skipping shim generation for ${$} (already installed)`),skippedManualNoBinaryPath:()=>W("Skipping shim generation (manual tool has .bin() but no binaryPath \u2014 use shell functions instead)")},generateShim:{resolvedShimPath:($)=>W(`Resolved shim output path ${$}`),existingShim:($)=>W(`Existing shim found at ${$}; overwrite is disabled`),conflictingFile:($,M)=>W(`Cannot create shim for "${$}": conflicting file exists at ${M}. Use --overwrite to replace it.`),overwritingConflict:($)=>W(`Overwriting conflicting file at ${$}`),resolvedBinaryPath:($,M,J)=>W(`Resolved binary path for ${$}/${M} to ${J}`),generatedContent:($)=>W(`Generated shim content for ${$}`),success:($,M,J)=>W(`Generated shim ${$} at ${M} using ${J}`)}};class T6{fs;config;logger;systemInfo;externallyManagedMethods;missingBinaryMessagesByMethod;toolInstallationRegistry;isConfigurationOnlyToolConfig($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}constructor($,M,J,Q,Y,G,X){let Z=$.getSubLogger({name:"ShimGenerator"});this.logger=Z,Z.getSubLogger({name:"constructor"}).debug(_$.constructor.initialized()),this.fs=M,this.config=J,this.systemInfo=Q,this.externallyManagedMethods=Y??new Set,this.missingBinaryMessagesByMethod=G??new Map,this.toolInstallationRegistry=X}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $)if(Object.hasOwn($,Y)){let G=$[Y];if(G){let X=await this.generateForTool(Y,G,M);Q.push(...X)}else J.debug(_$.generate.missingToolConfig(Y))}return Q}async generateForTool($,M,J){let Q=this.logger.getSubLogger({name:"generateForTool",context:$}),Y=this.fs instanceof f?this.fs.withToolName($):this.fs,G=Y.constructor.name;Q.debug(_$.generateForTool.started($,G));let X=Y$(M,this.systemInfo),Z=[],q=J?.overwrite??!1,I=J?.overwriteConflicts??!1;if(this.isConfigurationOnlyToolConfig(X))return Z;if(X.installationMethod==="manual"&&!X.installParams?.binaryPath)return Q.warn(_$.generateForTool.skippedManualNoBinaryPath()),Z;if(this.externallyManagedMethods.has(X.installationMethod)){if(!this.toolInstallationRegistry)return Q.debug(_$.generateForTool.skippedExternallyManaged($,X.installationMethod)),Z;if(await this.toolInstallationRegistry.isToolInstalled($))return Q.debug(_$.generateForTool.skippedAlreadyInstalled($)),Z}let U=X.binaries&&X.binaries.length>0?X.binaries:[];if(U.length===0)return Q.debug(_$.generateForTool.skippedNoBinaries($)),Z;let K=U.map((H)=>typeof H==="string"?H:H.name);for(let H of K){let _=await this.generateShimForBinary(Y,$,X,H,q,I);if(_)Z.push(_)}return Z}async generateShimForBinary($,M,J,Q,Y,G){let X=this.logger.getSubLogger({name:"generateShimForBinary"}),Z=this.config.paths.targetDir,q=x6.join(Z,Q);if(X.debug(_$.generateShim.resolvedShimPath(q)),await $.exists(q)){if(!await this.isGeneratedShim($,q)){if(!G)return X.error(_$.generateShim.conflictingFile(M,q)),null;X.debug(_$.generateShim.overwritingConflict(q))}else if(!Y)return X.debug(_$.generateShim.existingShim(q)),null}let I=x6.join(this.config.paths.binariesDir,M,"current",Q);X.debug(_$.generateShim.resolvedBinaryPath(M,Q,I));let U=M.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),K=this.missingBinaryMessagesByMethod.get(J.installationMethod),H=K?`echo "${K.replaceAll('"',"\\\"")}" >&2`:'echo "Installation completed but binary not found at: $TOOL_EXECUTABLE" >&2',_=c(`
161
+ `)}}import{randomUUID as B6}from"crypto";import WX from"path";var v={constructor:{initialized:()=>Z("Initializing GeneratorOrchestrator")},autoInstall:{completed:($)=>Z(`Auto-installed: ${$}`)},generateAll:{parsedOptions:($)=>Z(`Parsed ${$} tool configuration entries`),toolDisabled:($)=>Z(`Skipping disabled tool: ${$}`),toolHostnameMismatch:($,I,M)=>Z(`Skipping tool "${$}": hostname "${M}" does not match pattern "${I}"`),dependenciesValidationStarted:($)=>Z(`Validating tool dependencies (${$} tools)`),dependenciesOrderResolved:($)=>Z(`Dependency order resolved: ${$}`),missingDependency:($,I,M,G)=>Z(`Missing dependency: tool "${$}" requires binary "${I}" but no tool provides it for platform ${M}/${G}.`),ambiguousDependency:($,I,M)=>Z(`Ambiguous dependency: binary "${$}" is provided by multiple tools (${I}). Tool "${M}" cannot determine which to use.`),circularDependency:($)=>Z(`Circular dependency detected between tools: ${$}`),shimGenerate:()=>Z("Generating shims with resolved options"),shimGenerationComplete:($)=>Z(`Shim generation completed with ${$} paths recorded`),shellGenerate:()=>Z("Generating shell initialization files with resolved options"),shellInitComplete:($)=>Z(`Shell initialization generation complete; primary path: ${$}`),completionGenerated:($,I,M)=>Z(`Generated completion ${$} for ${I} (${M})`),completionGeneratedAtPath:($)=>Z(`Generated completion at ${$}`),completionGenerationFailed:($,I)=>Z(`Failed to generate completion for ${$} (${I})`),completionSkippedNotInstalled:($,I)=>Z(`Skipping completion generation for ${$} (${I}) - tool not installed yet`),symlinkGenerationComplete:($)=>Z(`Symlink generation completed with ${$} operations recorded`),copyGenerationComplete:($)=>Z(`Copy generation completed with ${$} operations recorded`)},cleanup:{started:($)=>Z(`Cleaning up artifacts for disabled tool: ${$}`),noFilesToCleanup:($)=>Z(`No tracked artifacts found to clean up for: ${$}`),filesFound:($,I)=>Z(`Found ${I} artifacts to clean up for: ${$}`),fileDeleted:($,I)=>Z(`Removed ${I}: ${$}`),deleteError:($,I)=>Z(`Failed to delete: ${$}`),completed:($,I)=>Z(`Cleanup completed for ${$}: ${I} files removed`)},orphanCleanup:{found:($)=>Z(`Found ${$} orphaned tool${$===1?"":"s"} with no configuration`),cleaningUp:()=>Z("Cleaning up orphaned tool")},staleSymlinkCleanup:{removing:($,I)=>Z(`Removing stale symlink ${$} for tool: ${I}`)},staleCopyCleanup:{removing:($,I)=>Z(`Removing stale copy ${$} for tool: ${I}`)}};function JX($,I){let M=new Set;if(I.binaries&&I.binaries.length>0)for(let J of I.binaries)if(typeof J==="string")M.add(J);else M.add(J.name);if(M.size===0)M.add($);return[...M]}function QX($){if(!$.dependencies||$.dependencies.length===0)return[];let I=new Set;for(let G of $.dependencies){let J=G.trim();if(J.length>0)I.add(J)}return[...I]}function rQ($,I,M){let G=M.get(I)??Number.MAX_SAFE_INTEGER,J=$.findIndex((Q)=>{return(M.get(Q)??Number.MAX_SAFE_INTEGER)>G});if(J===-1)J=$.length;$.splice(J,0,I)}function YX($,I){let M=new Map,G=new Map,J=!1;for(let[Y,X]of Object.entries($)){if(!X)continue;let R=I$(X,I),W=JX(Y,R),q=QX(R),U={providedBinaries:W,dependencies:q};if(M.set(Y,U),q.length>0)J=!0;for(let H of W){let K=G.get(H);if(K)K.add(Y);else{let O=new Set([Y]);G.set(H,O)}}}return{metadataByTool:M,binaryProviders:G,hasDependencies:J}}function XX($,I,M,G,J){let Q=G.get(M);if(!Q||Q.size===0)throw $.error(v.generateAll.missingDependency(I,M,II(J.platform),MI(J.arch))),Error("Dependency validation failed");if(Q.size>1){let X=[...Q];throw $.error(v.generateAll.ambiguousDependency(M,X.join(", "),I)),Error("Dependency validation failed")}let[Y]=Q;if(!Y)throw $.error(v.generateAll.missingDependency(I,M,II(J.platform),MI(J.arch))),Error("Dependency validation failed");return Y}function ZX($,I,M,G,J){let Q=new Map,Y=new Map;for(let R of I)Q.set(R,new Set),Y.set(R,0);for(let R of I){let W=M.get(R);if(!W)continue;for(let q of W.dependencies){let U=XX($,R,q,G,J);if(U===R)continue;let H=Q.get(U);if(H)H.add(R);let K=Y.get(R)??0;Y.set(R,K+1)}}return{adjacency:Q,inDegree:Y}}function RX($,I,M){let G=[];for(let Q of $)if((I.inDegree.get(Q)??0)===0)rQ(G,Q,M);let J=[];while(G.length>0){let Q=G.shift();if(!Q)continue;J.push(Q);let Y=I.adjacency.get(Q);if(!Y)continue;for(let X of Y){let R=(I.inDegree.get(X)??0)-1;if(I.inDegree.set(X,R),R===0)rQ(G,X,M)}}return J}function sQ($,I,M){let G=$.getSubLogger({name:"orderToolConfigsByDependencies"}),J=Object.keys(I);if(G.debug(v.generateAll.dependenciesValidationStarted(J.length)),J.length===0)return I;let Q=new Map;J.forEach((H,K)=>{Q.set(H,K)});let{metadataByTool:Y,binaryProviders:X,hasDependencies:R}=YX(I,M);if(!R)return I;let W=ZX(G,J,Y,X,M),q=RX(J,W,Q);if(q.length!==J.length){let H=J.filter((K)=>(W.inDegree.get(K)??0)>0);throw G.error(v.generateAll.circularDependency(H.join(", "))),Error("Dependency validation failed")}G.debug(v.generateAll.dependenciesOrderResolved(q.join(" -> ")));let U={};for(let H of q){let K=I[H];if(!K)throw Error(`Tool configuration missing for "${H}" after dependency ordering.`);U[H]=K}return U}var tQ=new Set(["shim","symlink","copy","completion"]);class x6{logger;shimGenerator;shellInitGenerator;symlinkGenerator;copyGenerator;completionGenerator;systemInfo;projectConfig;fileRegistry;fs;completionTrackedFs;constructor($,I,M,G,J,Q,Y,X,R,W,q){this.logger=$.getSubLogger({name:"GeneratorOrchestrator"}),this.logger.getSubLogger({name:"constructor"}).debug(v.constructor.initialized()),this.shimGenerator=I,this.shellInitGenerator=M,this.symlinkGenerator=G,this.copyGenerator=J,this.completionGenerator=Q,this.systemInfo=Y,this.projectConfig=X,this.fileRegistry=R,this.fs=W,this.completionTrackedFs=q}matchesHostname($){let I=this.systemInfo.hostname;if($.startsWith("/")&&$.lastIndexOf("/")>0){let M=$.lastIndexOf("/"),G=$.slice(1,M),J=$.slice(M+1);try{return new RegExp(G,J).test(I)}catch{return I===$}}try{return new RegExp($).test(I)}catch{return I===$}}async generateAll($,I){let M=this.logger.getSubLogger({name:"generateAll"}),G={};for(let[A,T]of Object.entries($)){if(T.disabled){M.warn(v.generateAll.toolDisabled(A)),await this.cleanupToolArtifacts(A);continue}if(T.hostname&&!this.matchesHostname(T.hostname)){M.warn(v.generateAll.toolHostnameMismatch(A,T.hostname,this.systemInfo.hostname)),await this.cleanupToolArtifacts(A);continue}G[A]=T}await this.cleanupOrphanedTools($);let J=sQ(this.logger,G,this.systemInfo),Q=Object.keys(J).length;M.debug(v.generateAll.parsedOptions(Q));let Y=await this.runAutoInstalls(J,I?.installer),X={overwrite:!0,overwriteConflicts:I?.overwrite};M.debug(v.generateAll.shimGenerate());let W=(await this.shimGenerator.generate(J,X))?.length??0;M.debug(v.generateAll.shimGenerationComplete(W));let q={shellTypes:["zsh","bash","powershell"],systemInfo:this.systemInfo,pluginShellInit:Y};M.debug(v.generateAll.shellGenerate());let H=(await this.shellInitGenerator.generate(J,q))?.primaryPath??"null";M.debug(v.generateAll.shellInitComplete(H));let K={overwrite:!0,backup:!0},O=await this.symlinkGenerator.generate(J,K),B=O?.length??0;M.debug(v.generateAll.symlinkGenerationComplete(B));let j={overwrite:!0,backup:!0},V=await this.copyGenerator.generate(J,j),x=V?.length??0;M.debug(v.generateAll.copyGenerationComplete(x)),await this.cleanupStaleSymlinks(J,O),await this.cleanupStaleCopies(J,V)}async runAutoInstalls($,I){let M=this.logger.getSubLogger({name:"runAutoInstalls"}),G={};if(!I)return G;for(let[J,Q]of Object.entries($)){if(Q.installParams?.auto!==!0)continue;let R=await I.install(J,Q);if(!R.success)continue;if(R.installationMethod!=="already-installed")M.info(v.autoInstall.completed(J));if(R.shellInit)G[J]=R.shellInit}return G}async generateCompletionsForTool($,I,M,G){let J=this.logger.getSubLogger({name:"generateCompletionsForTool"}).setPrefix($),Q=I$(I,this.systemInfo),Y=["zsh","bash","powershell"],X=M??Q.version;for(let R of Y){let q=Q.shellConfigs?.[R]?.completions;if(!q)continue;try{let U=WX.join(this.projectConfig.paths.binariesDir,$,"current"),H={version:X},K=await $I(H,q),O=this.normalizeCompletionConfig(K);if(!O.cmd&&!O.source&&!O.url)continue;let B={...H,homeDir:this.projectConfig.paths.homeDir,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,toolInstallDir:U,toolName:$,configFilePath:I.configFilePath,binaryPaths:G},j=this.completionTrackedFs.withContext({toolName:$}),V=await this.completionGenerator.generateAndWriteCompletionFile({config:O,toolName:$,shellType:R,context:B,fs:j});J.info(v.generateAll.completionGeneratedAtPath(V.targetPath))}catch{J.warn(v.generateAll.completionGenerationFailed($,R))}}}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin&&{bin:$.bin}};if("url"in $)return{url:$.url,...$.source&&{source:$.source},...$.bin&&{bin:$.bin}};return{source:$.source,...$.bin&&{bin:$.bin}}}async cleanupOrphanedTools($){let I=this.logger.getSubLogger({name:"cleanupOrphanedTools"}),M=await this.fileRegistry.getRegisteredTools(),G=new Set(Object.keys($)),J=[];for(let Q of M){if(Q==="system"||G.has(Q))continue;if((await this.fileRegistry.getFileStatesForTool(Q)).some((R)=>tQ.has(R.fileType)))J.push(Q)}if(J.length===0)return;I.warn(v.orphanCleanup.found(J.length));for(let Q of J)I.getSubLogger({name:"cleanupOrphanedTools",context:Q}).warn(v.orphanCleanup.cleaningUp()),await this.cleanupToolArtifacts(Q)}async cleanupToolArtifacts($){let I=this.logger.getSubLogger({name:"cleanupToolArtifacts",context:$});I.debug(v.cleanup.started($));let G=(await this.fileRegistry.getFileStatesForTool($)).filter((Q)=>tQ.has(Q.fileType));if(G.length===0){I.debug(v.cleanup.noFilesToCleanup($));return}I.debug(v.cleanup.filesFound($,G.length));let J=G.toSorted((Q,Y)=>Y.filePath.length-Q.filePath.length);for(let Q of J)try{if(Q.fileType==="symlink"?await this.fs.lstat(Q.filePath).then(()=>!0,()=>!1):await this.fs.exists(Q.filePath)){if(Q.lastOperation==="mkdir")await this.fs.rmdir(Q.filePath);else await this.fs.rm(Q.filePath,{recursive:Q.fileType==="copy",force:!0});I.warn(v.cleanup.fileDeleted(Q.filePath,Q.fileType))}await this.fileRegistry.recordOperation({toolName:$,operationType:"rm",filePath:Q.filePath,fileType:Q.fileType,operationId:B6()})}catch(Y){I.debug(v.cleanup.deleteError(Q.filePath,Y))}I.debug(v.cleanup.completed($,G.length))}async cleanupStaleSymlinks($,I){let M=this.logger.getSubLogger({name:"cleanupStaleSymlinks"}),G=new Set(I.filter((Q)=>Q.success).map((Q)=>Q.targetPath)),J=this.projectConfig.paths.binariesDir;for(let Q of Object.keys($)){let X=(await this.fileRegistry.getFileStatesForTool(Q)).filter((R)=>R.fileType==="symlink"&&R.lastOperation==="symlink"&&!R.filePath.startsWith(J));for(let R of X){if(G.has(R.filePath))continue;M.warn(v.staleSymlinkCleanup.removing(R.filePath,Q));try{try{await this.fs.lstat(R.filePath),await this.fs.rm(R.filePath)}catch{}await this.fileRegistry.recordOperation({toolName:Q,operationType:"rm",filePath:R.filePath,fileType:"symlink",operationId:B6()})}catch(W){M.debug(v.cleanup.deleteError(R.filePath,W))}}}}async cleanupStaleCopies($,I){let M=this.logger.getSubLogger({name:"cleanupStaleCopies"}),G=new Set(I.filter((J)=>J.success).map((J)=>J.targetPath));for(let J of Object.keys($)){let Y=(await this.fileRegistry.getFileStatesForTool(J)).filter((X)=>X.fileType==="copy"&&X.lastOperation==="cp");for(let X of Y){if(G.has(X.filePath))continue;M.warn(v.staleCopyCleanup.removing(X.filePath,J));try{if(await this.fs.exists(X.filePath))await this.fs.rm(X.filePath,{recursive:!0,force:!0});await this.fileRegistry.recordOperation({toolName:J,operationType:"rm",filePath:X.filePath,fileType:"copy",operationId:B6()})}catch(R){M.debug(v.cleanup.deleteError(X.filePath,R))}}}}}import qX from"path";var PM={installing:($)=>Z(`Installing from curl-binary: toolName=${$}`),downloadingBinary:($)=>Z(`Downloading binary from: ${$}`),binaryDownloaded:()=>Z("Binary downloaded successfully"),settingPermissions:()=>Z("Setting binary executable permissions")};async function oQ($,I,M,G,J,Q,Y,X,R){let W=R$(J,$),q=X.getSubLogger({name:"installFromCurlBinary"});if(q.debug(PM.installing($)),!I.installParams||!("url"in I.installParams))return{success:!1,error:"URL not specified in installParams"};let U=I.installParams,H=U.url;return J$("curl-binary",$,q,async()=>{q.debug(PM.downloadingBinary(H));let O=qX.join(M.stagingDir,$);await U$(q,H,O,$,Q,G),q.debug(PM.binaryDownloaded());let B={...M,downloadPath:O},j=await y$(I,B,Y,J,q);if(!j.success)return{success:!1,error:j.error};q.debug(PM.settingPermissions()),await JM(W,$,I,M,O,q);let V=o(I.binaries,M.stagingDir),x,A=V[0];if(A)x=await D$({binaryPath:A,args:U.versionArgs,regex:U.versionRegex,shellExecutor:R});return{success:!0,binaryPaths:V,metadata:{method:"curl-binary",downloadUrl:H,binaryUrl:H},version:x||(I.version!=="latest"?I.version:void 0)}})}import{z as HM}from"zod";var u0=s.extend({url:HM.string().url(),versionArgs:HM.array(HM.string()).optional(),versionRegex:HM.union([HM.string(),HM.instanceof(RegExp)]).optional()});import{z as f0}from"zod";var eQ=t.extend({installationMethod:f0.literal("curl-binary"),installParams:u0,binaries:f0.array(f0.union([f0.string().min(1),X$])).min(1)});var UX="1.0.0";class D6{fs;downloader;hookExecutor;shell;method="curl-binary";displayName="Curl Binary Installer";version=UX;paramsSchema=u0;toolConfigSchema=eQ;constructor($,I,M,G){this.fs=$;this.downloader=I;this.hookExecutor=M;this.shell=G}async install($,I,M,G,J){let Q=await oQ($,I,M,G,this.fs,this.downloader,this.hookExecutor,J,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import HX from"path";var KI={installing:($)=>Z(`Installing from npm: package=${$}`),executingCommand:($)=>Z(`Executing command: ${$}`),versionFetched:($,I)=>Z(`Fetched version ${I} for npm package ${$}`),versionFetchFailed:($)=>Z(`Failed to fetch version for npm package ${$}`),updateCheckFailed:()=>Z("Failed to check update for npm tool")};async function $1($,I,M,G,J,Q,Y){let X=J.getSubLogger({name:"installFromNpm"});if(!I.installParams)return{success:!1,error:"Install parameters not specified"};let R=I.installParams,W=R.package||$,q=R.version,U=q?`${W}@${q}`:W;X.debug(KI.installing(W));let H=R.packageManager==="bun";return J$("npm",$,X,async()=>{let O=Y??Z$({logger:X,skipCommandLog:!0});if(H)await _X(U,X,O);else await OX(U,X,O);let B=await KX(H,O),j=o(I.binaries,B),V;if(R.versionArgs&&R.versionRegex){let T=j[0];if(T)V=await D$({binaryPath:T,args:R.versionArgs,regex:R.versionRegex,shellExecutor:Q})}else if(H){let T=j[0];if(T)V=await D$({binaryPath:T,args:["--version"],regex:"(\\d+\\.\\d+\\.\\d+)",shellExecutor:Q})}else V=await jX(W,Q);let x={method:"npm",packageName:W};return{success:!0,binaryPaths:j,version:V?j$(V):void 0,metadata:x}})}async function KX($,I){if($)return(await I`bun pm bin -g`.quiet()).stdout.toString().trim();let M=await I`npm prefix -g`.quiet();return HX.join(M.stdout.toString().trim(),"bin")}async function _X($,I,M){let G=`bun install -g ${$}`;I.debug(KI.executingCommand(G)),await M`bun install -g ${$}`}async function OX($,I,M){let G=`npm install -g ${$}`;I.debug(KI.executingCommand(G)),await M`npm install -g ${$}`}async function jX($,I){try{return(await I`npm view ${$} version`.quiet().noThrow()).stdout.toString().trim()||void 0}catch{return}}import{z as kI}from"zod";var p0=s.extend({package:kI.string().min(1).optional(),version:kI.string().optional(),versionArgs:kI.array(kI.string()).optional(),versionRegex:kI.union([kI.string(),kI.instanceof(RegExp)]).optional(),packageManager:kI.enum(["npm","bun"]).optional()});import{z as c0}from"zod";var I1=t.extend({installationMethod:c0.literal("npm"),installParams:p0,binaries:c0.array(c0.union([c0.string().min(1),X$])).min(1)});var VX="1.0.0";class A6{shell;method="npm";displayName="npm Installer";version=VX;externallyManaged=!0;paramsSchema=p0;toolConfigSchema=I1;constructor($){this.shell=$}async install($,I,M,G,J){let Q=await $1($,I,M,G,J,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata}}async resolveVersion($,I,M,G){let J=G.getSubLogger({name:"resolveVersion"});try{let Y=I.installParams?.package||$,R=(await this.shell`npm view ${Y} version`.quiet().noThrow()).stdout.toString().trim();if(!R)return J.debug(KI.versionFetchFailed(Y)),null;let W=FI(R);return J.debug(KI.versionFetched(Y,W)),W}catch(Q){return J.debug(KI.versionFetchFailed($),Q),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,I,M,G){let J=G.getSubLogger({name:"checkUpdate",context:$});try{let Y=I.installParams?.package||$,R=(await this.shell`npm view ${Y} version`.quiet().noThrow()).stdout.toString().trim();if(!R)return{success:!1,error:`Could not fetch latest version for npm package: ${Y}`};let W=I.version||"latest";if(W==="latest")return{success:!0,hasUpdate:!1,currentVersion:R,latestVersion:R};return{success:!0,hasUpdate:W!==R,currentVersion:W,latestVersion:R}}catch(Q){return J.error(KI.updateCheckFailed(),Q),{success:!1,error:Q instanceof Error?Q.message:"Unknown error"}}}supportsReadme(){return!1}}import CM from"path";var i$={installing:($)=>Z(`Installing zsh plugin: ${$}`),cloning:($,I)=>Z(`Cloning ${$} to ${I}`),updating:($)=>Z(`Updating existing plugin at ${$}`),cloneSuccess:($)=>Z(`Cloned plugin: ${$}`),updateSuccess:($)=>Z(`Updated plugin: ${$}`),cloneFailed:($)=>Z(`Failed to clone: ${$}`),updateFailed:($)=>Z(`Failed to update: ${$}`),versionDetected:($)=>Z(`Detected version: ${$}`),sourceFileDetected:($)=>Z(`Detected source file: ${$}`),sourceFileNotFound:($)=>Z(`Specified source file not found: ${$}`),noParamsProvided:()=>Z("No install parameters provided"),invalidParams:()=>Z("Either repo or url must be specified")};async function M1($,I,M,G,J,Q,Y){let X=G.getSubLogger({name:"installFromZshPlugin"});X.debug(i$.installing($));let R=I.installParams;if(!R)return{success:!1,error:"No install parameters provided"};if(!R.repo&&!R.url)return{success:!1,error:"Either repo or url must be specified"};return J$("zsh-plugin",$,X,async()=>{let q=R.url??`https://github.com/${R.repo}.git`,U=F6(R.pluginName,R.repo,R.url),H=CM.join(M.stagingDir,U),K=await J.exists(H),O=Y??Z$({logger:X,skipCommandLog:!0});if(K)X.debug(i$.updating(H)),await xX(H,O),X.info(i$.updateSuccess(U));else X.debug(i$.cloning(q,H)),await BX(q,H,O),X.info(i$.cloneSuccess(U));let B=await zX(H,U,R.source,J,X);if(!B)return{success:!1,error:`Could not detect plugin source file in ${H}. Specify 'source' parameter explicitly.`};let j=await DX(H,Q,X),V=CM.join(M.currentDir,U,B);return{success:!0,binaryPaths:[],version:j,metadata:{method:"zsh-plugin",pluginName:U,gitUrl:q,pluginPath:H,sourceFile:B},shellInit:{zsh:{scripts:[a$(`source "${V}"`)]}}}})}function F6($,I,M){if($)return $;if(I)return I.split("/")[1]??I;if(M){let G=new URL(M).pathname;return CM.basename(G,".git")}throw Error("Cannot determine plugin name")}async function zX($,I,M,G,J){let Q=J.getSubLogger({name:"detectSourceFile"});if(M){let X=CM.join($,M);if(await G.exists(X))return Q.debug(i$.sourceFileDetected(M)),M;Q.warn(i$.sourceFileNotFound(M));return}let Y=[`${I}.plugin.zsh`,`${I}.zsh`,"init.zsh","plugin.zsh",`${I}.zsh-theme`];for(let X of Y){let R=CM.join($,X);if(await G.exists(R))return Q.debug(i$.sourceFileDetected(X)),X}return}async function BX($,I,M){await M`git clone --depth 1 ${$} ${I}`}async function xX($,I){await I`git -C ${$} pull --ff-only`}async function DX($,I,M){let G=M.getSubLogger({name:"getGitVersion"});try{let J=await I`git -C ${$} describe --tags --abbrev=0`.quiet().noThrow();if(J.code===0){let Y=J.stdout.trim();return G.debug(i$.versionDetected(Y)),Y}let Q=await I`git -C ${$} rev-parse --short HEAD`.quiet().noThrow();if(Q.code===0){let Y=Q.stdout.trim();return G.debug(i$.versionDetected(Y)),Y}return}catch{return}}import{z as dM}from"zod";var h0=s.extend({repo:dM.string().regex(/^[^/]+\/[^/]+$/,"Must be in user/repo format").optional(),url:dM.string().url().optional(),pluginName:dM.string().min(1).optional(),source:dM.string().min(1).optional(),auto:dM.boolean().default(!0)}).refine(($)=>$.repo||$.url,{message:"Either repo or url must be specified"});import{z as L6}from"zod";var G1=t.extend({installationMethod:L6.literal("zsh-plugin"),installParams:h0,binaries:L6.array(L6.string().min(1)).default([])});import AX from"path";var FX="1.0.0";class E6{fs;shell;method="zsh-plugin";displayName="Zsh Plugin Installer";version=FX;paramsSchema=h0;toolConfigSchema=G1;externallyManaged=!1;constructor($,I){this.fs=$;this.shell=I}async install($,I,M,G,J){let Q=await M1($,I,M,J,this.fs,this.shell);if(!Q.success)return{success:!1,error:Q.error};return{success:!0,binaryPaths:Q.binaryPaths,version:Q.version,metadata:Q.metadata,shellInit:Q.shellInit}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}getShellInit($,I,M){let G=I.installParams;if(!G)return;let J=F6(G.pluginName,G.repo,G.url),Q=G.source??`${J}.plugin.zsh`,Y=AX.join(M,J,Q);return{zsh:{scripts:[a$(`source "${Y}"`)]}}}}import T6 from"path";var K$={constructor:{initialized:()=>Z("ShimGenerator initialized")},generate:{missingToolConfig:($)=>Z(`Skipping shim generation for ${$} because configuration is missing`)},generateForTool:{started:($,I)=>Z(`Generating shims for ${$} using ${I}`),skippedExternallyManaged:($,I)=>Z(`Skipping shim generation for ${$} (externally managed via ${I})`),skippedNoBinaries:($)=>Z(`Skipping shim generation for ${$} (no binaries defined)`),skippedAlreadyInstalled:($)=>Z(`Skipping shim generation for ${$} (already installed)`),skippedManualNoBinaryPath:()=>Z("Skipping shim generation (manual tool has .bin() but no binaryPath \u2014 use shell functions instead)")},generateShim:{resolvedShimPath:($)=>Z(`Resolved shim output path ${$}`),existingShim:($)=>Z(`Existing shim found at ${$}; overwrite is disabled`),conflictingFile:($,I)=>Z(`Cannot create shim for "${$}": conflicting file exists at ${I}. Use --overwrite to replace it.`),overwritingConflict:($)=>Z(`Overwriting conflicting file at ${$}`),resolvedBinaryPath:($,I,M)=>Z(`Resolved binary path for ${$}/${I} to ${M}`),generatedContent:($)=>Z(`Generated shim content for ${$}`),success:($,I,M)=>Z(`Generated shim ${$} at ${I} using ${M}`)}};class S6{fs;config;logger;systemInfo;externallyManagedMethods;missingBinaryMessagesByMethod;toolInstallationRegistry;isConfigurationOnlyToolConfig($){let I=$.installationMethod==="manual",M=!$.installParams||Object.keys($.installParams).length===0,G=!$.binaries||$.binaries.length===0;return I&&M&&G}constructor($,I,M,G,J,Q,Y){let X=$.getSubLogger({name:"ShimGenerator"});this.logger=X,X.getSubLogger({name:"constructor"}).debug(K$.constructor.initialized()),this.fs=I,this.config=M,this.systemInfo=G,this.externallyManagedMethods=J??new Set,this.missingBinaryMessagesByMethod=Q??new Map,this.toolInstallationRegistry=Y}async generate($,I){let M=this.logger.getSubLogger({name:"generate"}),G=[];for(let J in $)if(Object.hasOwn($,J)){let Q=$[J];if(Q){let Y=await this.generateForTool(J,Q,I);G.push(...Y)}else M.debug(K$.generate.missingToolConfig(J))}return G}async generateForTool($,I,M){let G=this.logger.getSubLogger({name:"generateForTool",context:$}),J=this.fs instanceof f?this.fs.withToolName($):this.fs,Q=J.constructor.name;G.debug(K$.generateForTool.started($,Q));let Y=I$(I,this.systemInfo),X=[],R=M?.overwrite??!1,W=M?.overwriteConflicts??!1;if(this.isConfigurationOnlyToolConfig(Y))return X;if(Y.installationMethod==="manual"&&!Y.installParams?.binaryPath)return G.warn(K$.generateForTool.skippedManualNoBinaryPath()),X;if(this.externallyManagedMethods.has(Y.installationMethod)){if(!this.toolInstallationRegistry)return G.debug(K$.generateForTool.skippedExternallyManaged($,Y.installationMethod)),X;if(await this.toolInstallationRegistry.isToolInstalled($))return G.debug(K$.generateForTool.skippedAlreadyInstalled($)),X}let q=Y.binaries&&Y.binaries.length>0?Y.binaries:[];if(q.length===0)return G.debug(K$.generateForTool.skippedNoBinaries($)),X;let U=q.map((H)=>typeof H==="string"?H:H.name);for(let H of U){let K=await this.generateShimForBinary(J,$,Y,H,R,W);if(K)X.push(K)}return X}async generateShimForBinary($,I,M,G,J,Q){let Y=this.logger.getSubLogger({name:"generateShimForBinary"}),X=this.config.paths.targetDir,R=T6.join(X,G);if(Y.debug(K$.generateShim.resolvedShimPath(R)),await $.exists(R)){if(!await this.isGeneratedShim($,R)){if(!Q)return Y.error(K$.generateShim.conflictingFile(I,R)),null;Y.debug(K$.generateShim.overwritingConflict(R))}else if(!J)return Y.debug(K$.generateShim.existingShim(R)),null}let W=T6.join(this.config.paths.binariesDir,I,"current",G);Y.debug(K$.generateShim.resolvedBinaryPath(I,G,W));let q=I.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),U=this.missingBinaryMessagesByMethod.get(M.installationMethod),H=U?`echo "${U.replaceAll('"',"\\\"")}" >&2`:'echo "Installation completed but binary not found at: $TOOL_EXECUTABLE" >&2',K=c(`
162
162
  #!/usr/bin/env bash
163
- # Shim for ${Q}
163
+ # Shim for ${G}
164
164
  # Generated by Dotfiles Management Tool
165
165
 
166
166
  set -euo pipefail
167
167
 
168
- TOOL_NAME="${M}"
169
- BINARY_NAME="${Q}"
170
- TOOL_EXECUTABLE="${I}"
171
- GENERATOR_CLI_EXECUTABLE="${sM()}"
168
+ TOOL_NAME="${I}"
169
+ BINARY_NAME="${G}"
170
+ TOOL_EXECUTABLE="${W}"
171
+ GENERATOR_CLI_EXECUTABLE="${tI()}"
172
172
  CONFIG_PATH="${this.config.configFilePath}"
173
173
 
174
174
  # Check for recursion
175
- RECURSION_ENV_VAR="DOTFILES_INSTALLING_${U}"
175
+ RECURSION_ENV_VAR="DOTFILES_INSTALLING_${q}"
176
176
 
177
177
  if [ -n "\${!RECURSION_ENV_VAR:-}" ]; then
178
178
  echo "Recursive installation detected for $TOOL_NAME. Aborting to prevent infinite loop." >&2
@@ -219,11 +219,11 @@ ${T}`)}return A.data}async function m1($){return ZQ.parse({})}async function c9(
219
219
  exit $install_exit_code
220
220
  fi
221
221
  fi
222
- `);X.debug(_$.generateShim.generatedContent(Q)),await this.fs.ensureDir(x6.dirname(q)),await $.writeFile(q,_);let O=493;try{if(((await $.stat(q)).mode&511)!==O)await $.chmod(q,O)}catch{await $.chmod(q,O)}return X.debug(_$.generateShim.success(Q,q,$.constructor.name)),q}async isGeneratedShim($,M){try{try{if((await $.lstat(M)).isSymbolicLink())return!0}catch{}return(await $.readFile(M,"utf8")).includes("# Generated by Dotfiles Management Tool")}catch{return!1}}}import k6 from"path";var h={generate:{processingTool:($)=>W(`Processing symlinks for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`)},process:{symlinkDetails:($,M,J,Q)=>W(`Processing symlink: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping symlink creation.`)},filesystem:{backupFailed:($)=>W(`Failed to write backup of ${$}`),deleteFailed:($)=>W(`Failed to delete ${$}`),directoryCreateFailed:($)=>W(`Failed to create directory ${$}`),symlinkFailed:($,M)=>W(`Failed to create symlink ${$} \u2192 ${M}`),symlinkAlreadyExists:($,M)=>W(`Symlink already exists and is valid: ${$} -> ${M}`),creatingSymlink:($,M)=>W(`Creating symlink: ${$} -> ${M}`),symlinkCreated:($,M)=>W(`Successfully created symlink: ${$} -> ${M}`),removingBrokenSymlink:($)=>W(`Removing broken symlink: ${$}`)},copy:{processingTool:($)=>W(`Processing copies for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`),copyDetails:($,M,J,Q)=>W(`Processing copy: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping copy.`),copyFailed:($,M)=>W(`Failed to copy ${$} \u2192 ${M}`)}};class S6{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"CopyGenerator"})}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $){let G=$[Y];if(!G)continue;let X=Y$(G,this.systemInfo);if(!this.shouldProcessTool(X,Y,J))continue;let Z=J.getSubLogger({context:Y}),q=this.fs instanceof f?this.fs.withToolName(Y):this.fs;Z.debug(h.copy.processingTool(Y));for(let I of X.copies){let U=await this.processCopy(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.copy.missingToolConfig(M)),!1;if(!$.copies||$.copies.length===0)return!1;return!0}async processCopy($,M,J,Q,Y){let G=Y.getSubLogger({name:"processCopy"}),{overwrite:X=!1,backup:Z=!1}=Q,q=RM($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=RM($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(G.debug(h.copy.copyDetails(M.source,q,M.target,I)),!await J.exists(q))return G.error(h.copy.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.copy.sourceMissing($.name,q)};if(await J.exists(I)){if(G.debug(h.copy.targetExists(I)),!X)return G.debug(h.copy.skipExistingTarget(I)),{success:!0,sourcePath:q,targetPath:I,status:"skipped_exists"};let K=await this.handleOverwrite(I,J,Z,G);if(K.failed)return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:K.error};return this.performCopy(q,I,J,K.status,G)}return this.performCopy(q,I,J,"created",G)}async handleOverwrite($,M,J,Q){if(J){let Y=`${$}.bak`;try{if(await M.exists(Y))await M.rm(Y,{recursive:!0,force:!0});return await M.rename($,Y),{failed:!1,status:"backed_up"}}catch{let G=h.filesystem.backupFailed($);return Q.error(G),{failed:!0,error:G}}}try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1,status:"updated_target"}}catch{let Y=h.filesystem.deleteFailed($);return Q.error(Y),{failed:!0,error:Y}}}async performCopy($,M,J,Q,Y){let G=Y.getSubLogger({name:"performCopy"}),X=k6.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{if((await J.stat($)).isDirectory())await this.copyDirectory($,M,J);else await J.copyFile($,M);return{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.copy.copyFailed($,M);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}async copyDirectory($,M,J){await J.ensureDir(M);let Q=await J.readdir($);for(let Y of Q){let G=k6.join($,Y),X=k6.join(M,Y);if((await J.stat(G)).isDirectory())await this.copyDirectory(G,X,J);else await J.copyFile(G,X)}}}import a$ from"path";class w6{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"SymlinkGenerator"})}async createBinarySymlink($,M,J){let Q=$.getSubLogger({name:"createBinarySymlink"});try{if((await this.fs.lstat(J)).isSymbolicLink()){let I=await this.fs.readlink(J),U=a$.resolve(a$.dirname(J),I),K=a$.resolve(M);if(U===K){if(await this.fs.exists(U)){Q.debug(h.filesystem.symlinkAlreadyExists(J,U));return}}await this.fs.rm(J,{force:!0})}else await this.fs.rm(J,{force:!0})}catch{}if(!await this.fs.exists(M))throw Error(`Cannot create symlink: binary does not exist at ${M}`);Q.debug(h.filesystem.creatingSymlink(J,M)),await this.fs.symlink(M,J);let G=await this.fs.readlink(J),X=a$.resolve(a$.dirname(J),G),Z=a$.resolve(M);if(X!==Z)throw Error(`Symlink verification failed: ${J} points to ${X}, expected ${Z}`);Q.debug(h.filesystem.symlinkCreated(J,M))}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $){let G=$[Y];if(!G)continue;let X=Y$(G,this.systemInfo);if(!this.shouldProcessTool(X,Y,J))continue;let Z=J.getSubLogger({context:Y}),q=this.fs instanceof f?this.fs.withToolName(Y):this.fs;Z.debug(h.generate.processingTool(Y));for(let I of X.symlinks){let U=await this.processSymlink(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.generate.missingToolConfig(M)),!1;if(!$.symlinks||$.symlinks.length===0)return!1;return!0}async processSymlink($,M,J,Q,Y){let G=Y.getSubLogger({name:"processSymlink"}),{overwrite:X=!1,backup:Z=!1}=Q,q=RM($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=RM($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(G.debug(h.process.symlinkDetails(M.source,q,M.target,I),M.source,q,M.target,I),!await J.exists(q))return G.error(h.process.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.process.sourceMissing($.name,q)};let U=await this.handleExistingTarget(q,I,J,{overwrite:X,backup:Z},G);if(U.shouldSkip){if(U.status==="failed")return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:U.error??"Unknown error"};if(U.status==="skipped_correct"&&J instanceof f)await J.recordExistingSymlink(q,I);return{success:!0,sourcePath:q,targetPath:I,status:U.status}}return await this.createSymlink(q,I,J,U.status,G)}async handleExistingTarget($,M,J,Q,Y){let G=Y.getSubLogger({name:"handleExistingTarget"});if(!await J.exists(M)){let q=await this.removeBrokenSymlink(M,J,G);if(q.failed)return{shouldSkip:!0,status:"failed",error:q.error};return{shouldSkip:!1,status:"created"}}if(G.debug(h.process.targetExists(M)),(await this.checkCorrectSymlink($,M,J)).isCorrect)return{shouldSkip:!0,status:"skipped_correct"};if(!Q.overwrite)return G.debug(h.process.skipExistingTarget(M)),{shouldSkip:!0,status:"skipped_exists"};return await this.handleOverwrite(M,J,Q.backup,G)}async checkCorrectSymlink($,M,J){try{if((await J.lstat(M)).isSymbolicLink()){let Y=await J.readlink(M),G=a$.resolve(a$.dirname(M),Y),X=a$.resolve($);return{isCorrect:G===X}}}catch{}return{isCorrect:!1}}async handleOverwrite($,M,J,Q){let Y=Q.getSubLogger({name:"handleOverwrite"}),G="updated_target";if(J){let X=await this.createBackup($,M,Y);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error};G="backed_up"}else{let X=await this.deleteTarget($,M,Y);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error}}return{shouldSkip:!1,status:G}}async createBackup($,M,J){let Q=J.getSubLogger({name:"createBackup"}),Y=`${$}.bak`;try{if(await M.exists(Y))await M.rm(Y,{recursive:!0,force:!0});return await M.rename($,Y),{failed:!1}}catch{let G=h.filesystem.backupFailed($);return Q.error(G),{failed:!0,error:G}}}async deleteTarget($,M,J){let Q=J.getSubLogger({name:"deleteTarget"});try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1}}catch{let Y=h.filesystem.deleteFailed($);return Q.error(Y),{failed:!0,error:Y}}}async removeBrokenSymlink($,M,J){let Q=J.getSubLogger({name:"removeBrokenSymlink"});try{if((await M.lstat($)).isSymbolicLink())Q.debug(h.filesystem.removingBrokenSymlink($)),await M.rm($,{force:!0});return{failed:!1}}catch{return{failed:!1}}}async createSymlink($,M,J,Q,Y){let G=Y.getSubLogger({name:"createSymlink"}),X=a$.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{return await J.symlink($,M),{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.filesystem.symlinkFailed($,M);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}}import{eq as V4,gt as z4,valid as JG}from"semver";var y$={initializing:()=>W("Initializing VersionChecker with githubClient"),fetchingLatestRelease:($,M)=>W(`Fetching latest version for ${$}/${M}`),latestReleaseFound:($)=>W(`Latest release found ${$}`),latestReleaseError:($,M)=>W(`Failed to fetch latest release for ${$}/${M}`),noLatestRelease:($,M)=>W(`No latest release found for ${$}/${M}`),comparingVersions:($,M)=>W(`Comparing versions configured ${$} vs latest ${M}`),invalidConfiguredVersion:($)=>W(`Configured version invalid ${$}`),invalidLatestVersion:($)=>W(`Latest version invalid ${$}`),versionComparisonResult:($)=>W(`Version comparison result ${$}`)};class b6{githubClient;logger;constructor($,M){this.logger=$.getSubLogger({name:"VersionChecker"}),this.logger.debug(y$.initializing()),this.githubClient=M}async getLatestToolVersion($,M){let J=this.logger.getSubLogger({name:"getLatestToolVersion"});J.debug(y$.fetchingLatestRelease($,M));try{let Q=await this.githubClient.getLatestRelease($,M);if(Q?.tag_name){let Y=Q.tag_name.replace(/^v/,"");return J.debug(y$.latestReleaseFound(Y)),Y}return J.debug(y$.noLatestRelease($,M)),null}catch(Q){return J.debug(y$.latestReleaseError($,M),Q),null}}async checkVersionStatus($,M){let J=this.logger.getSubLogger({name:"checkVersionStatus"});J.debug(y$.comparingVersions($,M));let Q=$.replace(/^v/,""),Y=M.replace(/^v/,"");if(!JG(Q))return J.debug(y$.invalidConfiguredVersion(Q)),"INVALID_CURRENT_VERSION";if(!JG(Y))return J.debug(y$.invalidLatestVersion(Y)),"INVALID_LATEST_VERSION";if(z4(Y,Q))return J.debug(y$.versionComparisonResult("NEWER_AVAILABLE")),"NEWER_AVAILABLE";if(V4(Y,Q))return J.debug(y$.versionComparisonResult("UP_TO_DATE")),"UP_TO_DATE";return J.debug(y$.versionComparisonResult("AHEAD_OF_LATEST")),"AHEAD_OF_LATEST"}}import G5 from"net";import K0 from"path";import{realpath as B4}from"fs/promises";import D4 from"path";var QG={name:"bin",description:"Print the real path to a binary",hasPositionalArg:!0,positionalArgDescription:"binary name",positionalArgType:"tool"};async function A4($,M,J,Q,Y,G,X){let Z=await G.loadSingleToolConfig($,M,J,Q,Y,X);if(Z){let K=(Y$(Z,X).binaries??[])[0],H=K?typeof K==="string"?K:K.name:M;return{toolName:M,binaryName:H}}let q=await G.loadToolConfigByBinary($,M,J,Q,Y,X);if(q&&!("error"in q))return{toolName:q.name,binaryName:M};return}async function E4($,M,J){let{projectConfig:Q,fs:Y,configService:G,systemInfo:X}=J,Z=$.getSubLogger({minLevel:7}),q=await A4(Z,M,Q.paths.toolConfigsDir,Y,Q,G,X);if(!q)return x.ERROR;let{toolName:I,binaryName:U}=q,K=D4.join(Q.paths.binariesDir,I,"current",U);try{let H=await B4(K);return process.stdout.write(H),x.SUCCESS}catch{return x.ERROR}}function YG($,M,J){let Q=$.getSubLogger({name:"registerBinCommand"});M.command("bin <name>").description("Print the absolute real path to a binary (resolving symlinks). Accepts tool name or binary name (from .bin()).").action(async(Y)=>{let G=await J(),X=await E4(Q,Y,G);N(X)})}import GG from"path";var R={proxyUnavailable:($)=>W(`HTTP proxy not available on port ${$}. Start with 'bun proxy' or unset DEV_PROXY env var.`),proxyEnabled:($)=>W(`Routing requests through HTTP proxy on port ${$}`),proxyCheckingAvailability:($)=>W(`Checking proxy availability on port ${$}`),commandActionStarted:($,M)=>W(`${$} command action logic started${M?`. Tool: ${M}`:""}`),commandConfigErrorDetails:()=>W("Configuration loading error details: %O"),dryRunEnabled:()=>W("Dry run enabled. Initializing MemFileSystem"),componentInitialized:($)=>W(`${$} initialized`),toolConfigsLoading:($)=>W(`tool config loading: ${$}`),toolConfigsLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigsForDryRun:()=>W("tool configs for dry run"),commandCompleted:($)=>W(`DONE${$?" (dry run)":""}`),commandExecutionFailed:($,M)=>W(`Command failed [${$}] exit ${M}`),commandVersionComparison:($,M,J)=>W(`Tool: ${$}, Configured: ${M}, Latest: ${J}`),commandUnsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`),toolNotFound:($,M)=>W(`Tool "${$}" not found in ${M}`),toolInstalled:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),toolAlreadyInstalled:($,M)=>W(`Tool "${$}" \`${M}\` is already installed`),toolInstallSkippedConfigurationOnly:($)=>W(`Tool "${$}" has no installation steps`),shimDeleted:($,M)=>W(`Deleted temporary shim ${$} at ${M}`),toolNoConfigurationsFound:($)=>W(`No tool configurations found in ${$}`),toolCheckingUpdates:($)=>W(`updates for ${$}`),toolUpdateAvailable:($,M,J)=>W(`Update available for ${$}: ${M} -> ${J}`),toolUpToDate:($,M,J)=>W(`${$} (${M}) is up to date. Latest: ${J}`),toolAheadOfLatest:($,M,J)=>W(`${$} (${M}) is ahead of the latest known version (${J})`),toolConfiguredToLatest:($,M)=>W(`Tool "${$}" is configured to 'latest'. The latest available version is ${M}`),toolVersionComparisonFailed:($,M,J)=>W(`Could not determine update status for ${$} (${M}) against latest ${J}`),toolShimUpToDate:($,M)=>W(`${$} is already up to date (${M})`),toolShimOnLatest:($,M)=>W(`${$} is already on latest version (${M})`),toolShimUpdateStarting:($,M,J)=>W(`Updating ${$} from ${M} to ${J}...`),toolProcessingUpdate:($,M,J)=>W(`${$} update from ${M} to ${J}`),toolShimUpdateSuccess:($,M)=>W(`${$} successfully updated to ${M}`),toolUpdated:($,M,J)=>W(`Tool "${$}" updated from \`${M}\` to \`${J}\``),toolUpdateFailed:($,M)=>W(`Update failed for tool "${$}": ${M}`),toolVersionPinned:($,M)=>W(`Tool "${$}" is pinned to version \`${M}\`. Set version to "latest" in the tool config to enable updates`),toolUpdateNotSupported:($,M)=>W(`Tool "${$}" uses ${M} which does not support updates. Performing regular install instead`),commandCheckingUpdatesFor:($)=>W(`Checking "${$}" for updates`),commandCheckingUpdatesForAll:()=>W("Checking all tools for updates"),fsReadFailed:($)=>W(`Failed to read ${$}`),fsAccessDenied:($,M)=>W(`Access denied ${$}: ${M}`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsWrite:($,M)=>W(`[${$}] write ${M}`),toolConflictsDetected:($,M)=>W(`${$}
223
- ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles:()=>W("Registry-based cleanup: Removing all tracked files"),cleanupRegistryDatabase:()=>W("registry database cleanup"),cleanupRegistryDryRun:()=>W("Would clean up registry database (dry run)"),cleanupToolFiles:($)=>W(`Registry-based cleanup: files for tool '${$}'`),cleanupRegistryTool:($,M)=>W(M?`Would remove registry entries for tool: ${$} (dry run)`:`Removed registry entries for tool: ${$}`),cleanupTypeFiles:($)=>W(`Registry-based cleanup: files of type '${$}'`),cleanupFoundFiles:($,M,J)=>W(`Found ${$} files for tool '${M}'${J?` of type '${J}'`:""}`),cleanupFileRemoved:($)=>W(`[cleanup] rm ${$}`),fileCleanupDryRun:($)=>W(`Would delete: ${$}`),cleanupFileNotFound:($)=>W(`file not found ${$}`),cleanupDeleteFailed:($)=>W(`Failed to delete ${$}`),cleanupProcessStarted:($)=>W(`starting cleanup process, dryRun=${$}: %O`),configParameterOverridden:($,M)=>W(`${$.charAt(0).toUpperCase()+$.slice(1)} overridden to: ${M}`),cleanupProcessFinished:($)=>W(`cleanup process finished, dryRun=${$}`),logCheckingFileStates:()=>W("Checking file states for all tools"),logFileStatesForTool:($)=>W(`${$} files`),logFileStatus:($,M,J,Q,Y)=>W(`${$} ${M} [${J}] - ${Q}${Y}`),logTargetStatus:($,M)=>W(`${$} ${M}`),logNoOperationsFound:()=>W("No file operations found matching criteria"),logOperationHistory:($,M,J)=>W(`${$} ${M}${J?` ${J}`:""}`),cachingDisabled:()=>W("Caching disabled"),registryInitialized:($)=>W(`File tracking initialized: ${$}`),cliStarted:()=>W("CLI starting with arguments"),serviceGithubResourceNotFound:($,M)=>W(`GitHub ${$} not found: ${M}`),serviceGithubApiFailed:($,M)=>W(`GitHub API failed [${$}] ${M}`),configLoadFailed:($)=>W(`Failed to load configuration from ${$}`),configPathResolved:($)=>W(`Using configuration: ${$}`),configNotFound:()=>W("No configuration file found. Create dotfiles.config.ts or specify --config <path>"),configParameterIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configParameterInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),updatesCommandCompleted:()=>W("Check-updates command completed"),toolTypesGenerated:($)=>W(`Generated tool types: ${$}`),toolNotInstalled:($)=>W(`Tool "${$}" is not installed`),installPathNotFound:($)=>W(`Installation path not found: ${$}`),filesCommandShowingTree:($)=>W($),filesCommandEmptyDirectory:()=>W("(empty directory)"),filesCommandTree:($)=>W($),skillAlreadyExists:($)=>W(`Destination already exists, removing: ${$}`),skillDryRun:($,M)=>W(`Would copy skill: ${M} -> ${$}`),skillCopied:($,M)=>W(`Copied skill: ${M} -> ${$}`),skillCopyFailed:($)=>W(`Failed to copy skill to: ${$}`),cliCompletionGenerated:($)=>W(`CLI completion generated: ${$}`),dashboardStopping:()=>W("Stopping dashboard server"),dashboardBrowserOpenFailed:()=>W("Failed to open browser"),toolLookupByBinaryStarted:($)=>W(`Tool not found by name '${$}', searching by binary name`),toolFoundByBinary:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),toolNotFoundByBinary:($,M)=>W(`No tool or binary named "${$}" found in ${M}`),envCreated:($)=>W(`Environment created at ${$}`),envDeleted:($)=>W(`Environment deleted at ${$}`),envNotFound:($)=>W(`Environment not found at ${$}`),envOperationFailed:($,M)=>W(`Environment ${$} failed: ${M}`),envDeletionCancelled:()=>W("Deletion cancelled"),envActivationHint:($)=>W(`To activate: source ${$}/source`),envConfigPath:($)=>W(`Config file: ${$}`),envConfigFromEnvVar:($)=>W(`Using config from DOTFILES_ENV_DIR: ${$}`)};var XG={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function F4($,M,J,Q,Y,G){let X={};if(J){$.debug(R.commandCheckingUpdatesFor(J));try{let Z=await M.loadSingleToolConfig($,J,Q.paths.toolConfigsDir,Y,Q,G);if(Z)X[J]=Z;else return $.error(R.toolNotFound(J,Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),null}}else try{if($.debug(R.commandCheckingUpdatesForAll()),X=await M.loadToolConfigs($,Q.paths.toolConfigsDir,Y,Q,G),Object.keys(X).length===0)return $.error(R.toolNoConfigurationsFound(Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed("tool configurations"),Z),null}return X}function L4($,M,J,Q,Y){let G=new Date().toISOString().replace(/:/g,"-").split(".")[0],X=$.configFilePath?GG.dirname($.configFilePath):M.paths.toolConfigsDir,Z=GG.join(M.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:X,currentDir:Z,stagingDir:"",timestamp:G||"",systemInfo:J,toolConfig:$,projectConfig:M,$:$M(W$(),process.env),fileSystem:Q,replaceInFile:(I,U,K,H)=>c0(Q,I,U,K,H),resolve:()=>{throw Error("resolve not supported in version check context")},log:IQ(Y,$.name)}}async function x4($,M,J,Q,Y,G){if(Q==="latest"){$.info(R.toolConfiguredToLatest(J.name,Y));return}if(G){$.info(R.toolUpdateAvailable(J.name,Q,Y));return}let X=await M.checkVersionStatus(Q,Y);if(X==="UP_TO_DATE")$.info(R.toolUpToDate(J.name,Q,Y));else if(X==="AHEAD_OF_LATEST")$.info(R.toolAheadOfLatest(J.name,Q,Y));else $.warn(R.toolVersionComparisonFailed(J.name,Q,Y))}async function T4($,M,J){let{projectConfig:Q,versionChecker:Y,pluginRegistry:G,systemInfo:X,fs:Z}=J,q=L4(M,Q,X,Z,$),I=G.get(M.installationMethod);if(!I){$.warn(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}if(!I.supportsUpdateCheck||!I.supportsUpdateCheck()){$.info(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}let U=await I.checkUpdate?.(M.name,M,q,$);if(!U){$.warn(R.commandUnsupportedOperation("check-updates",M.name));return}if(!U.success){$.error(R.serviceGithubApiFailed("check update",0),Error(U.error));return}let K=U.currentVersion||M.version||"unknown",H=U.latestVersion||"unknown";await x4($,Y,M,K,H,U.hasUpdate)}async function k4($,M,J){$.trace(R.commandActionStarted("check-updates",M||"all"));let Q=await F4($,J.configService,M,J.projectConfig,J.fs,J.systemInfo);if(!Q)return;for(let Y of Object.values(Q))await T4($,Y,J)}function ZG($,M,J){let Q=$.getSubLogger({name:"registerCheckUpdatesCommand"});M.command("check-updates [toolName]").description("Checks for available updates for configured tools. If [toolName] is provided, checks only that tool.").action(async(Y)=>{try{let G=await J();await k4(Q,Y,G)}catch(G){Q.error(R.commandExecutionFailed("check-updates",x.ERROR),G),N(x.ERROR)}})}var WG={name:"cleanup",description:"Clean up generated files and registry entries",options:[{flag:"--tool",description:"Cleanup files for specific tool",hasArg:!0,argPlaceholder:"<name>"},{flag:"--type",description:"Cleanup files of specific type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--all",description:"Cleanup all tracked files"}]};async function S4($,M,J,Q,Y){$.info(R.cleanupAllTrackedFiles());let G=await J.getRegisteredTools();for(let X of G)await qG($,M,J,X,Q,void 0,Y);if(!Y){for(let X of G)await J.removeToolOperations(X);$.info(R.cleanupRegistryDatabase())}else $.info(R.cleanupRegistryDryRun())}async function w4($,M,J,Q,Y,G,X){if($.info(R.cleanupToolFiles(Q)),await qG($,M,J,Q,Y,G,X),!X)await J.removeToolOperations(Q),$.info(R.cleanupRegistryTool(Q,!1));else $.info(R.cleanupRegistryTool(Q,!0))}async function b4($,M,J,Q,Y,G){$.info(R.cleanupTypeFiles(Q));let X=await J.getOperations({fileType:Q});for(let Z of X){let q=await J.getFileState(Z.filePath);if(q&&q.lastOperation!=="rm")await IG($,M,Z.filePath,Y,G)}}async function N4($,M,J){let{fs:Q,fileRegistry:Y}=M,{dryRun:G,tool:X,type:Z,all:q}=J,I=M.projectConfig.paths.homeDir;if(q)await S4($,Q,Y,I,G);else if(X)await w4($,Q,Y,X,I,Z,G);else if(Z)await b4($,Q,Y,Z,I,G);else $.warn(R.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function qG($,M,J,Q,Y,G,X){let Z=await J.getFileStatesForTool(Q),q=Z;if(G)q=Z.filter((I)=>I.fileType===G);$.trace(R.cleanupFoundFiles(q.length,Q,G));for(let I of q)if(I.lastOperation!=="rm"){let U=I.fileType==="symlink"&&I.targetPath?I.targetPath:I.filePath;await IG($,M,U,Y,X||!1)}}async function IG($,M,J,Q,Y){try{if(await M.exists(J))if(!Y)await M.rm(J,{force:!0}),$.info(R.cleanupFileRemoved(s(Q,J)));else $.info(R.fileCleanupDryRun(J));else $.debug(R.cleanupFileNotFound(J))}catch(G){$.error(R.cleanupDeleteFailed(J),G)}}async function v4($,M,J){let{dryRun:Q,tool:Y,type:G,all:X}=M;try{$.trace(R.cleanupProcessStarted(Q),M);let Z={...M,all:X||!Y&&!G};await N4($,J,Z),$.trace(R.cleanupProcessFinished(Q))}catch(Z){$.error(R.commandExecutionFailed("cleanup",1),Z),N(1)}}function UG($,M,J){let Q=$.getSubLogger({name:"registerCleanupCommand"});M.command("cleanup").description("Remove all generated artifacts, including shims, shell configurations, and the .generated directory.").option("--tool <name>","Remove files for specific tool only (registry-based)").option("--type <type>","Remove files of specific type only (registry-based)").option("--all","Remove all tracked files (registry-based)").action(async(Y)=>{let G={...Y,...M.opts()},X=await J();await v4(Q,G,X)})}import{Command as y4}from"commander";var KG={name:"dotfiles",description:"Dotfiles management CLI",options:[{flag:"--config",description:"Path to configuration file",hasArg:!0,argPlaceholder:"<path>"},{flag:"--dry-run",description:"Simulate operations without changes"},{flag:"--log",description:"Set log level",hasArg:!0,argPlaceholder:"<level>"},{flag:"--verbose",description:"Enable detailed debug messages"},{flag:"--quiet",description:"Suppress informational output"},{flag:"--platform",description:"Override detected platform",hasArg:!0,argPlaceholder:"<platform>"},{flag:"--arch",description:"Override detected architecture",hasArg:!0,argPlaceholder:"<arch>"}]};function HG(){return new y4().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.5").option("--config <path>","Path to a configuration file","").option("--dry-run","Simulate all operations without making changes to the file system",!1).option("--trace","Show file paths and line numbers in log output",!1).option("--log <level>",`Set log level (${WQ.join(", ")})`,"default").option("--verbose","Enable detailed debug messages (alias for --log=verbose)",!1).option("--quiet","Suppress all informational and debug output. Errors are still displayed (alias for --log=quiet)",!1).option("--platform <platform>",`Override the detected platform (${m0.join(", ")})`).option("--arch <arch>",`Override the detected architecture (${g0.join(", ")})`)}import r4 from"fs";import t4 from"path";var b={serverStarted:($)=>W(`Dashboard available at ${$}`),serverStopping:()=>W("Stopping dashboard server"),serverStopped:()=>W("Dashboard server stopped"),requestReceived:($,M)=>W(`${$} ${M}`),apiError:($)=>W(`API error in ${$}`),installFailed:($)=>W(`Installation failed: ${$}`),installSucceeded:()=>W("Installation succeeded"),checkUpdateCompleted:($,M,J)=>W(`Update check complete: hasUpdate=${$} current=${M} latest=${J}`),checkUpdateFailed:($)=>W(`Update check failed: ${$}`),updateNotSupported:($)=>W(`Update not supported for method ${$}`),updateFailed:($)=>W(`Update failed: ${$}`),updateSucceeded:($,M)=>W(`Updated from ${$} to ${M}`)};function P4($){let M=[];if($&1)M.push("Linux");if($&2)M.push("macOS");if($&4)M.push("Windows");return M}function C4($){let M=[];if($&1)M.push("x86_64");if($&2)M.push("arm64");return M}function _G($){let M={};if(typeof $.repo==="string")M.repo=$.repo;if(typeof $.assetPattern==="string")M.assetPattern=$.assetPattern;if(typeof $.ghCli==="boolean")M.ghCli=$.ghCli;if(typeof $.crate==="string")M.crate=$.crate;if(typeof $.crateName==="string")M.crate=$.crateName;if(typeof $.formula==="string")M.formula=$.formula;if(typeof $.url==="string")M.url=$.url;return M}function d4($){let M={};if("installParams"in $&&$.installParams){let Q=$.installParams;Object.assign(M,_G(Q))}let J;if($.platformConfigs&&$.platformConfigs.length>0)J=$.platformConfigs.map((Q)=>{let Y={platforms:P4(Q.platforms)};if(Q.architectures!==void 0)Y.architectures=C4(Q.architectures);let G=Q.config;if(G.installationMethod)Y.installationMethod=G.installationMethod;if(G.installParams)Y.installParams=_G(G.installParams);if(G.binaries)Y.binaries=G.binaries;if(G.symlinks)Y.symlinks=G.symlinks;return Y});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:M,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:J}}function u4($,M){let J=M.get($);if(!J)return{status:"not-installed",installedVersion:null,installedAt:null,installPath:null,binaryPaths:[],hasUpdate:!1};return{status:"installed",installedVersion:J.version,installedAt:J.installedAt.toISOString(),installPath:J.installPath,binaryPaths:J.binaryPaths||[],hasUpdate:!1}}function RG($,M,J,Q,Y,G){return{config:d4($),runtime:u4($.name,M),files:J,binaryDiskSize:Y,usage:G}}function P$($){return new Date($).toISOString()}function U0($){let J=Date.now()-$,Q=Math.floor(J/1000);if(Q<60)return"just now";let Y=Math.floor(Q/60);if(Y<60)return`${Y} minute${Y===1?"":"s"} ago`;let G=Math.floor(Y/60);if(G<24)return`${G} hour${G===1?"":"s"} ago`;let X=Math.floor(G/24);if(X<30)return`${X} day${X===1?"":"s"} ago`;let Z=Math.floor(X/30);return`${Z} month${Z===1?"":"s"} ago`}async function OG($,M,J=20){try{let Y=(await M.fileRegistry.getOperations()).toSorted((Z,q)=>q.createdAt-Z.createdAt),G=Y.length;return{success:!0,data:{activities:Y.slice(0,J).map((Z)=>({id:Z.id,toolName:Z.toolName,action:Z.operationType,description:`${Z.operationType} ${Z.fileType}: ${Z.filePath}`,timestamp:P$(Z.createdAt),relativeTime:U0(Z.createdAt)})),totalCount:G}}}catch(Q){return $.error(b.apiError("getActivity"),Q),{success:!1,error:"Failed to retrieve activity feed"}}}async function jG($,M){try{let J=M.projectConfig.paths;return{success:!0,data:{dotfilesDir:J.dotfilesDir,generatedDir:J.generatedDir,binariesDir:J.binariesDir,targetDir:J.targetDir,toolConfigsDir:J.toolConfigsDir}}}catch(J){return $.error(b.apiError("getConfig"),J),{success:!1,error:"Failed to retrieve configuration"}}}import y0 from"path";async function f4($){let{fs:M,projectConfig:J}=$,Q=J.paths.binariesDir,Y=[];if(!await M.exists(Q))return[];let G=await M.readdir(Q);for(let X of G){let Z=y0.join(Q,X);if(!(await M.stat(Z).catch(()=>null))?.isDirectory())continue;let I=await M.readdir(Z),U=y0.join(Z,"current"),K=null;if(I.includes("current")){if((await M.lstat(U).catch(()=>null))?.isSymbolicLink()){let _=await M.readlink(U).catch(()=>null);if(_)K=y0.isAbsolute(_)?_:y0.resolve(Z,_)}}for(let H of I){if(H==="current")continue;let _=y0.join(Z,H);if(!(await M.lstat(_).catch(()=>null))?.isDirectory())continue;if(K!==_)Y.push(_)}}return Y}async function VG($,M){try{let J=[],Q=await f4(M);if(Q.length>0)J.push({name:"Unused Binaries",status:"warn",message:"",details:Q});let G=await M.fileRegistry.validate();J.push({name:"Registry Integrity",status:G.valid?"pass":"warn",message:G.valid?"Registry is healthy":`Found ${G.issues.length} issues`,details:G.issues});let Z=(await M.toolInstallationRegistry.getAllToolInstallations()).length;J.push({name:"Tool Installations",status:Z>0?"pass":"warn",message:`${Z} tool${Z===1?"":"s"} installed`});let q=J.some((H)=>H.status==="fail"),I=J.some((H)=>H.status==="warn");return{success:!0,data:{overall:q?"unhealthy":I?"warning":"healthy",checks:J,lastCheck:new Date().toISOString()}}}catch(J){return $.error(b.apiError("getHealth"),J),{success:!1,error:"Failed to retrieve health status"}}}import N6 from"path";async function zG($,M){let J=$.fs,Q=0;try{if(!await J.exists(M))return 0;let Y=await J.readdir(M);for(let G of Y){let X=N6.join(M,G),Z=await J.stat(X);if(Z.isDirectory())Q+=await zG($,X);else if(Z.isFile())Q+=Z.size}}catch{}return Q}async function v6($,M){let J=N6.join($.projectConfig.paths.generatedDir,"binaries"),Q=N6.join(J,M);return zG($,Q)}var hJ=null;async function p4(){let $=new Map;try{let M=Bun.spawn(["git","rev-parse","--show-toplevel"],{stdout:"pipe",stderr:"pipe"}),J=(await new Response(M.stdout).text()).trim();if(await M.exited!==0||!J)return $;let Y=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),G=await new Response(Y.stdout).text();if(await Y.exited!==0)return $;let Z=G.split(`
224
- `),q=null;for(let I of Z){let U=I.trim();if(!U)continue;if(/^\d{4}-\d{2}-\d{2}/.test(U))q=new Date(U);else if(q){let K=`${J}/${U}`;if(!$.has(K))$.set(K,q)}}}catch{}return $}async function c4($){try{let M=Bun.spawn(["git","log","--diff-filter=A","--format=%aI","--",$],{stdout:"pipe",stderr:"pipe"}),J=await new Response(M.stdout).text();if(await M.exited!==0||!J.trim())return null;let Y=J.trim().split(`
225
- `)[0];if(!Y)return null;return new Date(Y)}catch{return null}}async function y6($){if(!hJ)hJ=await p4();let M=hJ.get($);if(M)return M;let J=await c4($);if(J)hJ.set($,J);return J}var mJ=null;async function R$($,M){if(mJ)return mJ;let{projectConfig:J,fs:Q,configService:Y,systemInfo:G}=M;return mJ=await Y.loadToolConfigs($,J.paths.toolConfigsDir,Q,J,G),mJ}async function BG($,M,J=10){try{let Q=M.projectConfig.paths.toolConfigsDir,Y=[];async function G(I){let U=await M.fs.readdir(I);for(let K of U){let H=`${I}/${K}`;if((await M.fs.stat(H)).isDirectory())await G(H);else if(K.endsWith(".tool.ts")){let O=K.replace(/\.tool\.ts$/,"");Y.push({name:O,configFilePath:H})}}}return await G(Q),{success:!0,data:{tools:(await Promise.all(Y.map(async(I)=>{let U=await y6(I.configFilePath);if(U)return{name:I.name,configFilePath:I.configFilePath,timestamp:U.getTime(),source:"git"};let K=await M.fs.stat(I.configFilePath);return{name:I.name,configFilePath:I.configFilePath,timestamp:K.mtimeMs,source:"mtime"}}))).toSorted((I,U)=>U.timestamp-I.timestamp).slice(0,J).map((I)=>({name:I.name,configFilePath:I.configFilePath,createdAt:P$(I.timestamp),relativeTime:U0(I.timestamp),timestampSource:I.source}))}}}catch(Q){return $.error(b.apiError("getRecentTools"),Q),{success:!1,error:"Failed to retrieve recent tools"}}}async function DG($,M){try{let J=await M.fileRegistry.getOperations({fileType:"completion"}),Q=await M.fileRegistry.getOperations({fileType:"init"}),Y=new Map;for(let I of J){let U=Y.get(I.filePath);if(!U||I.createdAt>U.createdAt)Y.set(I.filePath,I)}let G=new Map;for(let I of Q){let U=G.get(I.filePath);if(!U||I.createdAt>U.createdAt)G.set(I.filePath,I)}let X=Array.from(Y.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"completion",lastModified:P$(I.createdAt)})),Z=Array.from(G.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"init",lastModified:P$(I.createdAt)}));return{success:!0,data:{completions:X,initScripts:Z,totalFiles:X.length+Z.length}}}catch(J){return $.error(b.apiError("getShellIntegration"),J),{success:!1,error:"Failed to retrieve shell integration"}}}async function AG($,M){try{let J=await M.fileRegistry.getStats();return{success:!0,data:{toolsInstalled:(await M.toolInstallationRegistry.getAllToolInstallations()).length,updatesAvailable:0,filesTracked:J.totalFiles,totalOperations:J.totalOperations,oldestOperation:J.oldestOperation>0?P$(J.oldestOperation):null,newestOperation:J.newestOperation>0?P$(J.newestOperation):null}}}catch(J){return $.error(b.apiError("getStats"),J),{success:!1,error:"Failed to retrieve statistics"}}}async function EG($,M,J){let Q=$.getSubLogger({name:"checkToolUpdate",context:J});try{let G=(await R$($,M))[J];if(!G)return{success:!1,error:`Tool "${J}" not found in configuration`};let X=M.pluginRegistry.get(G.installationMethod);if(!X||!X.supportsUpdateCheck||!X.supportsUpdateCheck())return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!1,error:`Update checking is not supported for installation method "${G.installationMethod}"`}};let Z=await X.checkUpdate?.(J,G,{},Q);if(!Z)return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!1,error:"Update check returned no result"}};if(!Z.success)return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!0,error:Z.error}};return Q.info(b.checkUpdateCompleted(Z.hasUpdate,Z.currentVersion??"unknown",Z.latestVersion??"unknown")),{success:!0,data:{hasUpdate:Z.hasUpdate,currentVersion:Z.currentVersion??G.version??"unknown",latestVersion:Z.latestVersion??"unknown",supported:!0}}}catch(Y){let G=Y instanceof Error?Y.message:String(Y);return Q.error(b.checkUpdateFailed(G),Y),{success:!1,error:`Failed to check for updates: ${G}`}}}async function FG($,M){try{let J=M.projectConfig.paths.toolConfigsDir,Q=await R$($,M),Y=new Map;for(let Z of Object.values(Q))if(Z.configFilePath)Y.set(Z.configFilePath,Z.name);async function G(Z){let q=[],I=await M.fs.readdir(Z);for(let U of I){let K=`${Z}/${U}`;if((await M.fs.stat(K)).isDirectory()){let _=await G(K);if(_.length>0)q.push({name:U,path:K,type:"directory",children:_})}else if(U.endsWith(".tool.ts"))q.push({name:U,path:K,type:"file",toolName:Y.get(K)})}return q.toSorted((U,K)=>{if(U.type!==K.type)return U.type==="directory"?-1:1;return U.name.localeCompare(K.name)})}let X=await G(J);return{success:!0,data:{rootPath:J,entries:X}}}catch(J){return $.error(b.apiError("getToolConfigsTree"),J),{success:!1,error:"Failed to retrieve tool configs tree"}}}async function LG($,M,J){try{let Y=(await M.fileRegistry.getOperations({toolName:J})).toSorted((Z,q)=>q.createdAt-Z.createdAt),G=await M.toolInstallationRegistry.getToolInstallation(J),X=Y.map((Z)=>({id:Z.id,operationType:Z.operationType,fileType:Z.fileType,filePath:Z.filePath,timestamp:P$(Z.createdAt),relativeTime:U0(Z.createdAt)}));return{success:!0,data:{entries:X,totalCount:X.length,installedAt:G?.installedAt.toISOString()??null,dotfilesDir:M.projectConfig.paths.dotfilesDir}}}catch(Q){return $.error(b.apiError("getToolHistory"),Q),{success:!1,error:"Failed to retrieve tool history"}}}async function xG($,M,J,Q){let Y=$.getSubLogger({name:"installTool",context:J});try{let X=(await R$($,M))[J];if(!X)return{success:!1,error:`Tool "${J}" not found in configuration`};let Z=await M.installer.install(J,X,{force:Q.force??!1});if(!Z.success)return Y.error(b.installFailed(Z.error??"Unknown error")),{success:!0,data:{installed:!1,error:Z.error??"Installation failed"}};return Y.info(b.installSucceeded()),{success:!0,data:{installed:!0,version:Z.version,alreadyInstalled:Z.installationMethod==="already-installed"}}}catch(G){let X=G instanceof Error?G.message:String(G);return Y.error(b.installFailed(X),G),{success:!1,error:`Failed to install tool: ${X}`}}}function TG($){if(!$)return null;let M=$.repo;return typeof M==="string"?M:null}function g4($,M){if(M.platform===0)return!1;if(!rM($.platforms,M.platform))return!1;if($.architectures===void 0)return!0;if(M.arch===0)return!1;return tM($.architectures,M.arch)}function n4($,M){let J=TG($.installParams);if(J)return J;for(let Q of $.platformConfigs??[]){if(!g4(Q,M))continue;let Y=TG(Q.config?.installParams);if(Y)return Y}return null}async function kG($,M,J){try{let Y=(await R$($,M))[J];if(!Y)return{success:!1,error:"Tool not found"};let G=n4(Y,M.systemInfo);if(!G)return{success:!1,error:"Tool does not have a GitHub repository"};let X=Y.version?[Y.version,"main","master"]:["main","master"];for(let Z of X){let q=`https://raw.githubusercontent.com/${G}/${Z}/README.md`;try{let I=await M.downloader.download($,q);if(I)return{success:!0,data:{content:I.toString("utf-8")}}}catch(I){if(I instanceof S$)continue;throw I}}return{success:!1,error:"README not found"}}catch(Q){return $.error(b.apiError("getToolReadme"),Q),{success:!1,error:"Failed to retrieve README"}}}async function SG($,M,J){try{let Y=(await R$($,M))[J];if(!Y)return{success:!1,error:"Tool not found"};let G=Y.configFilePath;if(!G)return{success:!1,error:"Tool configuration file path not available"};return{success:!0,data:{content:await M.fs.readFile(G,"utf-8"),filePath:G}}}catch(Q){return $.error(b.apiError("getToolSource"),Q),{success:!1,error:"Failed to retrieve tool source"}}}async function wG($,M,J){let Q=$.getSubLogger({name:"updateTool",context:J});try{let G=(await R$($,M))[J];if(!G)return{success:!1,error:`Tool "${J}" not found in configuration`};if(G.version!=="latest")return{success:!0,data:{updated:!1,supported:!1,error:`Tool is pinned to version "${G.version}". Only tools with version "latest" can be updated.`}};let X=M.pluginRegistry.get(G.installationMethod);if(!X||!X.supportsUpdate())Q.warn(b.updateNotSupported(G.installationMethod));let q=(await M.toolInstallationRegistry.getToolInstallation(J))?.version??"unknown",I=await M.installer.install(J,G,{force:!0});if(!I.success)return Q.error(b.updateFailed(I.error??"Unknown error")),{success:!0,data:{updated:!1,supported:!0,error:I.error??"Update failed"}};let U="version"in I&&typeof I.version==="string"?I.version:"unknown";return Q.info(b.updateSucceeded(q,U)),{success:!0,data:{updated:!0,oldVersion:q,newVersion:U,supported:!0}}}catch(Y){let G=Y instanceof Error?Y.message:String(Y);return Q.error(b.updateFailed(G),Y),{success:!1,error:`Failed to update tool: ${G}`}}}async function i4($,M){return Promise.all($.map(async(J)=>{if(J.sizeBytes!==void 0)return J;try{let Q=await M.stat(J.filePath);if(Q.isFile())return{...J,sizeBytes:Q.size}}catch{}return J}))}function l4($){if(!$.binaries||$.binaries.length===0)return[];return $.binaries.map((M)=>typeof M==="string"?M:M.name)}async function a4($,M,J){let Q=await Promise.all(J.map(async(G)=>{let X=await $.toolInstallationRegistry.getToolUsage(M,G);return{binaryName:G,count:X?.usageCount??0,lastUsedAt:X?.lastUsedAt?X.lastUsedAt.toISOString():null}}));return{totalCount:Q.reduce((G,X)=>G+X.count,0),binaries:Q}}async function bG($,M){try{let J=await R$($,M),Q=await M.toolInstallationRegistry.getAllToolInstallations(),Y=new Map(Q.map((Z)=>[Z.toolName,Z]));return{success:!0,data:(await Promise.all(Object.values(J).map(async(Z)=>{let q=await M.fileRegistry.getFileStatesForTool(Z.name),I=await i4(q,M.fs),U=await v6(M,Z.name),K=l4(Z),H=await a4(M,Z.name,K);return RG(Z,Y,I,M.systemInfo,U,H)}))).toSorted((Z,q)=>Z.config.name.localeCompare(q.config.name))}}catch(J){return $.error(b.apiError("getTools"),J),{success:!1,error:"Failed to retrieve tools"}}}function NG($,M){let J=$.getSubLogger({name:"api"});return{getTools:()=>bG(J,M),getStats:()=>AG(J,M),getHealth:()=>VG(J,M),getConfig:()=>jG(J,M),getToolConfigsTree:()=>FG(J,M),getShellIntegration:()=>DG(J,M),getActivity:(Q)=>OG(J,M,Q),getToolHistory:(Q)=>LG(J,M,Q),getToolReadme:(Q)=>kG(J,M,Q),getToolSource:(Q)=>SG(J,M,Q),getRecentTools:(Q)=>BG(J,M,Q),installTool:(Q,Y)=>xG(J,M,Q,Y),checkToolUpdate:(Q)=>EG(J,M,Q),updateTool:(Q)=>wG(J,M,Q)}}var yG=vG("{\"index\":\"./dashboard.js\",\"files\":[{\"path\":\"./cli-w822cqdk.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"IUqVLF461B4\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"path\":\"./cli-fj2hdbnx.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"SXWin7hyR_o\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-0ebz5sqb.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"E4eqVcrkzYE\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard.js\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"eqXrNcjoIac\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/preact-iso@2.11.1/node_modules/preact-iso/src/prerender.js\",\"path\":\"./prerender-kpxyx916.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"D-BSy7GnzyQ\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/shiki@3.23.0/node_modules/shiki/dist/wasm.mjs\",\"path\":\"./wasm-n3cagcre.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"50fw3f0UtlU\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-3axqywva.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"gMrIjjRYnE4\",\"content-type\":\"text/css;charset=utf-8\"}}]}");var o4=import.meta.dir,gJ=!1,e4=gJ&&process.env.DOTFILES_IS_RELOAD==="1";function $3($){let M={};try{let J=r4.readdirSync($);for(let Q of J)if(Q.endsWith(".js")){let Y=t4.join($,Q);M[`/${Q}`]=()=>{return new Response(Bun.file(Y),{headers:{"Content-Type":"text/javascript"}})}}}catch{}return M}function P6($,M,J){let Q=$.getSubLogger({name:"DashboardServer"}),Y=NG(Q,M),G=null;return{async start(){if(process.env.DOTFILES_IS_RELOAD="1",!gJ)process.chdir(o4);let X=gJ?{}:$3(process.cwd());return G=Bun.serve({port:J.port,hostname:J.host,development:gJ,routes:{...X,"/api/tools":async()=>{let Z=await Y.getTools();return Response.json(Z)},"/api/stats":async()=>{let Z=await Y.getStats();return Response.json(Z)},"/api/health":async()=>{let Z=await Y.getHealth();return Response.json(Z)},"/api/config":async()=>{let Z=await Y.getConfig();return Response.json(Z)},"/api/tool-configs-tree":async()=>{let Z=await Y.getToolConfigsTree();return Response.json(Z)},"/api/shell":async()=>{let Z=await Y.getShellIntegration();return Response.json(Z)},"/api/activity":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await Y.getActivity(U);return Response.json(K)},"/api/tools/:name/history":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolHistory(q);return Response.json(I)},"/api/tools/:name/readme":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolReadme(q);return Response.json(I)},"/api/tools/:name/source":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolSource(q);return Response.json(I)},"/api/tools/:name/install":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Z.json().catch(()=>({})),U=await Y.installTool(q,I);return Response.json(U)},"/api/tools/:name/check-update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Y.checkToolUpdate(q);return Response.json(I)},"/api/tools/:name/update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Y.updateTool(q);return Response.json(I)},"/api/recent-tools":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await Y.getRecentTools(U);return Response.json(K)},"/api/*":Response.json({success:!1,error:"Not found"},{status:404}),"/server/*":(Z)=>{let q=new URL(Z.url),I=q.pathname.replace(/^\/server\//,"/");return Response.redirect(new URL(I,q.origin).href,302)},"/*":yG},fetch(Z){let q=new URL(Z.url);return Q.debug(b.requestReceived(Z.method,q.pathname)),new Response("Not Found",{status:404})}}),Q.info(b.serverStarted(this.getUrl())),e4},async stop(){if(Q.info(b.serverStopping()),G)G.stop(),G=null;Q.info(b.serverStopped())},getUrl(){return`http://${J.host}:${J.port}`}}}var{$:M3}=globalThis.Bun;var J3=async($,M)=>{let J=M===2?"open":M===4?"start":"xdg-open";await M3`${J} ${$}`.nothrow().quiet()};function PG($,M,J,Q={}){let Y=Q.openBrowser??J3,G=Q.createServer??P6,X=$.getSubLogger({name:"dashboard"});M.command("dashboard").description("Start the web-based visualization dashboard").option("--port <port>","Port to run the server on","3000").option("--host <host>","Host to bind the server to","localhost").option("--no-open","Do not open browser when server starts").action(async(Z)=>{let q=parseInt(Z.port??"3000",10),I=Z.host??"localhost",U=Z.open??!0,K=await J(),H={projectConfig:K.projectConfig,fs:K.fs,configService:K.configService,systemInfo:K.systemInfo,fileRegistry:K.fileRegistry,toolInstallationRegistry:K.toolInstallationRegistry,versionChecker:K.versionChecker,downloader:K.downloader,installer:K.installer,pluginRegistry:K.pluginRegistry},O=await G(X,H,{port:q,host:I}).start();if(U&&!O){let B=`http://${I}:${q}`;try{await Y(B,K.systemInfo.platform)}catch(j){X.warn(R.dashboardBrowserOpenFailed(),j)}}})}import aM from"path";var CG={name:"detect-conflicts",description:"Detect file conflicts before generating"};async function Q3($,M,J,Q,Y){try{let G=await Q.loadToolConfigs($,M.paths.toolConfigsDir,J,M,Y);return{toolConfigs:Object.values(G),exitCode:x.SUCCESS}}catch(G){return $.error(R.configLoadFailed("tool configurations"),G),{toolConfigs:[],exitCode:x.ERROR}}}async function Y3($,M,J,Q,Y){if(!J.binaries)return;for(let G of J.binaries){let X=typeof G==="string"?G:G.name,Z=aM.join(Q,X);if(await M.exists(Z))try{if(!(await M.readFile(Z)).includes("# Generated by Dotfiles Management Tool"))Y.push(`[${J.name}]: ${Z} (exists but is not a generator shim)`)}catch(q){$.warn(R.fsReadFailed(Z),q),Y.push(`[${J.name}]: ${Z} (exists but could not be read/verified)`)}}}async function G3($,M,J,Q,Y,G){if(!J.symlinks)return;for(let X of J.symlinks){let Z=aM.join(Q,X.target),q=aM.join(Y,X.source);try{let I=await M.lstat(Z);if(I)if(I.isSymbolicLink()){let U=await M.readlink(Z);if(aM.resolve(aM.dirname(Z),U)!==q)G.push(`[${J.name}]: ${Z} (points to '${U}', expected '${q}')`)}else G.push(`[${J.name}]: ${Z} (exists but is not a symlink)`)}catch(I){if(I.code!=="ENOENT")$.warn(R.fsReadFailed(Z),I)}}}function X3($,M){if(M.length>0){let Q=M.map((Y)=>` - ${Y}`).join(`
226
- `);return $.warn(R.toolConflictsDetected("Conflicts detected with files not owned by the generator:",Q)),x.ERROR}else return $.info(R.noConflictsDetected()),x.SUCCESS}async function Z3($,M,J){let{projectConfig:Q,fs:Y,configService:G,systemInfo:X}=J,Z=[],q=await Q3($,Q,Y,G,X);if(q.exitCode!==x.SUCCESS)return q.exitCode;let I=q.toolConfigs;if(I.length===0)return $.info(R.toolNoConfigurationsFound(Q.paths.toolConfigsDir)),x.SUCCESS;for(let U of I)await Y3($,Y,U,Q.paths.targetDir,Z),await G3($,Y,U,Q.paths.homeDir,Q.paths.dotfilesDir,Z);return X3($,Z)}function dG($,M,J){let Q=$.getSubLogger({name:"registerDetectConflictsCommand"});M.command("detect-conflicts").description("Detects conflicts between potential generated artifacts and existing system files.").action(async()=>{let Y=M.opts(),G;try{let X=await J();G=await Z3(Q,Y,X)}catch(X){Q.error(R.commandExecutionFailed("detect-conflicts",x.ERROR),X),G=x.ERROR}N(G)})}var G$="DOTFILES_ENV_DIR",TM="DOTFILES_ENV_NAME",P0="env",nJ="source",uG="source.ps1",HM="config.ts",C6="tools";function fG(){let $=p0();return c(`
222
+ `);Y.debug(K$.generateShim.generatedContent(G)),await this.fs.ensureDir(T6.dirname(R)),await $.writeFile(R,K);let O=493;try{if(((await $.stat(R)).mode&511)!==O)await $.chmod(R,O)}catch{await $.chmod(R,O)}return Y.debug(K$.generateShim.success(G,R,$.constructor.name)),R}async isGeneratedShim($,I){try{try{if((await $.lstat(I)).isSymbolicLink())return!0}catch{}return(await $.readFile(I,"utf8")).includes("# Generated by Dotfiles Management Tool")}catch{return!1}}}import k6 from"path";var g={generate:{processingTool:($)=>Z(`Processing symlinks for tool "${$}"`),missingToolConfig:($)=>Z(`Tool config for "${$}" is undefined. Skipping.`)},process:{symlinkDetails:($,I,M,G)=>Z(`Processing symlink: source="${$}" (abs: "${I}"), target="${M}" (abs: "${G}")`),sourceMissing:($,I)=>Z(`Tool "${$}" source file not found: ${I}`),targetExists:($)=>Z(`Target path "${$}" already exists.`),skipExistingTarget:($)=>Z(`Target "${$}" exists and overwrite is false. Skipping symlink creation.`)},filesystem:{backupFailed:($)=>Z(`Failed to write backup of ${$}`),deleteFailed:($)=>Z(`Failed to delete ${$}`),directoryCreateFailed:($)=>Z(`Failed to create directory ${$}`),symlinkFailed:($,I)=>Z(`Failed to create symlink ${$} \u2192 ${I}`),symlinkAlreadyExists:($,I)=>Z(`Symlink already exists and is valid: ${$} -> ${I}`),creatingSymlink:($,I)=>Z(`Creating symlink: ${$} -> ${I}`),symlinkCreated:($,I)=>Z(`Successfully created symlink: ${$} -> ${I}`),removingBrokenSymlink:($)=>Z(`Removing broken symlink: ${$}`)},copy:{processingTool:($)=>Z(`Processing copies for tool "${$}"`),missingToolConfig:($)=>Z(`Tool config for "${$}" is undefined. Skipping.`),copyDetails:($,I,M,G)=>Z(`Processing copy: source="${$}" (abs: "${I}"), target="${M}" (abs: "${G}")`),sourceMissing:($,I)=>Z(`Tool "${$}" source file not found: ${I}`),targetExists:($)=>Z(`Target path "${$}" already exists.`),skipExistingTarget:($)=>Z(`Target "${$}" exists and overwrite is false. Skipping copy.`),copyFailed:($,I)=>Z(`Failed to copy ${$} \u2192 ${I}`)}};class w6{fs;projectConfig;systemInfo;logger;constructor($,I,M,G){this.fs=I,this.projectConfig=M,this.systemInfo=G,this.logger=$.getSubLogger({name:"CopyGenerator"})}async generate($,I={}){let M=this.logger.getSubLogger({name:"generate"}),G=[];for(let J in $){let Q=$[J];if(!Q)continue;let Y=I$(Q,this.systemInfo);if(!this.shouldProcessTool(Y,J,M))continue;let X=M.getSubLogger({context:J}),R=this.fs instanceof f?this.fs.withToolName(J):this.fs;X.debug(g.copy.processingTool(J));for(let W of Y.copies){let q=await this.processCopy(Y,W,R,I,X);G.push(q)}}return G}shouldProcessTool($,I,M){let G=M.getSubLogger({name:"shouldProcessTool"});if(!$)return G.debug(g.copy.missingToolConfig(I)),!1;if(!$.copies||$.copies.length===0)return!1;return!0}async processCopy($,I,M,G,J){let Q=J.getSubLogger({name:"processCopy"}),{overwrite:Y=!1,backup:X=!1}=G,R=w$($.configFilePath,I.source,this.projectConfig,this.systemInfo),W=w$($.configFilePath,I.target,this.projectConfig,this.systemInfo);if(Q.debug(g.copy.copyDetails(I.source,R,I.target,W)),!await M.exists(R))return Q.error(g.copy.sourceMissing($.name,R)),{success:!1,sourcePath:R,targetPath:W,status:"failed",error:g.copy.sourceMissing($.name,R)};if(await M.exists(W)){if(Q.debug(g.copy.targetExists(W)),!Y)return Q.debug(g.copy.skipExistingTarget(W)),{success:!0,sourcePath:R,targetPath:W,status:"skipped_exists"};let U=await this.handleOverwrite(W,M,X,Q);if(U.failed)return{success:!1,sourcePath:R,targetPath:W,status:"failed",error:U.error};return this.performCopy(R,W,M,U.status,Q)}return this.performCopy(R,W,M,"created",Q)}async handleOverwrite($,I,M,G){if(M){let J=`${$}.bak`;try{if(await I.exists(J))await I.rm(J,{recursive:!0,force:!0});return await I.rename($,J),{failed:!1,status:"backed_up"}}catch{let Q=g.filesystem.backupFailed($);return G.error(Q),{failed:!0,error:Q}}}try{if((await I.stat($)).isDirectory())await I.rm($,{recursive:!0,force:!0});else await I.rm($,{force:!0});return{failed:!1,status:"updated_target"}}catch{let J=g.filesystem.deleteFailed($);return G.error(J),{failed:!0,error:J}}}async performCopy($,I,M,G,J){let Q=J.getSubLogger({name:"performCopy"}),Y=k6.dirname(I);try{await M.ensureDir(Y)}catch{let X=g.filesystem.directoryCreateFailed(Y);return Q.error(X),{success:!1,sourcePath:$,targetPath:I,status:"failed",error:X}}try{if((await M.stat($)).isDirectory())await this.copyDirectory($,I,M);else await M.copyFile($,I);return{success:!0,sourcePath:$,targetPath:I,status:G}}catch{let X=g.copy.copyFailed($,I);return Q.error(X),{success:!1,sourcePath:$,targetPath:I,status:"failed",error:X}}}async copyDirectory($,I,M){await M.ensureDir(I);let G=await M.readdir($);for(let J of G){let Q=k6.join($,J),Y=k6.join(I,J);if((await M.stat(Q)).isDirectory())await this.copyDirectory(Q,Y,M);else await M.copyFile(Q,Y)}}}import t$ from"path";class b6{fs;projectConfig;systemInfo;logger;constructor($,I,M,G){this.fs=I,this.projectConfig=M,this.systemInfo=G,this.logger=$.getSubLogger({name:"SymlinkGenerator"})}async createBinarySymlink($,I,M){let G=$.getSubLogger({name:"createBinarySymlink"});try{if((await this.fs.lstat(M)).isSymbolicLink()){let W=await this.fs.readlink(M),q=t$.resolve(t$.dirname(M),W),U=t$.resolve(I);if(q===U){if(await this.fs.exists(q)){G.debug(g.filesystem.symlinkAlreadyExists(M,q));return}}await this.fs.rm(M,{force:!0})}else await this.fs.rm(M,{force:!0})}catch{}if(!await this.fs.exists(I))throw Error(`Cannot create symlink: binary does not exist at ${I}`);G.debug(g.filesystem.creatingSymlink(M,I)),await this.fs.symlink(I,M);let Q=await this.fs.readlink(M),Y=t$.resolve(t$.dirname(M),Q),X=t$.resolve(I);if(Y!==X)throw Error(`Symlink verification failed: ${M} points to ${Y}, expected ${X}`);G.debug(g.filesystem.symlinkCreated(M,I))}async generate($,I={}){let M=this.logger.getSubLogger({name:"generate"}),G=[];for(let J in $){let Q=$[J];if(!Q)continue;let Y=I$(Q,this.systemInfo);if(!this.shouldProcessTool(Y,J,M))continue;let X=M.getSubLogger({context:J}),R=this.fs instanceof f?this.fs.withToolName(J):this.fs;X.debug(g.generate.processingTool(J));for(let W of Y.symlinks){let q=await this.processSymlink(Y,W,R,I,X);G.push(q)}}return G}shouldProcessTool($,I,M){let G=M.getSubLogger({name:"shouldProcessTool"});if(!$)return G.debug(g.generate.missingToolConfig(I)),!1;if(!$.symlinks||$.symlinks.length===0)return!1;return!0}async processSymlink($,I,M,G,J){let Q=J.getSubLogger({name:"processSymlink"}),{overwrite:Y=!1,backup:X=!1}=G,R=w$($.configFilePath,I.source,this.projectConfig,this.systemInfo),W=w$($.configFilePath,I.target,this.projectConfig,this.systemInfo);if(Q.debug(g.process.symlinkDetails(I.source,R,I.target,W),I.source,R,I.target,W),!await M.exists(R))return Q.error(g.process.sourceMissing($.name,R)),{success:!1,sourcePath:R,targetPath:W,status:"failed",error:g.process.sourceMissing($.name,R)};let q=await this.handleExistingTarget(R,W,M,{overwrite:Y,backup:X},Q);if(q.shouldSkip){if(q.status==="failed")return{success:!1,sourcePath:R,targetPath:W,status:"failed",error:q.error??"Unknown error"};if(q.status==="skipped_correct"&&M instanceof f)await M.recordExistingSymlink(R,W);return{success:!0,sourcePath:R,targetPath:W,status:q.status}}return await this.createSymlink(R,W,M,q.status,Q)}async handleExistingTarget($,I,M,G,J){let Q=J.getSubLogger({name:"handleExistingTarget"});if(!await M.exists(I)){let R=await this.removeBrokenSymlink(I,M,Q);if(R.failed)return{shouldSkip:!0,status:"failed",error:R.error};return{shouldSkip:!1,status:"created"}}if(Q.debug(g.process.targetExists(I)),(await this.checkCorrectSymlink($,I,M)).isCorrect)return{shouldSkip:!0,status:"skipped_correct"};if(!G.overwrite)return Q.debug(g.process.skipExistingTarget(I)),{shouldSkip:!0,status:"skipped_exists"};return await this.handleOverwrite(I,M,G.backup,Q)}async checkCorrectSymlink($,I,M){try{if((await M.lstat(I)).isSymbolicLink()){let J=await M.readlink(I),Q=t$.resolve(t$.dirname(I),J),Y=t$.resolve($);return{isCorrect:Q===Y}}}catch{}return{isCorrect:!1}}async handleOverwrite($,I,M,G){let J=G.getSubLogger({name:"handleOverwrite"}),Q="updated_target";if(M){let Y=await this.createBackup($,I,J);if(Y.failed)return{shouldSkip:!0,status:"failed",error:Y.error};Q="backed_up"}else{let Y=await this.deleteTarget($,I,J);if(Y.failed)return{shouldSkip:!0,status:"failed",error:Y.error}}return{shouldSkip:!1,status:Q}}async createBackup($,I,M){let G=M.getSubLogger({name:"createBackup"}),J=`${$}.bak`;try{if(await I.exists(J))await I.rm(J,{recursive:!0,force:!0});return await I.rename($,J),{failed:!1}}catch{let Q=g.filesystem.backupFailed($);return G.error(Q),{failed:!0,error:Q}}}async deleteTarget($,I,M){let G=M.getSubLogger({name:"deleteTarget"});try{if((await I.stat($)).isDirectory())await I.rm($,{recursive:!0,force:!0});else await I.rm($,{force:!0});return{failed:!1}}catch{let J=g.filesystem.deleteFailed($);return G.error(J),{failed:!0,error:J}}}async removeBrokenSymlink($,I,M){let G=M.getSubLogger({name:"removeBrokenSymlink"});try{if((await I.lstat($)).isSymbolicLink())G.debug(g.filesystem.removingBrokenSymlink($)),await I.rm($,{force:!0});return{failed:!1}}catch{return{failed:!1}}}async createSymlink($,I,M,G,J){let Q=J.getSubLogger({name:"createSymlink"}),Y=t$.dirname(I);try{await M.ensureDir(Y)}catch{let X=g.filesystem.directoryCreateFailed(Y);return Q.error(X),{success:!1,sourcePath:$,targetPath:I,status:"failed",error:X}}try{return await M.symlink($,I),{success:!0,sourcePath:$,targetPath:I,status:G}}catch{let X=g.filesystem.symlinkFailed($,I);return Q.error(X),{success:!1,sourcePath:$,targetPath:I,status:"failed",error:X}}}}import{eq as EX,gt as TX,valid as J1}from"semver";var d$={initializing:()=>Z("Initializing VersionChecker with githubClient"),fetchingLatestRelease:($,I)=>Z(`Fetching latest version for ${$}/${I}`),latestReleaseFound:($)=>Z(`Latest release found ${$}`),latestReleaseError:($,I)=>Z(`Failed to fetch latest release for ${$}/${I}`),noLatestRelease:($,I)=>Z(`No latest release found for ${$}/${I}`),comparingVersions:($,I)=>Z(`Comparing versions configured ${$} vs latest ${I}`),invalidConfiguredVersion:($)=>Z(`Configured version invalid ${$}`),invalidLatestVersion:($)=>Z(`Latest version invalid ${$}`),versionComparisonResult:($)=>Z(`Version comparison result ${$}`)};class N6{githubClient;logger;constructor($,I){this.logger=$.getSubLogger({name:"VersionChecker"}),this.logger.debug(d$.initializing()),this.githubClient=I}async getLatestToolVersion($,I){let M=this.logger.getSubLogger({name:"getLatestToolVersion"});M.debug(d$.fetchingLatestRelease($,I));try{let G=await this.githubClient.getLatestRelease($,I);if(G?.tag_name){let J=G.tag_name.replace(/^v/,"");return M.debug(d$.latestReleaseFound(J)),J}return M.debug(d$.noLatestRelease($,I)),null}catch(G){return M.debug(d$.latestReleaseError($,I),G),null}}async checkVersionStatus($,I){let M=this.logger.getSubLogger({name:"checkVersionStatus"});M.debug(d$.comparingVersions($,I));let G=$.replace(/^v/,""),J=I.replace(/^v/,"");if(!J1(G))return M.debug(d$.invalidConfiguredVersion(G)),"INVALID_CURRENT_VERSION";if(!J1(J))return M.debug(d$.invalidLatestVersion(J)),"INVALID_LATEST_VERSION";if(TX(J,G))return M.debug(d$.versionComparisonResult("NEWER_AVAILABLE")),"NEWER_AVAILABLE";if(EX(J,G))return M.debug(d$.versionComparisonResult("UP_TO_DATE")),"UP_TO_DATE";return M.debug(d$.versionComparisonResult("AHEAD_OF_LATEST")),"AHEAD_OF_LATEST"}}import _3 from"net";import OM from"path";import{realpath as SX}from"fs/promises";import kX from"path";var Q1={name:"bin",description:"Print the real path to a binary",hasPositionalArg:!0,positionalArgDescription:"binary name",positionalArgType:"tool"};async function wX($,I,M,G,J,Q,Y){let X=await Q.loadSingleToolConfig($,I,M,G,J,Y);if(X){let U=(I$(X,Y).binaries??[])[0],H=U?typeof U==="string"?U:U.name:I;return{toolName:I,binaryName:H}}let R=await Q.loadToolConfigByBinary($,I,M,G,J,Y);if(R&&!("error"in R))return{toolName:R.name,binaryName:I};return}async function bX($,I,M){let{projectConfig:G,fs:J,configService:Q,systemInfo:Y}=M,X=$.getSubLogger({minLevel:7}),R=await wX(X,I,G.paths.toolConfigsDir,J,G,Q,Y);if(!R)return E.ERROR;let{toolName:W,binaryName:q}=R,U=kX.join(G.paths.binariesDir,W,"current",q);try{let H=await SX(U);return process.stdout.write(H),E.SUCCESS}catch{return E.ERROR}}function Y1($,I,M){let G=$.getSubLogger({name:"registerBinCommand"});I.command("bin <name>").description("Print the absolute real path to a binary (resolving symlinks). Accepts tool name or binary name (from .bin()).").action(async(J)=>{let Q=await M(),Y=await bX(G,J,Q);y(Y)})}import X1 from"path";var _={proxyUnavailable:($)=>Z(`HTTP proxy not available on port ${$}. Start with 'bun proxy' or unset DEV_PROXY env var.`),proxyEnabled:($)=>Z(`Routing requests through HTTP proxy on port ${$}`),proxyCheckingAvailability:($)=>Z(`Checking proxy availability on port ${$}`),commandActionStarted:($,I)=>Z(`${$} command action logic started${I?`. Tool: ${I}`:""}`),commandConfigErrorDetails:()=>Z("Configuration loading error details: %O"),dryRunEnabled:()=>Z("Dry run enabled. Initializing MemFileSystem"),componentInitialized:($)=>Z(`${$} initialized`),toolConfigsLoading:($)=>Z(`tool config loading: ${$}`),toolConfigsLoaded:($,I)=>Z(`Configuration loaded from ${$} (${I} tools configured)`),toolConfigsForDryRun:()=>Z("tool configs for dry run"),commandCompleted:($)=>Z(`DONE${$?" (dry run)":""}`),commandExecutionFailed:($,I)=>Z(`Command failed [${$}] exit ${I}`),commandVersionComparison:($,I,M)=>Z(`Tool: ${$}, Configured: ${I}, Latest: ${M}`),commandUnsupportedOperation:($,I)=>Z(`${$} not yet supported (${I})`),toolNotFound:($,I)=>Z(`Tool "${$}" not found in ${I}`),toolInstalled:($,I,M)=>Z(`Tool "${$}" \`${I}\` installed successfully using ${M}`),toolAlreadyInstalled:($,I)=>Z(`Tool "${$}" \`${I}\` is already installed and healthy`),toolArtifactsRepaired:($)=>Z(`Tool "${$}" is installed. Repaired generated artifacts`),toolInstallSkippedConfigurationOnly:($)=>Z(`Tool "${$}" has no installation steps`),shimDeleted:($,I)=>Z(`Deleted temporary shim ${$} at ${I}`),toolNoConfigurationsFound:($)=>Z(`No tool configurations found in ${$}`),toolCheckingUpdates:($)=>Z(`updates for ${$}`),toolUpdateAvailable:($,I,M)=>Z(`Update available for ${$}: ${I} -> ${M}`),toolUpToDate:($,I,M)=>Z(`${$} (${I}) is up to date. Latest: ${M}`),toolAheadOfLatest:($,I,M)=>Z(`${$} (${I}) is ahead of the latest known version (${M})`),toolConfiguredToLatest:($,I)=>Z(`Tool "${$}" is configured to 'latest'. The latest available version is ${I}`),toolVersionComparisonFailed:($,I,M)=>Z(`Could not determine update status for ${$} (${I}) against latest ${M}`),toolShimUpToDate:($,I)=>Z(`${$} is already up to date (${I})`),toolShimOnLatest:($,I)=>Z(`${$} is already on latest version (${I})`),toolShimUpdateStarting:($,I,M)=>Z(`Updating ${$} from ${I} to ${M}...`),toolProcessingUpdate:($,I,M)=>Z(`${$} update from ${I} to ${M}`),toolShimUpdateSuccess:($,I)=>Z(`${$} successfully updated to ${I}`),toolUpdated:($,I,M)=>Z(`Tool "${$}" updated from \`${I}\` to \`${M}\``),toolUpdateFailed:($,I)=>Z(`Update failed for tool "${$}": ${I}`),toolVersionPinned:($,I)=>Z(`Tool "${$}" is pinned to version \`${I}\`. Set version to "latest" in the tool config to enable updates`),toolUpdateNotSupported:($,I)=>Z(`Tool "${$}" uses ${I} which does not support updates. Performing regular install instead`),commandCheckingUpdatesFor:($)=>Z(`Checking "${$}" for updates`),commandCheckingUpdatesForAll:()=>Z("Checking all tools for updates"),fsReadFailed:($)=>Z(`Failed to read ${$}`),fsAccessDenied:($,I)=>Z(`Access denied ${$}: ${I}`),fsItemNotFound:($,I)=>Z(`${$} not found: ${I}`),fsWrite:($,I)=>Z(`[${$}] write ${I}`),toolConflictsDetected:($,I)=>Z(`${$}
223
+ ${I}`),noConflictsDetected:()=>Z("No conflicts detected"),cleanupAllTrackedFiles:()=>Z("Registry-based cleanup: Removing all tracked files"),cleanupRegistryDatabase:()=>Z("registry database cleanup"),cleanupRegistryDryRun:()=>Z("Would clean up registry database (dry run)"),cleanupToolFiles:($)=>Z(`Registry-based cleanup: files for tool '${$}'`),cleanupRegistryTool:($,I)=>Z(I?`Would remove registry entries for tool: ${$} (dry run)`:`Removed registry entries for tool: ${$}`),cleanupTypeFiles:($)=>Z(`Registry-based cleanup: files of type '${$}'`),cleanupFoundFiles:($,I,M)=>Z(`Found ${$} files for tool '${I}'${M?` of type '${M}'`:""}`),cleanupFileRemoved:($)=>Z(`[cleanup] rm ${$}`),fileCleanupDryRun:($)=>Z(`Would delete: ${$}`),cleanupFileNotFound:($)=>Z(`file not found ${$}`),cleanupDeleteFailed:($)=>Z(`Failed to delete ${$}`),cleanupProcessStarted:($)=>Z(`starting cleanup process, dryRun=${$}: %O`),configParameterOverridden:($,I)=>Z(`${$.charAt(0).toUpperCase()+$.slice(1)} overridden to: ${I}`),cleanupProcessFinished:($)=>Z(`cleanup process finished, dryRun=${$}`),logCheckingFileStates:()=>Z("Checking file states for all tools"),logFileStatesForTool:($)=>Z(`${$} files`),logFileStatus:($,I,M,G,J)=>Z(`${$} ${I} [${M}] - ${G}${J}`),logTargetStatus:($,I)=>Z(`${$} ${I}`),logNoOperationsFound:()=>Z("No file operations found matching criteria"),logOperationHistory:($,I,M)=>Z(`${$} ${I}${M?` ${M}`:""}`),cachingDisabled:()=>Z("Caching disabled"),registryInitialized:($)=>Z(`File tracking initialized: ${$}`),cliStarted:()=>Z("CLI starting with arguments"),serviceGithubResourceNotFound:($,I)=>Z(`GitHub ${$} not found: ${I}`),serviceGithubApiFailed:($,I)=>Z(`GitHub API failed [${$}] ${I}`),configLoadFailed:($)=>Z(`Failed to load configuration from ${$}`),configPathResolved:($)=>Z(`Using configuration: ${$}`),configNotFound:()=>Z("No configuration file found. Create dotfiles.config.ts or specify --config <path>"),configParameterIgnored:($,I)=>Z(`Configuration field "${$}" ignored: ${I}`),configParameterInvalid:($,I,M)=>Z(`Invalid ${$}: "${I}" (expected ${M})`),updatesCommandCompleted:()=>Z("Check-updates command completed"),toolTypesGenerated:($)=>Z(`Generated tool types: ${$}`),toolNotInstalled:($)=>Z(`Tool "${$}" is not installed`),installPathNotFound:($)=>Z(`Installation path not found: ${$}`),filesCommandShowingTree:($)=>Z($),filesCommandEmptyDirectory:()=>Z("(empty directory)"),filesCommandTree:($)=>Z($),skillAlreadyExists:($)=>Z(`Destination already exists, removing: ${$}`),skillDryRun:($,I)=>Z(`Would copy skill: ${I} -> ${$}`),skillCopied:($,I)=>Z(`Copied skill: ${I} -> ${$}`),skillCopyFailed:($)=>Z(`Failed to copy skill to: ${$}`),cliCompletionGenerated:($)=>Z(`CLI completion generated: ${$}`),dashboardStopping:()=>Z("Stopping dashboard server"),dashboardBrowserOpenFailed:()=>Z("Failed to open browser"),toolLookupByBinaryStarted:($)=>Z(`Tool not found by name '${$}', searching by binary name`),toolFoundByBinary:($,I)=>Z(`Binary '${$}' is provided by tool '${I}'`),toolNotFoundByBinary:($,I)=>Z(`No tool or binary named "${$}" found in ${I}`),envCreated:($)=>Z(`Environment created at ${$}`),envDeleted:($)=>Z(`Environment deleted at ${$}`),envNotFound:($)=>Z(`Environment not found at ${$}`),envOperationFailed:($,I)=>Z(`Environment ${$} failed: ${I}`),envDeletionCancelled:()=>Z("Deletion cancelled"),envActivationHint:($)=>Z(`To activate: source ${$}/source`),envConfigPath:($)=>Z(`Config file: ${$}`),envConfigFromEnvVar:($)=>Z(`Using config from DOTFILES_ENV_DIR: ${$}`)};var Z1={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function NX($,I,M,G,J,Q){let Y={};if(M){$.debug(_.commandCheckingUpdatesFor(M));try{let X=await I.loadSingleToolConfig($,M,G.paths.toolConfigsDir,J,G,Q);if(X)Y[M]=X;else return $.error(_.toolNotFound(M,G.paths.toolConfigsDir)),null}catch(X){return $.error(_.configLoadFailed(`tool "${M}"`),X),null}}else try{if($.debug(_.commandCheckingUpdatesForAll()),Y=await I.loadToolConfigs($,G.paths.toolConfigsDir,J,G,Q),Object.keys(Y).length===0)return $.error(_.toolNoConfigurationsFound(G.paths.toolConfigsDir)),null}catch(X){return $.error(_.configLoadFailed("tool configurations"),X),null}return Y}function yX($,I,M,G,J){let Q=new Date().toISOString().replace(/:/g,"-").split(".")[0],Y=$.configFilePath?X1.dirname($.configFilePath):I.paths.toolConfigsDir,X=X1.join(I.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:Y,currentDir:X,stagingDir:"",timestamp:Q||"",systemInfo:M,toolConfig:$,projectConfig:I,$:GI(Z$(),process.env),fileSystem:G,replaceInFile:(W,q,U,H)=>nM(G,W,q,U,H),resolve:()=>{throw Error("resolve not supported in version check context")},log:qG(J,$.name)}}async function vX($,I,M,G,J,Q){if(G==="latest"){$.info(_.toolConfiguredToLatest(M.name,J));return}if(Q){$.info(_.toolUpdateAvailable(M.name,G,J));return}let Y=await I.checkVersionStatus(G,J);if(Y==="UP_TO_DATE")$.info(_.toolUpToDate(M.name,G,J));else if(Y==="AHEAD_OF_LATEST")$.info(_.toolAheadOfLatest(M.name,G,J));else $.warn(_.toolVersionComparisonFailed(M.name,G,J))}async function PX($,I,M){let{projectConfig:G,versionChecker:J,pluginRegistry:Q,systemInfo:Y,fs:X}=M,R=yX(I,G,Y,X,$),W=Q.get(I.installationMethod);if(!W){$.warn(_.commandUnsupportedOperation("check-updates",`installation method: "${I.installationMethod}" for tool "${I.name}"`));return}if(!W.supportsUpdateCheck||!W.supportsUpdateCheck()){$.info(_.commandUnsupportedOperation("check-updates",`installation method: "${I.installationMethod}" for tool "${I.name}"`));return}let q=await W.checkUpdate?.(I.name,I,R,$);if(!q){$.warn(_.commandUnsupportedOperation("check-updates",I.name));return}if(!q.success){$.error(_.serviceGithubApiFailed("check update",0),Error(q.error));return}let U=q.currentVersion||I.version||"unknown",H=q.latestVersion||"unknown";await vX($,J,I,U,H,q.hasUpdate)}async function CX($,I,M){$.trace(_.commandActionStarted("check-updates",I||"all"));let G=await NX($,M.configService,I,M.projectConfig,M.fs,M.systemInfo);if(!G)return;for(let J of Object.values(G))await PX($,J,M)}function R1($,I,M){let G=$.getSubLogger({name:"registerCheckUpdatesCommand"});I.command("check-updates [toolName]").description("Checks for available updates for configured tools. If [toolName] is provided, checks only that tool.").action(async(J)=>{try{let Q=await M();await CX(G,J,Q)}catch(Q){G.error(_.commandExecutionFailed("check-updates",E.ERROR),Q),y(E.ERROR)}})}var W1={name:"cleanup",description:"Clean up generated files and registry entries",options:[{flag:"--tool",description:"Cleanup files for specific tool",hasArg:!0,argPlaceholder:"<name>"},{flag:"--type",description:"Cleanup files of specific type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--all",description:"Cleanup all tracked files"}]};async function dX($,I,M,G,J){$.info(_.cleanupAllTrackedFiles());let Q=await M.getRegisteredTools();for(let Y of Q)await q1($,I,M,Y,G,void 0,J);if(!J){for(let Y of Q)await M.removeToolOperations(Y);$.info(_.cleanupRegistryDatabase())}else $.info(_.cleanupRegistryDryRun())}async function uX($,I,M,G,J,Q,Y){if($.info(_.cleanupToolFiles(G)),await q1($,I,M,G,J,Q,Y),!Y)await M.removeToolOperations(G),$.info(_.cleanupRegistryTool(G,!1));else $.info(_.cleanupRegistryTool(G,!0))}async function fX($,I,M,G,J,Q){$.info(_.cleanupTypeFiles(G));let Y=await M.getOperations({fileType:G});for(let X of Y){let R=await M.getFileState(X.filePath);if(R&&R.lastOperation!=="rm")await U1($,I,X.filePath,J,Q)}}async function pX($,I,M){let{fs:G,fileRegistry:J}=I,{dryRun:Q,tool:Y,type:X,all:R}=M,W=I.projectConfig.paths.homeDir;if(R)await dX($,G,J,W,Q);else if(Y)await uX($,G,J,Y,W,X,Q);else if(X)await fX($,G,J,X,W,Q);else $.warn(_.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function q1($,I,M,G,J,Q,Y){let X=await M.getFileStatesForTool(G),R=X;if(Q)R=X.filter((W)=>W.fileType===Q);$.trace(_.cleanupFoundFiles(R.length,G,Q));for(let W of R)if(W.lastOperation!=="rm"){let q=W.fileType==="symlink"&&W.targetPath?W.targetPath:W.filePath;await U1($,I,q,J,Y||!1)}}async function U1($,I,M,G,J){try{if(await I.exists(M))if(!J)await I.rm(M,{force:!0}),$.info(_.cleanupFileRemoved(r(G,M)));else $.info(_.fileCleanupDryRun(M));else $.debug(_.cleanupFileNotFound(M))}catch(Q){$.error(_.cleanupDeleteFailed(M),Q)}}async function cX($,I,M){let{dryRun:G,tool:J,type:Q,all:Y}=I;try{$.trace(_.cleanupProcessStarted(G),I);let X={...I,all:Y||!J&&!Q};await pX($,M,X),$.trace(_.cleanupProcessFinished(G))}catch(X){$.error(_.commandExecutionFailed("cleanup",1),X),y(1)}}function H1($,I,M){let G=$.getSubLogger({name:"registerCleanupCommand"});I.command("cleanup").description("Remove all generated artifacts, including shims, shell configurations, and the .generated directory.").option("--tool <name>","Remove files for specific tool only (registry-based)").option("--type <type>","Remove files of specific type only (registry-based)").option("--all","Remove all tracked files (registry-based)").action(async(J)=>{let Q={...J,...I.opts()},Y=await M();await cX(G,Q,Y)})}import{Command as hX}from"commander";var K1={name:"dotfiles",description:"Dotfiles management CLI",options:[{flag:"--config",description:"Path to configuration file",hasArg:!0,argPlaceholder:"<path>"},{flag:"--dry-run",description:"Simulate operations without changes"},{flag:"--log",description:"Set log level",hasArg:!0,argPlaceholder:"<level>"},{flag:"--verbose",description:"Enable detailed debug messages"},{flag:"--quiet",description:"Suppress informational output"},{flag:"--platform",description:"Override detected platform",hasArg:!0,argPlaceholder:"<platform>"},{flag:"--arch",description:"Override detected architecture",hasArg:!0,argPlaceholder:"<arch>"}]};function _1(){return new hX().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.10").option("--config <path>","Path to a configuration file","").option("--dry-run","Simulate all operations without making changes to the file system",!1).option("--trace","Show file paths and line numbers in log output",!1).option("--log <level>",`Set log level (${RG.join(", ")})`,"default").option("--verbose","Enable detailed debug messages (alias for --log=verbose)",!1).option("--quiet","Suppress all informational and debug output. Errors are still displayed (alias for --log=quiet)",!1).option("--platform <platform>",`Override the detected platform (${lM.join(", ")})`).option("--arch <arch>",`Override the detected architecture (${aM.join(", ")})`)}import M8 from"fs";import G8 from"path";var b={serverStarted:($)=>Z(`Dashboard available at ${$}`),serverStopping:()=>Z("Stopping dashboard server"),serverStopped:()=>Z("Dashboard server stopped"),requestReceived:($,I)=>Z(`${$} ${I}`),apiError:($)=>Z(`API error in ${$}`),installFailed:($)=>Z(`Installation failed: ${$}`),installSucceeded:()=>Z("Installation succeeded"),checkUpdateCompleted:($,I,M)=>Z(`Update check complete: hasUpdate=${$} current=${I} latest=${M}`),checkUpdateFailed:($)=>Z(`Update check failed: ${$}`),updateNotSupported:($)=>Z(`Update not supported for method ${$}`),updateFailed:($)=>Z(`Update failed: ${$}`),updateSucceeded:($,I)=>Z(`Updated from ${$} to ${I}`)};function mX($){let I=[];if($&1)I.push("Linux");if($&2)I.push("macOS");if($&4)I.push("Windows");return I}function gX($){let I=[];if($&1)I.push("x86_64");if($&2)I.push("arm64");return I}function O1($){let I={};if(typeof $.repo==="string")I.repo=$.repo;if(typeof $.assetPattern==="string")I.assetPattern=$.assetPattern;if(typeof $.ghCli==="boolean")I.ghCli=$.ghCli;if(typeof $.crate==="string")I.crate=$.crate;if(typeof $.crateName==="string")I.crate=$.crateName;if(typeof $.formula==="string")I.formula=$.formula;if(typeof $.url==="string")I.url=$.url;return I}function nX($){let I={};if($.installParams)Object.assign(I,O1($.installParams));let M;if($.platformConfigs&&$.platformConfigs.length>0)M=$.platformConfigs.map((G)=>{let J={platforms:mX(G.platforms)};if(G.architectures!==void 0)J.architectures=gX(G.architectures);let Q=G.config;if(Q.installationMethod)J.installationMethod=Q.installationMethod;if(Q.installParams)J.installParams=O1(Q.installParams);if(Q.binaries)J.binaries=Q.binaries;if(Q.symlinks)J.symlinks=Q.symlinks;return J});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:I,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:M}}function iX($,I){let M=I.get($);if(!M)return{status:"not-installed",installedVersion:null,installedAt:null,installPath:null,binaryPaths:[],hasUpdate:!1};return{status:"installed",installedVersion:M.version,installedAt:M.installedAt.toISOString(),installPath:M.installPath,binaryPaths:M.binaryPaths||[],hasUpdate:!1}}function j1($,I,M,G,J,Q){return{config:nX($),runtime:iX($.name,I),files:M,binaryDiskSize:J,usage:Q}}function u$($){return new Date($).toISOString()}function KM($){let M=Date.now()-$,G=Math.floor(M/1000);if(G<60)return"just now";let J=Math.floor(G/60);if(J<60)return`${J} minute${J===1?"":"s"} ago`;let Q=Math.floor(J/60);if(Q<24)return`${Q} hour${Q===1?"":"s"} ago`;let Y=Math.floor(Q/24);if(Y<30)return`${Y} day${Y===1?"":"s"} ago`;let X=Math.floor(Y/30);return`${X} month${X===1?"":"s"} ago`}async function V1($,I,M=20){try{let J=(await I.fileRegistry.getOperations()).toSorted((X,R)=>R.createdAt-X.createdAt),Q=J.length;return{success:!0,data:{activities:J.slice(0,M).map((X)=>({id:X.id,toolName:X.toolName,action:X.operationType,description:`${X.operationType} ${X.fileType}: ${X.filePath}`,timestamp:u$(X.createdAt),relativeTime:KM(X.createdAt)})),totalCount:Q}}}catch(G){return $.error(b.apiError("getActivity"),G),{success:!1,error:"Failed to retrieve activity feed"}}}async function z1($,I){try{let M=I.projectConfig.paths;return{success:!0,data:{dotfilesDir:M.dotfilesDir,generatedDir:M.generatedDir,binariesDir:M.binariesDir,targetDir:M.targetDir,toolConfigsDir:M.toolConfigsDir}}}catch(M){return $.error(b.apiError("getConfig"),M),{success:!1,error:"Failed to retrieve configuration"}}}import uM from"path";async function lX($){let{fs:I,projectConfig:M}=$,G=M.paths.binariesDir,J=[];if(!await I.exists(G))return[];let Q=await I.readdir(G);for(let Y of Q){let X=uM.join(G,Y);if(!(await I.stat(X).catch(()=>null))?.isDirectory())continue;let W=await I.readdir(X),q=uM.join(X,"current"),U=null;if(W.includes("current")){if((await I.lstat(q).catch(()=>null))?.isSymbolicLink()){let K=await I.readlink(q).catch(()=>null);if(K)U=uM.isAbsolute(K)?K:uM.resolve(X,K)}}for(let H of W){if(H==="current")continue;let K=uM.join(X,H);if(!(await I.lstat(K).catch(()=>null))?.isDirectory())continue;if(U!==K)J.push(K)}}return J}async function B1($,I){try{let M=[],G=await lX(I);if(G.length>0)M.push({name:"Unused Binaries",status:"warn",message:"",details:G});let Q=await I.fileRegistry.validate();M.push({name:"Registry Integrity",status:Q.valid?"pass":"warn",message:Q.valid?"Registry is healthy":`Found ${Q.issues.length} issues`,details:Q.issues});let X=(await I.toolInstallationRegistry.getAllToolInstallations()).length;M.push({name:"Tool Installations",status:X>0?"pass":"warn",message:`${X} tool${X===1?"":"s"} installed`});let R=M.some((H)=>H.status==="fail"),W=M.some((H)=>H.status==="warn");return{success:!0,data:{overall:R?"unhealthy":W?"warning":"healthy",checks:M,lastCheck:new Date().toISOString()}}}catch(M){return $.error(b.apiError("getHealth"),M),{success:!1,error:"Failed to retrieve health status"}}}import y6 from"path";async function x1($,I){let M=$.fs,G=0;try{if(!await M.exists(I))return 0;let J=await M.readdir(I);for(let Q of J){let Y=y6.join(I,Q),X=await M.stat(Y);if(X.isDirectory())G+=await x1($,Y);else if(X.isFile())G+=X.size}}catch{}return G}async function v6($,I){let M=y6.join($.projectConfig.paths.generatedDir,"binaries"),G=y6.join(M,I);return x1($,G)}var m0=null;async function aX(){let $=new Map;try{let I=Bun.spawn(["git","rev-parse","--show-toplevel"],{stdout:"pipe",stderr:"pipe"}),M=(await new Response(I.stdout).text()).trim();if(await I.exited!==0||!M)return $;let J=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),Q=await new Response(J.stdout).text();if(await J.exited!==0)return $;let X=Q.split(`
224
+ `),R=null;for(let W of X){let q=W.trim();if(!q)continue;if(/^\d{4}-\d{2}-\d{2}/.test(q))R=new Date(q);else if(R){let U=`${M}/${q}`;if(!$.has(U))$.set(U,R)}}}catch{}return $}async function rX($){try{let I=Bun.spawn(["git","log","--diff-filter=A","--format=%aI","--",$],{stdout:"pipe",stderr:"pipe"}),M=await new Response(I.stdout).text();if(await I.exited!==0||!M.trim())return null;let J=M.trim().split(`
225
+ `)[0];if(!J)return null;return new Date(J)}catch{return null}}async function P6($){if(!m0)m0=await aX();let I=m0.get($);if(I)return I;let M=await rX($);if(M)m0.set($,M);return M}var g0=null;async function _$($,I){if(g0)return g0;let{projectConfig:M,fs:G,configService:J,systemInfo:Q}=I;return g0=await J.loadToolConfigs($,M.paths.toolConfigsDir,G,M,Q),g0}async function F1($,I,M=10){try{let G=I.projectConfig.paths.toolConfigsDir,J=[];async function Q(W){let q=await I.fs.readdir(W);for(let U of q){let H=`${W}/${U}`;if((await I.fs.stat(H)).isDirectory())await Q(H);else if(U.endsWith(".tool.ts")){let O=U.replace(/\.tool\.ts$/,"");J.push({name:O,configFilePath:H})}}}return await Q(G),{success:!0,data:{tools:(await Promise.all(J.map(async(W)=>{let q=await P6(W.configFilePath);if(q)return{name:W.name,configFilePath:W.configFilePath,timestamp:q.getTime(),source:"git"};let U=await I.fs.stat(W.configFilePath);return{name:W.name,configFilePath:W.configFilePath,timestamp:U.mtimeMs,source:"mtime"}}))).toSorted((W,q)=>q.timestamp-W.timestamp).slice(0,M).map((W)=>({name:W.name,configFilePath:W.configFilePath,createdAt:u$(W.timestamp),relativeTime:KM(W.timestamp),timestampSource:W.source}))}}}catch(G){return $.error(b.apiError("getRecentTools"),G),{success:!1,error:"Failed to retrieve recent tools"}}}async function L1($,I){try{let M=await I.fileRegistry.getOperations({fileType:"completion"}),G=await I.fileRegistry.getOperations({fileType:"init"}),J=new Map;for(let W of M){let q=J.get(W.filePath);if(!q||W.createdAt>q.createdAt)J.set(W.filePath,W)}let Q=new Map;for(let W of G){let q=Q.get(W.filePath);if(!q||W.createdAt>q.createdAt)Q.set(W.filePath,W)}let Y=Array.from(J.values()).filter((W)=>W.operationType!=="rm").map((W)=>({toolName:W.toolName,filePath:W.filePath,fileType:"completion",lastModified:u$(W.createdAt)})),X=Array.from(Q.values()).filter((W)=>W.operationType!=="rm").map((W)=>({toolName:W.toolName,filePath:W.filePath,fileType:"init",lastModified:u$(W.createdAt)}));return{success:!0,data:{completions:Y,initScripts:X,totalFiles:Y.length+X.length}}}catch(M){return $.error(b.apiError("getShellIntegration"),M),{success:!1,error:"Failed to retrieve shell integration"}}}async function E1($,I){try{let M=await I.fileRegistry.getStats();return{success:!0,data:{toolsInstalled:(await I.toolInstallationRegistry.getAllToolInstallations()).length,updatesAvailable:0,filesTracked:M.totalFiles,totalOperations:M.totalOperations,oldestOperation:M.oldestOperation>0?u$(M.oldestOperation):null,newestOperation:M.newestOperation>0?u$(M.newestOperation):null}}}catch(M){return $.error(b.apiError("getStats"),M),{success:!1,error:"Failed to retrieve statistics"}}}async function T1($,I,M){let G=$.getSubLogger({name:"checkToolUpdate",context:M});try{let Q=(await _$($,I))[M];if(!Q)return{success:!1,error:`Tool "${M}" not found in configuration`};let Y=I.pluginRegistry.get(Q.installationMethod);if(!Y||!Y.supportsUpdateCheck||!Y.supportsUpdateCheck())return{success:!0,data:{hasUpdate:!1,currentVersion:Q.version||"unknown",latestVersion:"unknown",supported:!1,error:`Update checking is not supported for installation method "${Q.installationMethod}"`}};let X=await Y.checkUpdate?.(M,Q,{},G);if(!X)return{success:!0,data:{hasUpdate:!1,currentVersion:Q.version||"unknown",latestVersion:"unknown",supported:!1,error:"Update check returned no result"}};if(!X.success)return{success:!0,data:{hasUpdate:!1,currentVersion:Q.version||"unknown",latestVersion:"unknown",supported:!0,error:X.error}};return G.info(b.checkUpdateCompleted(X.hasUpdate,X.currentVersion??"unknown",X.latestVersion??"unknown")),{success:!0,data:{hasUpdate:X.hasUpdate,currentVersion:X.currentVersion??Q.version??"unknown",latestVersion:X.latestVersion??"unknown",supported:!0}}}catch(J){let Q=J instanceof Error?J.message:String(J);return G.error(b.checkUpdateFailed(Q),J),{success:!1,error:`Failed to check for updates: ${Q}`}}}async function S1($,I){try{let M=I.projectConfig.paths.toolConfigsDir,G=await _$($,I),J=new Map;for(let X of Object.values(G))if(X.configFilePath)J.set(X.configFilePath,X.name);async function Q(X){let R=[],W=await I.fs.readdir(X);for(let q of W){let U=`${X}/${q}`;if((await I.fs.stat(U)).isDirectory()){let K=await Q(U);if(K.length>0)R.push({name:q,path:U,type:"directory",children:K})}else if(q.endsWith(".tool.ts"))R.push({name:q,path:U,type:"file",toolName:J.get(U)})}return R.toSorted((q,U)=>{if(q.type!==U.type)return q.type==="directory"?-1:1;return q.name.localeCompare(U.name)})}let Y=await Q(M);return{success:!0,data:{rootPath:M,entries:Y}}}catch(M){return $.error(b.apiError("getToolConfigsTree"),M),{success:!1,error:"Failed to retrieve tool configs tree"}}}async function k1($,I,M){try{let J=(await I.fileRegistry.getOperations({toolName:M})).toSorted((X,R)=>R.createdAt-X.createdAt),Q=await I.toolInstallationRegistry.getToolInstallation(M),Y=J.map((X)=>({id:X.id,operationType:X.operationType,fileType:X.fileType,filePath:X.filePath,timestamp:u$(X.createdAt),relativeTime:KM(X.createdAt)}));return{success:!0,data:{entries:Y,totalCount:Y.length,installedAt:Q?.installedAt.toISOString()??null,dotfilesDir:I.projectConfig.paths.dotfilesDir}}}catch(G){return $.error(b.apiError("getToolHistory"),G),{success:!1,error:"Failed to retrieve tool history"}}}async function w1($,I,M,G){let J=$.getSubLogger({name:"installTool",context:M});try{let Y=(await _$($,I))[M];if(!Y)return{success:!1,error:`Tool "${M}" not found in configuration`};let X=await I.installer.install(M,Y,{force:G.force??!1});if(!X.success)return J.error(b.installFailed(X.error??"Unknown error")),{success:!0,data:{installed:!1,error:X.error??"Installation failed"}};return J.info(b.installSucceeded()),{success:!0,data:{installed:!0,version:X.version,alreadyInstalled:X.installationMethod==="already-installed"}}}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);return J.error(b.installFailed(Y),Q),{success:!1,error:`Failed to install tool: ${Y}`}}}function b1($){if(!$)return null;let I=$.repo;return typeof I==="string"?I:null}function sX($,I){if(I.platform===0)return!1;if(!oI($.platforms,I.platform))return!1;if($.architectures===void 0)return!0;if(I.arch===0)return!1;return eI($.architectures,I.arch)}function tX($,I){let M=b1($.installParams);if(M)return M;for(let G of $.platformConfigs??[]){if(!sX(G,I))continue;let J=b1(G.config?.installParams);if(J)return J}return null}async function N1($,I,M){try{let J=(await _$($,I))[M];if(!J)return{success:!1,error:"Tool not found"};let Q=tX(J,I.systemInfo);if(!Q)return{success:!1,error:"Tool does not have a GitHub repository"};let Y=J.version?[J.version,"main","master"]:["main","master"];for(let X of Y){let R=`https://raw.githubusercontent.com/${Q}/${X}/README.md`;try{let W=await I.downloader.download($,R);if(W)return{success:!0,data:{content:W.toString("utf-8")}}}catch(W){if(W instanceof N$)continue;throw W}}return{success:!1,error:"README not found"}}catch(G){return $.error(b.apiError("getToolReadme"),G),{success:!1,error:"Failed to retrieve README"}}}async function y1($,I,M){try{let J=(await _$($,I))[M];if(!J)return{success:!1,error:"Tool not found"};let Q=J.configFilePath;if(!Q)return{success:!1,error:"Tool configuration file path not available"};return{success:!0,data:{content:await I.fs.readFile(Q,"utf-8"),filePath:Q}}}catch(G){return $.error(b.apiError("getToolSource"),G),{success:!1,error:"Failed to retrieve tool source"}}}async function v1($,I,M){let G=$.getSubLogger({name:"updateTool",context:M});try{let Q=(await _$($,I))[M];if(!Q)return{success:!1,error:`Tool "${M}" not found in configuration`};if(Q.version!=="latest")return{success:!0,data:{updated:!1,supported:!1,error:`Tool is pinned to version "${Q.version}". Only tools with version "latest" can be updated.`}};let Y=I.pluginRegistry.get(Q.installationMethod);if(!Y||!Y.supportsUpdate())G.warn(b.updateNotSupported(Q.installationMethod));let R=(await I.toolInstallationRegistry.getToolInstallation(M))?.version??"unknown",W=await I.installer.install(M,Q,{force:!0});if(!W.success)return G.error(b.updateFailed(W.error??"Unknown error")),{success:!0,data:{updated:!1,supported:!0,error:W.error??"Update failed"}};let q="version"in W&&typeof W.version==="string"?W.version:"unknown";return G.info(b.updateSucceeded(R,q)),{success:!0,data:{updated:!0,oldVersion:R,newVersion:q,supported:!0}}}catch(J){let Q=J instanceof Error?J.message:String(J);return G.error(b.updateFailed(Q),J),{success:!1,error:`Failed to update tool: ${Q}`}}}async function oX($,I){return Promise.all($.map(async(M)=>{if(M.sizeBytes!==void 0)return M;try{let G=await I.stat(M.filePath);if(G.isFile())return{...M,sizeBytes:G.size}}catch{}return M}))}function eX($){if(!$.binaries||$.binaries.length===0)return[];return $.binaries.map((I)=>typeof I==="string"?I:I.name)}async function $8($,I,M){let G=await Promise.all(M.map(async(Q)=>{let Y=await $.toolInstallationRegistry.getToolUsage(I,Q);return{binaryName:Q,count:Y?.usageCount??0,lastUsedAt:Y?.lastUsedAt?Y.lastUsedAt.toISOString():null}}));return{totalCount:G.reduce((Q,Y)=>Q+Y.count,0),binaries:G}}async function P1($,I){try{let M=await _$($,I),G=await I.toolInstallationRegistry.getAllToolInstallations(),J=new Map(G.map((X)=>[X.toolName,X]));return{success:!0,data:(await Promise.all(Object.values(M).map(async(X)=>{let R=await I.fileRegistry.getFileStatesForTool(X.name),W=await oX(R,I.fs),q=await v6(I,X.name),U=eX(X),H=await $8(I,X.name,U);return j1(X,J,W,I.systemInfo,q,H)}))).toSorted((X,R)=>X.config.name.localeCompare(R.config.name))}}catch(M){return $.error(b.apiError("getTools"),M),{success:!1,error:"Failed to retrieve tools"}}}function C6($,I){let M=$.getSubLogger({name:"api"});return{getTools:()=>P1(M,I),getStats:()=>E1(M,I),getHealth:()=>B1(M,I),getConfig:()=>z1(M,I),getToolConfigsTree:()=>S1(M,I),getShellIntegration:()=>L1(M,I),getActivity:(G)=>V1(M,I,G),getToolHistory:(G)=>k1(M,I,G),getToolReadme:(G)=>N1(M,I,G),getToolSource:(G)=>y1(M,I,G),getRecentTools:(G)=>F1(M,I,G),installTool:(G,J)=>w1(M,I,G,J),checkToolUpdate:(G)=>T1(M,I,G),updateTool:(G)=>v1(M,I,G)}}var d1=C1("{\"index\":\"./dashboard.js\",\"files\":[{\"path\":\"./cli-w822cqdk.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"IUqVLF461B4\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"path\":\"./cli-fj2hdbnx.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"SXWin7hyR_o\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-vf1askzj.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"bWBROiF9oL0\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard.js\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"LV0S3GxJHiY\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/preact-iso@2.11.1/node_modules/preact-iso/src/prerender.js\",\"path\":\"./prerender-kpxyx916.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"D-BSy7GnzyQ\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/shiki@3.23.0/node_modules/shiki/dist/wasm.mjs\",\"path\":\"./wasm-n3cagcre.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"50fw3f0UtlU\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-3axqywva.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"gMrIjjRYnE4\",\"content-type\":\"text/css;charset=utf-8\"}}]}");var J8=import.meta.dir,n0=!1,Q8=n0&&process.env.DOTFILES_IS_RELOAD==="1";function Y8($){let I={};try{let M=M8.readdirSync($);for(let G of M)if(G.endsWith(".js")){let J=G8.join($,G);I[`/${G}`]=()=>{return new Response(Bun.file(J),{headers:{"Content-Type":"text/javascript"}})}}}catch{}return I}function d6($,I,M){let G=$.getSubLogger({name:"DashboardServer"}),J=C6(G,I),Q=null;return{async start(){if(process.env.DOTFILES_IS_RELOAD="1",!n0)process.chdir(J8);let Y=n0?{}:Y8(process.cwd());return Q=Bun.serve({port:M.port,hostname:M.host,development:n0,routes:{...Y,"/api/tools":async()=>{let X=await J.getTools();return Response.json(X)},"/api/stats":async()=>{let X=await J.getStats();return Response.json(X)},"/api/health":async()=>{let X=await J.getHealth();return Response.json(X)},"/api/config":async()=>{let X=await J.getConfig();return Response.json(X)},"/api/tool-configs-tree":async()=>{let X=await J.getToolConfigsTree();return Response.json(X)},"/api/shell":async()=>{let X=await J.getShellIntegration();return Response.json(X)},"/api/activity":async(X)=>{let W=new URL(X.url).searchParams.get("limit"),q=W?parseInt(W,10):void 0,U=await J.getActivity(q);return Response.json(U)},"/api/tools/:name/history":async(X)=>{let R=decodeURIComponent(X.params.name),W=await J.getToolHistory(R);return Response.json(W)},"/api/tools/:name/readme":async(X)=>{let R=decodeURIComponent(X.params.name),W=await J.getToolReadme(R);return Response.json(W)},"/api/tools/:name/source":async(X)=>{let R=decodeURIComponent(X.params.name),W=await J.getToolSource(R);return Response.json(W)},"/api/tools/:name/install":async(X)=>{if(X.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let R=decodeURIComponent(X.params.name),W=await X.json().catch(()=>({})),q=await J.installTool(R,W);return Response.json(q)},"/api/tools/:name/check-update":async(X)=>{if(X.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let R=decodeURIComponent(X.params.name),W=await J.checkToolUpdate(R);return Response.json(W)},"/api/tools/:name/update":async(X)=>{if(X.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let R=decodeURIComponent(X.params.name),W=await J.updateTool(R);return Response.json(W)},"/api/recent-tools":async(X)=>{let W=new URL(X.url).searchParams.get("limit"),q=W?parseInt(W,10):void 0,U=await J.getRecentTools(q);return Response.json(U)},"/api/*":Response.json({success:!1,error:"Not found"},{status:404}),"/server/*":(X)=>{let R=new URL(X.url),W=R.pathname.replace(/^\/server\//,"/");return Response.redirect(new URL(W,R.origin).href,302)},"/*":d1},fetch(X){let R=new URL(X.url);return G.debug(b.requestReceived(X.method,R.pathname)),new Response("Not Found",{status:404})}}),G.info(b.serverStarted(this.getUrl())),Q8},async stop(){if(G.info(b.serverStopping()),Q)Q.stop(),Q=null;G.info(b.serverStopped())},getUrl(){return`http://${M.host}:${M.port}`}}}var{$:X8}=globalThis.Bun;var Z8=async($,I)=>{let M=I===2?"open":I===4?"start":"xdg-open";await X8`${M} ${$}`.nothrow().quiet()};function u1($,I,M,G={}){let J=G.openBrowser??Z8,Q=G.createServer??d6,Y=$.getSubLogger({name:"dashboard"});I.command("dashboard").description("Start the web-based visualization dashboard").option("--port <port>","Port to run the server on","3000").option("--host <host>","Host to bind the server to","localhost").option("--no-open","Do not open browser when server starts").action(async(X)=>{let R=parseInt(X.port??"3000",10),W=X.host??"localhost",q=X.open??!0,U=await M(),H={projectConfig:U.projectConfig,fs:U.fs,configService:U.configService,systemInfo:U.systemInfo,fileRegistry:U.fileRegistry,toolInstallationRegistry:U.toolInstallationRegistry,versionChecker:U.versionChecker,downloader:U.downloader,installer:U.installer,pluginRegistry:U.pluginRegistry},O=await Q(Y,H,{port:R,host:W}).start();if(q&&!O){let B=`http://${W}:${R}`;try{await J(B,U.systemInfo.platform)}catch(j){Y.warn(_.dashboardBrowserOpenFailed(),j)}}})}import sI from"path";var f1={name:"detect-conflicts",description:"Detect file conflicts before generating"};async function R8($,I,M,G,J){try{let Q=await G.loadToolConfigs($,I.paths.toolConfigsDir,M,I,J);return{toolConfigs:Object.values(Q),exitCode:E.SUCCESS}}catch(Q){return $.error(_.configLoadFailed("tool configurations"),Q),{toolConfigs:[],exitCode:E.ERROR}}}async function W8($,I,M,G,J){if(!M.binaries)return;for(let Q of M.binaries){let Y=typeof Q==="string"?Q:Q.name,X=sI.join(G,Y);if(await I.exists(X))try{if(!(await I.readFile(X)).includes("# Generated by Dotfiles Management Tool"))J.push(`[${M.name}]: ${X} (exists but is not a generator shim)`)}catch(R){$.warn(_.fsReadFailed(X),R),J.push(`[${M.name}]: ${X} (exists but could not be read/verified)`)}}}async function q8($,I,M,G,J,Q){if(!M.symlinks)return;for(let Y of M.symlinks){let X=sI.join(G,Y.target),R=sI.join(J,Y.source);try{let W=await I.lstat(X);if(W)if(W.isSymbolicLink()){let q=await I.readlink(X);if(sI.resolve(sI.dirname(X),q)!==R)Q.push(`[${M.name}]: ${X} (points to '${q}', expected '${R}')`)}else Q.push(`[${M.name}]: ${X} (exists but is not a symlink)`)}catch(W){if(W.code!=="ENOENT")$.warn(_.fsReadFailed(X),W)}}}function U8($,I){if(I.length>0){let G=I.map((J)=>` - ${J}`).join(`
226
+ `);return $.warn(_.toolConflictsDetected("Conflicts detected with files not owned by the generator:",G)),E.ERROR}else return $.info(_.noConflictsDetected()),E.SUCCESS}async function H8($,I,M){let{projectConfig:G,fs:J,configService:Q,systemInfo:Y}=M,X=[],R=await R8($,G,J,Q,Y);if(R.exitCode!==E.SUCCESS)return R.exitCode;let W=R.toolConfigs;if(W.length===0)return $.info(_.toolNoConfigurationsFound(G.paths.toolConfigsDir)),E.SUCCESS;for(let q of W)await W8($,J,q,G.paths.targetDir,X),await q8($,J,q,G.paths.homeDir,G.paths.dotfilesDir,X);return U8($,X)}function p1($,I,M){let G=$.getSubLogger({name:"registerDetectConflictsCommand"});I.command("detect-conflicts").description("Detects conflicts between potential generated artifacts and existing system files.").action(async()=>{let J=I.opts(),Q;try{let Y=await M();Q=await H8(G,J,Y)}catch(Y){G.error(_.commandExecutionFailed("detect-conflicts",E.ERROR),Y),Q=E.ERROR}y(Q)})}var Q$="DOTFILES_ENV_DIR",wI="DOTFILES_ENV_NAME",fM="env",i0="source",c1="source.ps1",S$="dotfiles.config.ts",u6="tools";function h1(){let $=gM();return c(`
227
227
  import { defineConfig } from '${$}';
228
228
 
229
229
  export default defineConfig(({ configFileDir }) => {
@@ -238,22 +238,22 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
238
238
  },
239
239
  };
240
240
  });
241
- `)}function pG($,M){return c(`
241
+ `)}function m1($,I){return c(`
242
242
  # ==============================================================================
243
243
  # Dotfiles Virtual Environment Activation Script (PowerShell)
244
244
  # ==============================================================================
245
245
  # This file is automatically generated. Do not edit directly.
246
246
  #
247
247
  # Usage:
248
- # . .\\${M}\\source.ps1
249
- # . ${M}/source.ps1
248
+ # . .\\${I}\\source.ps1
249
+ # . ${I}/source.ps1
250
250
  #
251
251
  # To deactivate:
252
252
  # dotfiles-deactivate
253
253
  # ==============================================================================
254
254
 
255
255
  function global:dotfiles-deactivate {
256
- if ($env:${G$}) {
256
+ if ($env:${Q$}) {
257
257
  # Restore original XDG_CONFIG_HOME
258
258
  if ($env:_DOTFILES_OLD_XDG_CONFIG_HOME) {
259
259
  $env:XDG_CONFIG_HOME = $env:_DOTFILES_OLD_XDG_CONFIG_HOME
@@ -261,15 +261,15 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
261
261
  } else {
262
262
  Remove-Item Env:XDG_CONFIG_HOME -ErrorAction SilentlyContinue
263
263
  }
264
- Remove-Item Env:${G$} -ErrorAction SilentlyContinue
265
- Remove-Item Env:${TM} -ErrorAction SilentlyContinue
264
+ Remove-Item Env:${Q$} -ErrorAction SilentlyContinue
265
+ Remove-Item Env:${wI} -ErrorAction SilentlyContinue
266
266
  Remove-Item Function:dotfiles-deactivate -ErrorAction SilentlyContinue
267
267
  Write-Host "Deactivated dotfiles environment"
268
268
  }
269
269
  }
270
270
 
271
271
  # If already active, deactivate first
272
- if ($env:${G$}) {
272
+ if ($env:${Q$}) {
273
273
  dotfiles-deactivate
274
274
  }
275
275
 
@@ -286,14 +286,14 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
286
286
  }
287
287
 
288
288
  # Export environment variables
289
- $env:${G$} = $scriptDir
290
- $env:${TM} = "${M}"
289
+ $env:${Q$} = $scriptDir
290
+ $env:${wI} = "${I}"
291
291
  $env:XDG_CONFIG_HOME = "$scriptDir\\.config"
292
292
 
293
- Write-Host "Activated dotfiles environment: ${M}"
294
- Write-Host " Directory: $env:${G$}"
295
- Write-Host " Config: $env:${G$}\\config.ts"
296
- `)}function cG($,M){return c(`
293
+ Write-Host "Activated dotfiles environment: ${I}"
294
+ Write-Host " Directory: $env:${Q$}"
295
+ Write-Host " Config: $env:${Q$}\\${S$}"
296
+ `)}function g1($,I){return c(`
297
297
  #!/bin/sh
298
298
  # ==============================================================================
299
299
  # Dotfiles Virtual Environment Activation Script
@@ -301,8 +301,8 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
301
301
  # This file is automatically generated. Do not edit directly.
302
302
  #
303
303
  # Usage:
304
- # source ${M}/source
305
- # . ./${M}/source
304
+ # source ${I}/source
305
+ # . ./${I}/source
306
306
  #
307
307
  # To deactivate:
308
308
  # dotfiles-deactivate
@@ -310,7 +310,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
310
310
 
311
311
  # Deactivate function to clean up environment
312
312
  dotfiles-deactivate() {
313
- if [ -n "\${${G$}:-}" ]; then
313
+ if [ -n "\${${Q$}:-}" ]; then
314
314
  # Restore original XDG_CONFIG_HOME
315
315
  if [ -n "\${_DOTFILES_OLD_XDG_CONFIG_HOME:-}" ]; then
316
316
  export XDG_CONFIG_HOME="\${_DOTFILES_OLD_XDG_CONFIG_HOME}"
@@ -318,15 +318,15 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
318
318
  else
319
319
  unset XDG_CONFIG_HOME
320
320
  fi
321
- unset ${G$}
322
- unset ${TM}
321
+ unset ${Q$}
322
+ unset ${wI}
323
323
  unset -f dotfiles-deactivate 2>/dev/null
324
324
  echo "Deactivated dotfiles environment"
325
325
  fi
326
326
  }
327
327
 
328
328
  # If already active, deactivate first
329
- if [ -n "\${${G$}:-}" ]; then
329
+ if [ -n "\${${Q$}:-}" ]; then
330
330
  dotfiles-deactivate
331
331
  fi
332
332
 
@@ -347,22 +347,22 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
347
347
  fi
348
348
 
349
349
  # Export environment variables
350
- export ${G$}="\${_dotfiles_script_dir}"
351
- export ${TM}="${M}"
350
+ export ${Q$}="\${_dotfiles_script_dir}"
351
+ export ${wI}="${I}"
352
352
  export XDG_CONFIG_HOME="\${_dotfiles_script_dir}/.config"
353
353
 
354
354
  # Clean up temporary variable
355
355
  unset _dotfiles_script_dir
356
356
 
357
- echo "Activated dotfiles environment: ${M}"
358
- echo " Directory: \${${G$}}"
359
- echo " Config: \${${G$}}/config.ts"
360
- `)}import{z as s$}from"zod";var xx=s$.object({name:s$.string().min(1).default("env"),parentDir:s$.string().min(1),force:s$.boolean().default(!1)}),Tx=s$.object({envDir:s$.string(),name:s$.string(),configPath:s$.string(),sourcePath:s$.string(),toolsDir:s$.string()});import O$ from"path";var C$={creatingEnv:($)=>W(`Creating environment: ${$}`),envCreated:($)=>W(`Environment created at ${$}`),envAlreadyExists:($)=>W(`Environment already exists at ${$}`),envNotFound:($)=>W(`Environment not found at ${$}`),deletingEnv:($)=>W(`Deleting environment: ${$}`),envDeleted:($)=>W(`Environment deleted at ${$}`),envDetected:($)=>W(`Detected environment at ${$}`),envActive:($)=>W(`Active environment: ${$}`),sourceFileGenerated:($)=>W(`Source file generated at ${$}`),configFileGenerated:($)=>W(`Config file generated at ${$}`),toolsDirCreated:($)=>W(`Tools directory created at ${$}`),writeFile:($)=>W(`Writing ${$}`),deleteConfirmationRequired:()=>W("Deletion requires confirmation")};class iJ{parentLogger;fs;env;constructor($,M,J=process.env){this.parentLogger=$;this.fs=M;this.env=J}get logger(){return this.parentLogger.getSubLogger({name:"VirtualEnvManager"})}async create($){let M=this.logger.getSubLogger({name:"create"}),J=$.name,Q=O$.resolve($.parentDir,J);if(M.debug(C$.creatingEnv(J)),await this.fs.exists(Q)){if(!$.force)return M.warn(C$.envAlreadyExists(Q)),{success:!1,error:`Environment already exists at ${Q}`};await this.fs.rm(Q,{recursive:!0})}await this.fs.ensureDir(Q);let Y=O$.join(Q,C6);await this.fs.ensureDir(Y),M.debug(C$.toolsDirCreated(Y));let G=O$.join(Q,nJ),X=cG(Q,J);await this.fs.writeFile(G,X),await this.fs.chmod(G,493),M.debug(C$.sourceFileGenerated(G));let Z=O$.join(Q,uG),q=pG(Q,J);await this.fs.writeFile(Z,q),M.debug(C$.sourceFileGenerated(Z));let I=O$.join(Q,HM),U=fG();return await this.fs.writeFile(I,U),M.debug(C$.configFileGenerated(I)),M.debug(C$.envCreated(Q)),{success:!0,envDir:Q,envName:J}}async delete($){let M=this.logger.getSubLogger({name:"delete"}),J=O$.basename($);if(!await this.isValidEnv($))return M.warn(C$.envNotFound($)),{success:!1,error:`Environment not found at ${$}`};return M.debug(C$.deletingEnv(J)),await this.fs.rm($,{recursive:!0}),M.debug(C$.envDeleted($)),{success:!0,envDir:$,envName:J}}async getEnvInfo($){if(!await this.isValidEnv($))return null;return{envDir:O$.resolve($),name:O$.basename($),configPath:O$.join($,HM),sourcePath:O$.join($,nJ),toolsDir:O$.join($,C6)}}async isValidEnv($){let M=O$.join($,nJ),J=O$.join($,HM),[Q,Y]=await Promise.all([this.fs.exists(M),this.fs.exists(J)]);return Q&&Y}async detectEnv($,M){let J=this.logger.getSubLogger({name:"detectEnv"}),Q=M??P0,Y=O$.resolve($,Q);if(await this.isValidEnv(Y))return J.debug(C$.envDetected(Y)),{found:!0,envDir:Y,envName:Q,configPath:O$.join(Y,HM)};return{found:!1}}getActiveEnv(){let $=this.env[G$],M=this.env[TM];if($&&M)return{active:!0,envDir:$,envName:M};return{active:!1}}}import hG from"path";import*as mG from"readline";async function W3($){let M=mG.createInterface({input:process.stdin,output:process.stdout});return new Promise((J)=>{M.question(`Delete environment at '${$}'? [y/N] `,(Q)=>{M.close(),J(Q.toLowerCase()==="y"||Q.toLowerCase()==="yes")})})}async function q3($,M,J){let Q=new z$,Y=new iJ($,Q),G=process.cwd(),X=await Y.create({name:M,parentDir:G,force:!1});if(!X.success){$.error(R.envOperationFailed("create",X.error)),N(1);return}let Z=hG.join(X.envDir,HM);$.info(R.envCreated(X.envDir)),$.info(R.envActivationHint(M)),$.info(R.envConfigPath(Z))}async function I3($,M,J){let Q=new z$,Y=new iJ($,Q),G=process.cwd(),X=hG.resolve(G,M);if(!await Y.isValidEnv(X)){$.error(R.envNotFound(X)),N(1);return}if(!J.force){if(!await W3(X)){$.info(R.envDeletionCancelled());return}}let Z=await Y.delete(X);if(!Z.success){$.error(R.envOperationFailed("delete",Z.error)),N(1);return}$.info(R.envDeleted(Z.envDir))}function gG($,M){let J=$.getSubLogger({name:"registerEnvCommand"}),Q=M.command("env").description("Manage virtual environments for isolated dotfiles configurations.");Q.command("create [name]").description("Create a new virtual environment").action(async(Y)=>{let G=Y??P0,X=M.opts();await q3(J,G,X)}),Q.command("delete [name]").description("Delete a virtual environment").option("--force","Skip confirmation prompt",!1).action(async(Y,G)=>{let X=Y??P0,Z={...G,...M.opts()};await I3(J,X,Z)})}var nG={name:"features",description:"Manage features and generate artifacts",subcommands:[{name:"catalog",description:"Generate catalog of available features"}]};async function U3($,M,J){try{let{projectConfig:Q,fs:Y,configService:G,readmeService:X,systemInfo:Z}=J,q=await G.loadToolConfigs($,Q.paths.toolConfigsDir,Y,Q,Z);await X.generateCatalogFromConfigs(Q.features.catalog.filePath,q)}catch(Q){$.error(R.commandExecutionFailed("features catalog",1),Q),N(1)}}function iG($,M,J){let Q=$.getSubLogger({name:"registerFeaturesCommand"});M.command("features").description("Manage features and generate feature-specific artifacts.").command("catalog").description("Catalog of available features documentation").action(async()=>{let G=M.opts(),X=await J();await U3(Q,G,X),Q.info(R.commandCompleted(Boolean(G.dryRun)))})}var lG={name:"files",description:"Show generated files structure",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool"};async function aG($,M,J){let Q=[];try{let Y=await M.readdir(J);for(let G of Y){let X=`${J}/${G}`,q=(await M.stat(X)).isDirectory(),I={name:G,isDirectory:q};if(q)I.children=await aG($,M,X);Q.push(I)}}catch(Y){$.error(R.commandExecutionFailed("files",x.ERROR),Y)}return Q.toSorted((Y,G)=>{if(Y.isDirectory===G.isDirectory)return Y.name.localeCompare(G.name);return Y.isDirectory?-1:1})}function sG($,M=""){let J=[];for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(!Y)continue;let G=Q===$.length-1,X=G?"\u2514\u2500 ":"\u251C\u2500 ",Z=Y.name;if(J.push(`${M}${X}${Z}`),Y.isDirectory&&Y.children&&Y.children.length>0){let q=M+(G?" ":"\u2502 "),I=sG(Y.children,q);J.push(I)}}return J.join(`
361
- `)}async function K3($,M,J,Q,Y){let G=await J.getToolInstallation(Q);if(!G)return $.error(R.toolNotInstalled(Q)),x.ERROR;let X=G.installPath;if(!await M.exists(X))return $.error(R.installPathNotFound(X)),x.ERROR;Y(X);let q=await aG($,M,X);if(q.length===0)return Y("(empty directory)"),x.SUCCESS;let I=sG(q);return Y(I),x.SUCCESS}async function H3($,M,J,Q,Y){let{fs:G,projectConfig:X,configService:Z,toolInstallationRegistry:q,systemInfo:I}=Q;try{if(!await Z.loadSingleToolConfig($,M,X.paths.toolConfigsDir,G,X,I)){$.error(R.toolNotFound(M,X.paths.toolConfigsDir)),N(x.ERROR);return}let K=await K3($,G,q,M,Y);if(K!==x.SUCCESS)N(K)}catch(U){$.error(R.commandExecutionFailed("files",x.ERROR),U),N(x.ERROR)}}function rG($,M,J,Q=console.log){let Y=$.getSubLogger({name:"registerFilesCommand"});M.command("files <toolName>").description("Display a tree view of files in the tool installation directory").action(async(G,X)=>{let Z={...X,...M.opts()},q=await J();await H3(Y,G,Z,q,Q)})}import u6 from"path";var tG={name:"generate",description:"Generate shims, shell init files, and symlinks",options:[{flag:"--overwrite",description:"Overwrite conflicting files not created by generator"}]};import _3 from"path";var oG={name:"install",description:"Install a tool by name or binary",hasPositionalArg:!0,positionalArgDescription:"tool name or binary name to install",positionalArgType:"tool",options:[{flag:"--force",description:"Force installation even if already installed"},{flag:"--shim-mode",description:"Optimized output for shim usage"}]};function R3($){return typeof $==="object"&&$!==null&&"error"in $}async function O3($,M,J,Q,Y,G,X){let Z=await G.loadSingleToolConfig($,M,J,Q,Y,X);if(Z)return{success:!0,toolConfig:Z,toolName:M};$.debug(R.toolLookupByBinaryStarted(M));let q=await G.loadToolConfigByBinary($,M,J,Q,Y,X);if(R3(q))return{success:!1,error:q.error};if(q)return $.debug(R.toolFoundByBinary(M,q.name)),{success:!0,toolConfig:q,toolName:q.name};return{success:!1,error:`No tool or binary named "${M}" found in ${J}`}}function j3($,M,J,Q){if(M.success)if(Q)return 0;else{let Y=M.installationMethod??"unknown",G=M.version??"unknown";if(Y==="already-installed")$.info(R.toolAlreadyInstalled(J,G));else $.info(R.toolInstalled(J,G,Y));return null}else return 1}function V3($,M,J,Q){if(Q)process.stderr.write(`Failed to install '${J}': ${M.message}
362
- `);else $.error(R.commandExecutionFailed("install",1),M);return 1}async function z3($,M,J,Q){if(!$.binaries||$.binaries.length===0)return;for(let Y of $.binaries){let G=typeof Y==="string"?Y:Y.name,X=_3.join(M,G);try{await J.lstat(X),await J.rm(X,{force:!0}),Q.debug(R.shimDeleted(G,X))}catch{}}}function B3($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}function D3($){if($ instanceof Error)return $;return Error(typeof $==="string"?$:"Unknown error")}async function A3($,M,J,Q){let{projectConfig:Y,fs:G,installer:X,configService:Z,generatorOrchestrator:q,systemInfo:I}=Q;$.debug(R.commandActionStarted("install",M),Y.paths.toolConfigsDir,G.constructor.name);let U=await O3($,M,Y.paths.toolConfigsDir,G,Y,Z,I);if(!U.success)return $.error(R.toolNotFoundByBinary(M,Y.paths.toolConfigsDir)),1;let{toolConfig:K,toolName:H}=U,_=Y$(K,I);if(B3(_)){if(!J.shimMode)$.info(R.toolInstallSkippedConfigurationOnly(H));return await q.generateCompletionsForTool(H,K),J.shimMode?0:null}let O=await X.install(H,K,{force:J.force,verbose:J.verbose,shimMode:J.shimMode});if(O.success){let j="binaryPaths"in O?O.binaryPaths:void 0;if(await q.generateCompletionsForTool(H,K,O.version,j),Q.pluginRegistry.getExternallyManagedMethods().has(_.installationMethod))await z3(_,Y.paths.targetDir,G,$)}return j3($,O,H,J.shimMode)}function eG($,M,J){let Q=$.getSubLogger({name:"registerInstallCommand"});M.command("install <nameOrBinary>").description("Installs a tool by name or binary. Accepts tool name (filename without .tool.ts) or binary name (from .bin()).").option("--force","Force installation even if the tool is already installed",!1).option("--shim-mode","Optimized output for shim usage: shows progress bars but suppresses log messages",!1).action(async(Y,G)=>{let X={...G,...M.opts()},Z=await J(),q=null;try{q=await A3(Q,Y,X,Z)}catch(I){let U=D3(I);q=V3(Q,U,Y,X.shimMode)}if(q!==null)N(q)})}var $7={name:"log",description:"Show file operation history",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool",options:[{flag:"--type",description:"Filter by file type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--status",description:"Show current file states"},{flag:"--since",description:"Show operations since date",hasArg:!0,argPlaceholder:"<date>"}]};function E3($,M){let J=M.getSubLogger({name:"buildOperationsFilter"}),{tool:Q,type:Y,since:G}=$,X={};if(Q)X.toolName=Q;if(Y)X.fileType=Y;if(G){let Z=new Date(G);if(Number.isNaN(Z.getTime()))return J.error(R.configParameterInvalid("date format for --since",G,'ISO format like "2025-08-01"')),{filter:{},exitCode:x.ERROR};X.createdAfter=Z.getTime()}return{filter:X,exitCode:x.SUCCESS}}async function F3($,M,J,Q){let Y=$.getSubLogger({name:"showFileStates"}),G=await M.getRegisteredTools();Y.info(R.logCheckingFileStates());for(let X of G){if(Q&&X!==Q)continue;let Z=await M.getFileStatesForTool(X);if(Z.length===0)continue;Y.info(R.logFileStatesForTool(X));for(let q of Z)await L3(Y,J,q)}}async function L3($,M,J){let Q=$.getSubLogger({name:"logFileState"}),Y=await M.exists(J.filePath),G=Y?"\u2713":"\u2717",X=Y?"exists":"MISSING",Z=J.sizeBytes?` (${J.sizeBytes} bytes)`:"";if(Q.info(R.logFileStatus(G,J.filePath,J.fileType,X,Z)),J.targetPath){let I=await M.exists(J.targetPath)?"\u2192":"\u2717";Q.info(R.logTargetStatus(I,J.targetPath))}}function x3($){let M=[];if($.sizeBytes&&$.operationType==="writeFile")M.push(`size: ${$.sizeBytes}`);if($.metadata&&Object.keys($.metadata).length>0)for(let[J,Q]of Object.entries($.metadata))if(J==="newMode")M.push(`${J}: ${H0(Q)}`);else M.push(`${J}: ${Q}`);return M.length>0?`(${M.join(", ")})`:""}function T3($){return new Date($).toLocaleString("en-US",{hour12:!1,year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).replace(",","")}function k3($,M,J,Q,Y,G){let X=$.getSubLogger({name:"logOperationByType"});switch(M.operationType){case"writeFile":{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"mkdir":{let Z=`[${M.toolName}] mkdir ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"chmod":{let Z=H0(M.permissions||0),q=`[${M.toolName}] chmod ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"rm":{let Z=`[${M.toolName}] rm ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"rename":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] mv ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"cp":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] cp ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"symlink":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] ln -s ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}default:{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,Y))}}}function S3($){let M={};for(let J of $){if(!M[J.toolName])M[J.toolName]=[];M[J.toolName]?.push(J)}return M}async function w3($,M,J){let Q=$.getSubLogger({name:"showOperations"});if(M.length===0){Q.info(R.logNoOperationsFound());return}let Y=S3(M);for(let[,G]of Object.entries(Y))for(let X of G){let Z=T3(X.createdAt),q=x3(X),I=s(J.paths.homeDir,X.filePath);k3(Q,X,Z,I,q,J)}}async function b3($,M,J){let Q=$.getSubLogger({name:"logActionLogic"}),{fileRegistry:Y,fs:G,projectConfig:X}=J;try{if(M.status){await F3(Q,Y,G,M.tool);return}let Z=E3(M,Q);if(Z.exitCode!==x.SUCCESS){N(Z.exitCode);return}let q=await Y.getOperations(Z.filter);await w3(Q,q,X)}catch(Z){Q.error(R.commandExecutionFailed("log",x.ERROR),Z),N(x.ERROR)}}function M7($,M,J){let Q=$.getSubLogger({name:"registerLogCommand"});M.command("log [tool]").description("Inspect tracked files in the registry").option("--type <type>","Show files of specific type only (shim, binary, symlink, etc.)").option("--status","Check file status (missing, broken links, etc.)").option("--since <date>","Show files created since date (ISO format: 2025-08-01)").action(async(Y,G)=>{let X={...G,tool:Y,...M.opts()},Z=await J();await b3(Q,X,Z)})}import{cp as N3}from"fs/promises";import lJ from"path";var J7={name:"skill",description:"Copy the dotfiles skill folder to the target directory",hasPositionalArg:!0,positionalArgDescription:"target directory for skill folder"};function v3(){let $=sM(),M=$.split(" ").pop()??$,J=lJ.dirname(M);return lJ.join(J,"skill")}async function y3($,M,J){let Q=$.getSubLogger({name:"copySkill"}),Y=new z$,G=v3(),X=lJ.join(M,"dotfiles");if(!await Y.exists(G))return Q.error(R.fsItemNotFound("Skill directory",G)),x.ERROR;if(!await Y.exists(M))return Q.error(R.fsItemNotFound("Target directory",M)),x.ERROR;if(await Y.exists(X))Q.info(R.skillAlreadyExists(X)),await Y.rmdir(X,{recursive:!0});if(J)return Q.info(R.skillDryRun(X,G)),x.SUCCESS;try{return await N3(G,X,{recursive:!0}),Q.info(R.skillCopied(X,G)),x.SUCCESS}catch(U){return Q.error(R.skillCopyFailed(X),U),x.ERROR}}async function P3($,M){let J=$.getSubLogger({name:"skillActionLogic"}),{targetPath:Q,dryRun:Y}=M;J.debug(R.commandActionStarted("skill"));let G=await y3(J,Q,Y);N(G)}function Q7($,M,J){let Q=$.getSubLogger({name:"registerSkillCommand"});M.command("skill <path>").description("Copy the dotfiles skill folder to the target directory").action(async(Y)=>{let G={targetPath:lJ.resolve(Y),...M.opts()};await P3(Q,G)})}var Y7={name:"update",description:"Update an installed tool to latest version",hasPositionalArg:!0,positionalArgDescription:"tool name to update",positionalArgType:"tool",options:[{flag:"--shim-mode",description:"Optimized output for shim usage"}]};async function C3($,M,J,Q,Y,G,X){try{let Z=await M.loadSingleToolConfig($,J,Q,Y,G,X);if(!Z)return $.error(R.toolNotFound(J,Q)),{toolConfig:null,exitCode:x.ERROR};return{toolConfig:Z,exitCode:x.SUCCESS}}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),{toolConfig:null,exitCode:x.ERROR}}}async function d3($,M,J,Q,Y){let{toolInstallationRegistry:G,installer:X,pluginRegistry:Z}=M;if(Q.version!=="latest"){$.info(R.toolVersionPinned(J,Q.version));return}let q=Z.get(Q.installationMethod);if(q&&!q.supportsUpdate())$.warn(R.toolUpdateNotSupported(J,Q.installationMethod));let U=(await G.getToolInstallation(J))?.version||"unknown",K=await X.install(J,Q,{force:!0,shimMode:Y});if(!K.success){$.error(R.toolUpdateFailed(J,K.error)),N(x.ERROR);return}let H="version"in K&&typeof K.version==="string"?K.version:"unknown",_=U===H;if(Y)if(_)$.info(R.toolShimUpToDate(J,H));else $.info(R.toolShimUpdateStarting(J,U,H)),$.info(R.toolShimUpdateSuccess(J,H));else $.info(R.toolUpdated(J,U,H))}function G7($,M,J){let Q=$.getSubLogger({name:"registerUpdateCommand"});M.command("update <toolName>").description("Updates a specified tool to its latest version.").option("--shim-mode","Run in shim mode with minimal output",!1).action(async(Y,G)=>{let X={...G,...M.opts()},Z=await J(),{projectConfig:q,fs:I,configService:U,systemInfo:K}=Z;try{let H=await C3(Q,U,Y,q.paths.toolConfigsDir,I,q,K);if(H.exitCode!==x.SUCCESS){N(H.exitCode);return}if(!H.toolConfig){Q.error(R.toolNotFound(Y,q.paths.toolConfigsDir)),N(x.ERROR);return}let _=H.toolConfig;if(!X.shimMode)Q.info(R.commandCheckingUpdatesFor(Y));await d3(Q,Z,Y,_,X.shimMode)}catch(H){Q.error(R.commandExecutionFailed("update",x.ERROR),H),N(x.ERROR)}})}var u3=[QG,oG,tG,WG,XG,Y7,CG,$7,lG,J7,nG];function d6($){let M=$.flag,J=$.description.replace(/'/g,"\\'");if($.hasArg)return`'${M}=[${J}]:${$.argPlaceholder||"arg"}:'`;return`'${M}[${J}]'`}function f3($){let M=[];for(let J of $)M.push(d6(J));return M.push("'1:command:->command'"),M.push("'*::arg:->args'"),M.join(" \\\n")}function p3($){return $.replace(/'/g,"\\'")}function c3($){return $.map((M)=>p3(M)).join(" ")}function h3($,M,J){if(M==="tool"&&J.length>0){let Q=c3(J);return`'1:${$}:(${Q})'`}return`'1:${$}:'`}function m3(){return"_describe 'command' commands"}function g3($){if($.length===0)return;let M=$.length-1,J=$[M];if(J?.endsWith(" \\"))$[M]=J.slice(0,-2)}function n3($,M){let J=[];if($.options)for(let Q of $.options)J.push(d6(Q));for(let Q of M)J.push(d6(Q));return J}function i3($){let M=[];M.push("'1:subcommand:->subcommand'");let J=$.map((Q)=>`'${Q.name}:${Q.description.replace(/'/g,"\\'")}'`).join(" ");return M.push("case $state in"),M.push(" subcommand)"),M.push(` local -a subcommands=(${J})`),M.push(" _describe 'subcommand' subcommands"),M.push(" ;;"),M.push("esac"),M}function l3($,M,J){let Q=[];Q.push(`${$.name})`);let Y=n3($,M);if(Y.length>0||$.hasPositionalArg||$.subcommands){Q.push(" _arguments \\");for(let X of Y)Q.push(` ${X} \\`);if($.subcommands&&$.subcommands.length>0){let X=i3($.subcommands);for(let Z of X)Q.push(` ${Z}`)}else if($.hasPositionalArg){let X=$.positionalArgDescription||"argument",Z=h3(X,$.positionalArgType,J);Q.push(` ${Z}`)}else g3(Q)}return Q.push(" ;;"),Q.join(`
363
- `)}function a3($,M,J){return $.map((Y)=>l3(Y,M,J)).join(`
364
- `)}function X7($,M){let J=u3,Q=KG.options||[],Y=[...M].toSorted((Z,q)=>Z.localeCompare(q)),G=J.map((Z)=>`'${Z.name}:${Z.description.replace(/'/g,"\\'")}'`).join(`
365
- `);return oJ(`
357
+ echo "Activated dotfiles environment: ${I}"
358
+ echo " Directory: \${${Q$}}"
359
+ echo " Config: \${${Q$}}/${S$}"
360
+ `)}import{z as o$}from"zod";var MT=o$.object({name:o$.string().min(1).default("env"),parentDir:o$.string().min(1),force:o$.boolean().default(!1)}),GT=o$.object({envDir:o$.string(),name:o$.string(),configPath:o$.string(),sourcePath:o$.string(),toolsDir:o$.string()});import O$ from"path";var f$={creatingEnv:($)=>Z(`Creating environment: ${$}`),envCreated:($)=>Z(`Environment created at ${$}`),envAlreadyExists:($)=>Z(`Environment already exists at ${$}`),envNotFound:($)=>Z(`Environment not found at ${$}`),deletingEnv:($)=>Z(`Deleting environment: ${$}`),envDeleted:($)=>Z(`Environment deleted at ${$}`),envDetected:($)=>Z(`Detected environment at ${$}`),envActive:($)=>Z(`Active environment: ${$}`),sourceFileGenerated:($)=>Z(`Source file generated at ${$}`),configFileGenerated:($)=>Z(`Config file generated at ${$}`),toolsDirCreated:($)=>Z(`Tools directory created at ${$}`),writeFile:($)=>Z(`Writing ${$}`),deleteConfirmationRequired:()=>Z("Deletion requires confirmation")};class l0{parentLogger;fs;env;constructor($,I,M=process.env){this.parentLogger=$;this.fs=I;this.env=M}get logger(){return this.parentLogger.getSubLogger({name:"VirtualEnvManager"})}async create($){let I=this.logger.getSubLogger({name:"create"}),M=$.name,G=O$.resolve($.parentDir,M);if(I.debug(f$.creatingEnv(M)),await this.fs.exists(G)){if(!$.force)return I.warn(f$.envAlreadyExists(G)),{success:!1,error:`Environment already exists at ${G}`};await this.fs.rm(G,{recursive:!0})}await this.fs.ensureDir(G);let J=O$.join(G,u6);await this.fs.ensureDir(J),I.debug(f$.toolsDirCreated(J));let Q=O$.join(G,i0),Y=g1(G,M);await this.fs.writeFile(Q,Y),await this.fs.chmod(Q,493),I.debug(f$.sourceFileGenerated(Q));let X=O$.join(G,c1),R=m1(G,M);await this.fs.writeFile(X,R),I.debug(f$.sourceFileGenerated(X));let W=O$.join(G,S$),q=h1();return await this.fs.writeFile(W,q),I.debug(f$.configFileGenerated(W)),I.debug(f$.envCreated(G)),{success:!0,envDir:G,envName:M}}async delete($){let I=this.logger.getSubLogger({name:"delete"}),M=O$.basename($);if(!await this.isValidEnv($))return I.warn(f$.envNotFound($)),{success:!1,error:`Environment not found at ${$}`};return I.debug(f$.deletingEnv(M)),await this.fs.rm($,{recursive:!0}),I.debug(f$.envDeleted($)),{success:!0,envDir:$,envName:M}}async getEnvInfo($){if(!await this.isValidEnv($))return null;return{envDir:O$.resolve($),name:O$.basename($),configPath:O$.join($,S$),sourcePath:O$.join($,i0),toolsDir:O$.join($,u6)}}async isValidEnv($){let I=O$.join($,i0),M=O$.join($,S$),[G,J]=await Promise.all([this.fs.exists(I),this.fs.exists(M)]);return G&&J}async detectEnv($,I){let M=this.logger.getSubLogger({name:"detectEnv"}),G=I??fM,J=O$.resolve($,G);if(await this.isValidEnv(J))return M.debug(f$.envDetected(J)),{found:!0,envDir:J,envName:G,configPath:O$.join(J,S$)};return{found:!1}}getActiveEnv(){let $=this.env[Q$],I=this.env[wI];if($&&I)return{active:!0,envDir:$,envName:I};return{active:!1}}}import n1 from"path";import*as i1 from"readline";async function K8($){let I=i1.createInterface({input:process.stdin,output:process.stdout});return new Promise((M)=>{I.question(`Delete environment at '${$}'? [y/N] `,(G)=>{I.close(),M(G.toLowerCase()==="y"||G.toLowerCase()==="yes")})})}async function _8($,I,M){let G=new z$,J=new l0($,G),Q=process.cwd(),Y=await J.create({name:I,parentDir:Q,force:!1});if(!Y.success){$.error(_.envOperationFailed("create",Y.error)),y(1);return}let X=n1.join(Y.envDir,S$);$.info(_.envCreated(Y.envDir)),$.info(_.envActivationHint(I)),$.info(_.envConfigPath(X))}async function O8($,I,M){let G=new z$,J=new l0($,G),Q=process.cwd(),Y=n1.resolve(Q,I);if(!await J.isValidEnv(Y)){$.error(_.envNotFound(Y)),y(1);return}if(!M.force){if(!await K8(Y)){$.info(_.envDeletionCancelled());return}}let X=await J.delete(Y);if(!X.success){$.error(_.envOperationFailed("delete",X.error)),y(1);return}$.info(_.envDeleted(X.envDir))}function l1($,I){let M=$.getSubLogger({name:"registerEnvCommand"}),G=I.command("env").description("Manage virtual environments for isolated dotfiles configurations.");G.command("create [name]").description("Create a new virtual environment").action(async(J)=>{let Q=J??fM,Y=I.opts();await _8(M,Q,Y)}),G.command("delete [name]").description("Delete a virtual environment").option("--force","Skip confirmation prompt",!1).action(async(J,Q)=>{let Y=J??fM,X={...Q,...I.opts()};await O8(M,Y,X)})}var a1={name:"features",description:"Manage features and generate artifacts",subcommands:[{name:"catalog",description:"Generate catalog of available features"}]};async function j8($,I,M){try{let{projectConfig:G,fs:J,configService:Q,readmeService:Y,systemInfo:X}=M,R=await Q.loadToolConfigs($,G.paths.toolConfigsDir,J,G,X);await Y.generateCatalogFromConfigs(G.features.catalog.filePath,R)}catch(G){$.error(_.commandExecutionFailed("features catalog",1),G),y(1)}}function r1($,I,M){let G=$.getSubLogger({name:"registerFeaturesCommand"});I.command("features").description("Manage features and generate feature-specific artifacts.").command("catalog").description("Catalog of available features documentation").action(async()=>{let Q=I.opts(),Y=await M();await j8(G,Q,Y),G.info(_.commandCompleted(Boolean(Q.dryRun)))})}var s1={name:"files",description:"Show generated files structure",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool"};async function t1($,I,M){let G=[];try{let J=await I.readdir(M);for(let Q of J){let Y=`${M}/${Q}`,R=(await I.stat(Y)).isDirectory(),W={name:Q,isDirectory:R};if(R)W.children=await t1($,I,Y);G.push(W)}}catch(J){$.error(_.commandExecutionFailed("files",E.ERROR),J)}return G.toSorted((J,Q)=>{if(J.isDirectory===Q.isDirectory)return J.name.localeCompare(Q.name);return J.isDirectory?-1:1})}function o1($,I=""){let M=[];for(let G=0;G<$.length;G++){let J=$[G];if(!J)continue;let Q=G===$.length-1,Y=Q?"\u2514\u2500 ":"\u251C\u2500 ",X=J.name;if(M.push(`${I}${Y}${X}`),J.isDirectory&&J.children&&J.children.length>0){let R=I+(Q?" ":"\u2502 "),W=o1(J.children,R);M.push(W)}}return M.join(`
361
+ `)}async function V8($,I,M,G,J){let Q=await M.getToolInstallation(G);if(!Q)return $.error(_.toolNotInstalled(G)),E.ERROR;let Y=Q.installPath;if(!await I.exists(Y))return $.error(_.installPathNotFound(Y)),E.ERROR;J(Y);let R=await t1($,I,Y);if(R.length===0)return J("(empty directory)"),E.SUCCESS;let W=o1(R);return J(W),E.SUCCESS}async function z8($,I,M,G,J){let{fs:Q,projectConfig:Y,configService:X,toolInstallationRegistry:R,systemInfo:W}=G;try{if(!await X.loadSingleToolConfig($,I,Y.paths.toolConfigsDir,Q,Y,W)){$.error(_.toolNotFound(I,Y.paths.toolConfigsDir)),y(E.ERROR);return}let U=await V8($,Q,R,I,J);if(U!==E.SUCCESS)y(U)}catch(q){$.error(_.commandExecutionFailed("files",E.ERROR),q),y(E.ERROR)}}function e1($,I,M,G=console.log){let J=$.getSubLogger({name:"registerFilesCommand"});I.command("files <toolName>").description("Display a tree view of files in the tool installation directory").action(async(Q,Y)=>{let X={...Y,...I.opts()},R=await M();await z8(J,Q,X,R,G)})}import p6 from"path";var $Y={name:"generate",description:"Generate shims, shell init files, and symlinks",options:[{flag:"--overwrite",description:"Overwrite conflicting files not created by generator"}]};import _M from"path";var JY={name:"install",description:"Install a tool by name or binary",hasPositionalArg:!0,positionalArgDescription:"tool name or binary name to install",positionalArgType:"tool",options:[{flag:"--force",description:"Force installation even if already installed"},{flag:"--shim-mode",description:"Optimized output for shim usage"}]};function B8($){return typeof $==="object"&&$!==null&&"error"in $}async function x8($,I,M,G,J,Q,Y){let X=await Q.loadSingleToolConfig($,I,M,G,J,Y);if(X)return{success:!0,toolConfig:X,toolName:I};$.debug(_.toolLookupByBinaryStarted(I));let R=await Q.loadToolConfigByBinary($,I,M,G,J,Y);if(B8(R))return{success:!1,error:R.error};if(R)return $.debug(_.toolFoundByBinary(I,R.name)),{success:!0,toolConfig:R,toolName:R.name};return{success:!1,error:`No tool or binary named "${I}" found in ${M}`}}async function QY($,I,M=!1){if(M)try{return await $.lstat(I),!0}catch{return!1}return $.exists(I)}function D8($,I){return GM($.binaries).map((M)=>_M.join(I.paths.targetDir,M))}async function A8($,I,M,G){let J=[],Q=D8($,I);for(let Y of Q){let X=await QY(M,Y,!0);if(G){if(X)J.push(`stale shim at ${Y}`);continue}if(!X)J.push(`missing shim at ${Y}`)}return J}async function F8($,I,M,G){let J=[];if(!$.symlinks||$.symlinks.length===0)return J;for(let Q of $.symlinks){let Y=w$($.configFilePath,Q.source,I,M),X=w$($.configFilePath,Q.target,I,M);try{if(!(await G.lstat(X)).isSymbolicLink()){J.push(`expected symlink at ${X}`);continue}let W=await G.readlink(X);if(_M.resolve(_M.dirname(X),W)!==Y)J.push(`symlink target mismatch at ${X}`)}catch{J.push(`missing symlink at ${X}`)}}return J}async function L8($,I,M,G){let J=[];if(!$.copies||$.copies.length===0)return J;for(let Q of $.copies){let Y=w$($.configFilePath,Q.target,I,M);if(!await QY(G,Y))J.push(`missing copy at ${Y}`)}return J}async function IY($,I){let M=I$($,I.systemInfo),J=I.pluginRegistry.getExternallyManagedMethods().has(M.installationMethod),Q=await A8(M,I.projectConfig,I.fs,J),Y=await F8(M,I.projectConfig,I.systemInfo,I.fs),X=await L8(M,I.projectConfig,I.systemInfo,I.fs),R=[...Q,...Y,...X];return{hasIssues:R.length>0,issues:R}}function MY($){for(let I of $)if(!I.success)return I.error??"Operation failed";return null}async function GY($,I,M,G,J={}){let Q=await IY(M,G),Y=I$(M,G.systemInfo);if(G.pluginRegistry.getExternallyManagedMethods().has(Y.installationMethod))await S8(Y,G.projectConfig.paths.targetDir,G.fs,$);else await G.shimGenerator.generateForTool(I,M,{overwrite:!1,overwriteConflicts:!1});await G.generatorOrchestrator.generateCompletionsForTool(I,M,J.version,J.binaryPaths);let W=await G.symlinkGenerator.generate({[I]:M},{overwrite:!0,backup:!0}),q=MY(W);if(q)throw Error(q);let U=await G.copyGenerator.generate({[I]:M},{overwrite:!0,backup:!0}),H=MY(U);if(H)throw Error(H);let K=await IY(M,G);if(K.hasIssues)throw Error(`Failed to reconcile artifacts for "${I}": ${K.issues.join(", ")}`);return Q.hasIssues}function E8($,I,M,G,J){if(I.success)if(G)return 0;else{let Q=I.installationMethod??"unknown",Y=I.version??"unknown";if(Q==="already-installed")if(J)$.info(_.toolArtifactsRepaired(M));else $.info(_.toolAlreadyInstalled(M,Y));else $.info(_.toolInstalled(M,Y,Q));return null}else return 1}function T8($,I,M,G){if(G)process.stderr.write(`Failed to install '${M}': ${I.message}
362
+ `);else $.error(_.commandExecutionFailed("install",1),I);return 1}async function S8($,I,M,G){if(!$.binaries||$.binaries.length===0)return;for(let J of $.binaries){let Q=typeof J==="string"?J:J.name,Y=_M.join(I,Q);try{await M.lstat(Y),await M.rm(Y,{force:!0}),G.debug(_.shimDeleted(Q,Y))}catch{}}}function k8($){let I=$.installationMethod==="manual",M=!$.installParams||Object.keys($.installParams).length===0,G=!$.binaries||$.binaries.length===0;return I&&M&&G}function w8($){if($ instanceof Error)return $;return Error(typeof $==="string"?$:"Unknown error")}async function b8($,I,M,G){let{projectConfig:J,fs:Q,installer:Y,configService:X,systemInfo:R}=G;$.debug(_.commandActionStarted("install",I),J.paths.toolConfigsDir,Q.constructor.name);let W=await x8($,I,J.paths.toolConfigsDir,Q,J,X,R);if(!W.success)return $.error(_.toolNotFoundByBinary(I,J.paths.toolConfigsDir)),1;let{toolConfig:q,toolName:U}=W,H=I$(q,R);if(k8(H)){let j=await GY($,U,q,G);if(!M.shimMode){if($.info(_.toolInstallSkippedConfigurationOnly(U)),j)$.info(_.toolArtifactsRepaired(U))}return M.shimMode?0:null}let K=await Y.install(U,q,{force:M.force,verbose:M.verbose,shimMode:M.shimMode}),O=!1;if(K.success){let j="binaryPaths"in K?K.binaryPaths:void 0;O=await GY($,U,q,G,{version:K.version,binaryPaths:j})}return E8($,K,U,M.shimMode,O)}function YY($,I,M){let G=$.getSubLogger({name:"registerInstallCommand"});I.command("install <nameOrBinary>").description("Installs a tool by name or binary. Accepts tool name (filename without .tool.ts) or binary name (from .bin()).").option("--force","Force installation even if the tool is already installed",!1).option("--shim-mode","Optimized output for shim usage: shows progress bars but suppresses log messages",!1).action(async(J,Q)=>{let Y={...Q,...I.opts()},X=await M(),R=null;try{R=await b8(G,J,Y,X)}catch(W){let q=w8(W);R=T8(G,q,J,Y.shimMode)}if(R!==null)y(R)})}var XY={name:"log",description:"Show file operation history",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool",options:[{flag:"--type",description:"Filter by file type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--status",description:"Show current file states"},{flag:"--since",description:"Show operations since date",hasArg:!0,argPlaceholder:"<date>"}]};function N8($){switch($){case"shim":case"binary":case"symlink":case"copy":case"config":case"completion":case"init":case"hook-generated":case"catalog":return!0;default:return!1}}function y8($,I){let M=I.getSubLogger({name:"buildOperationsFilter"}),{tool:G,type:J,since:Q}=$,Y={};if(G)Y.toolName=G;if(J){if(!N8(J))return M.error(_.configParameterInvalid("file type for --type",J,"shim, binary, symlink, copy, config, completion, init, hook-generated, or catalog")),{filter:{},exitCode:E.ERROR};Y.fileType=J}if(Q){let X=new Date(Q);if(Number.isNaN(X.getTime()))return M.error(_.configParameterInvalid("date format for --since",Q,'ISO format like "2025-08-01"')),{filter:{},exitCode:E.ERROR};Y.createdAfter=X.getTime()}return{filter:Y,exitCode:E.SUCCESS}}async function v8($,I,M,G){let J=$.getSubLogger({name:"showFileStates"}),Q=await I.getRegisteredTools();J.info(_.logCheckingFileStates());for(let Y of Q){if(G&&Y!==G)continue;let X=await I.getFileStatesForTool(Y);if(X.length===0)continue;J.info(_.logFileStatesForTool(Y));for(let R of X)await P8(J,M,R)}}async function P8($,I,M){let G=$.getSubLogger({name:"logFileState"}),J=await I.exists(M.filePath),Q=J?"\u2713":"\u2717",Y=J?"exists":"MISSING",X=M.sizeBytes?` (${M.sizeBytes} bytes)`:"";if(G.info(_.logFileStatus(Q,M.filePath,M.fileType,Y,X)),M.targetPath){let W=await I.exists(M.targetPath)?"\u2192":"\u2717";G.info(_.logTargetStatus(W,M.targetPath))}}function C8($){let I=[];if($.sizeBytes&&$.operationType==="writeFile")I.push(`size: ${$.sizeBytes}`);if($.metadata&&Object.keys($.metadata).length>0)for(let[M,G]of Object.entries($.metadata)){if(M==="newMode"&&(typeof G==="string"||typeof G==="number")){I.push(`${M}: ${jM(G)}`);continue}I.push(`${M}: ${G}`)}return I.length>0?`(${I.join(", ")})`:""}function d8($){return new Date($).toLocaleString("en-US",{hour12:!1,year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).replace(",","")}function u8($,I,M,G,J,Q){let Y=$.getSubLogger({name:"logOperationByType"});switch(I.operationType){case"writeFile":{let X=`[${I.toolName}] write ${G}`;Y.info(_.logOperationHistory(M,X,J));break}case"mkdir":{let X=`[${I.toolName}] mkdir ${G}`;Y.info(_.logOperationHistory(M,X,J));break}case"chmod":{let X=jM(I.permissions||0),R=`[${I.toolName}] chmod ${X} ${G}`;Y.info(_.logOperationHistory(M,R,J));break}case"rm":{let X=`[${I.toolName}] rm ${G}`;Y.info(_.logOperationHistory(M,X,J));break}case"rename":{let X=I.targetPath?r(Q.paths.homeDir,I.targetPath):G,R=`[${I.toolName}] mv ${X} ${G}`;Y.info(_.logOperationHistory(M,R,J));break}case"cp":{let X=I.targetPath?r(Q.paths.homeDir,I.targetPath):G,R=`[${I.toolName}] cp ${X} ${G}`;Y.info(_.logOperationHistory(M,R,J));break}case"symlink":{let X=I.targetPath?r(Q.paths.homeDir,I.targetPath):G,R=`[${I.toolName}] ln -s ${X} ${G}`;Y.info(_.logOperationHistory(M,R,J));break}default:{let X=`[${I.toolName}] write ${G}`;Y.info(_.logOperationHistory(M,X,J))}}}function f8($){let I={};for(let M of $){if(!I[M.toolName])I[M.toolName]=[];I[M.toolName]?.push(M)}return I}async function p8($,I,M){let G=$.getSubLogger({name:"showOperations"});if(I.length===0){G.info(_.logNoOperationsFound());return}let J=f8(I);for(let[,Q]of Object.entries(J))for(let Y of Q){let X=d8(Y.createdAt),R=C8(Y),W=r(M.paths.homeDir,Y.filePath);u8(G,Y,X,W,R,M)}}async function c8($,I,M){let G=$.getSubLogger({name:"logActionLogic"}),{fileRegistry:J,fs:Q,projectConfig:Y}=M;try{if(I.status){await v8(G,J,Q,I.tool);return}let X=y8(I,G);if(X.exitCode!==E.SUCCESS){y(X.exitCode);return}let R=await J.getOperations(X.filter);await p8(G,R,Y)}catch(X){G.error(_.commandExecutionFailed("log",E.ERROR),X),y(E.ERROR)}}function ZY($,I,M){let G=$.getSubLogger({name:"registerLogCommand"});I.command("log [tool]").description("Inspect tracked files in the registry").option("--type <type>","Show files of specific type only (shim, binary, symlink, etc.)").option("--status","Check file status (missing, broken links, etc.)").option("--since <date>","Show files created since date (ISO format: 2025-08-01)").action(async(J,Q)=>{let Y={...Q,tool:J,...I.opts()},X=await M();await c8(G,Y,X)})}import{cp as h8}from"fs/promises";import a0 from"path";var RY={name:"skill",description:"Copy the dotfiles skill folder to the target directory",hasPositionalArg:!0,positionalArgDescription:"target directory for skill folder"};function m8(){let $=tI(),I=$.split(" ").pop()??$,M=a0.dirname(I);return a0.join(M,"skill")}async function g8($,I,M){let G=$.getSubLogger({name:"copySkill"}),J=new z$,Q=m8(),Y=a0.join(I,"dotfiles");if(!await J.exists(Q))return G.error(_.fsItemNotFound("Skill directory",Q)),E.ERROR;if(!await J.exists(I))return G.error(_.fsItemNotFound("Target directory",I)),E.ERROR;if(await J.exists(Y))G.info(_.skillAlreadyExists(Y)),await J.rmdir(Y,{recursive:!0});if(M)return G.info(_.skillDryRun(Y,Q)),E.SUCCESS;try{return await h8(Q,Y,{recursive:!0}),G.info(_.skillCopied(Y,Q)),E.SUCCESS}catch(q){return G.error(_.skillCopyFailed(Y),q),E.ERROR}}async function n8($,I){let M=$.getSubLogger({name:"skillActionLogic"}),{targetPath:G,dryRun:J}=I;M.debug(_.commandActionStarted("skill"));let Q=await g8(M,G,J);y(Q)}function WY($,I,M){let G=$.getSubLogger({name:"registerSkillCommand"});I.command("skill <path>").description("Copy the dotfiles skill folder to the target directory").action(async(J)=>{let Q={targetPath:a0.resolve(J),...I.opts()};await n8(G,Q)})}var qY={name:"update",description:"Update an installed tool to latest version",hasPositionalArg:!0,positionalArgDescription:"tool name to update",positionalArgType:"tool",options:[{flag:"--shim-mode",description:"Optimized output for shim usage"}]};async function i8($,I,M,G,J,Q,Y){try{let X=await I.loadSingleToolConfig($,M,G,J,Q,Y);if(!X)return $.error(_.toolNotFound(M,G)),{toolConfig:null,exitCode:E.ERROR};return{toolConfig:X,exitCode:E.SUCCESS}}catch(X){return $.error(_.configLoadFailed(`tool "${M}"`),X),{toolConfig:null,exitCode:E.ERROR}}}async function l8($,I,M,G,J){let{toolInstallationRegistry:Q,installer:Y,pluginRegistry:X}=I;if(G.version!=="latest"){$.info(_.toolVersionPinned(M,G.version));return}let R=X.get(G.installationMethod);if(R&&!R.supportsUpdate())$.warn(_.toolUpdateNotSupported(M,G.installationMethod));let q=(await Q.getToolInstallation(M))?.version||"unknown",U=await Y.install(M,G,{force:!0,shimMode:J});if(!U.success){$.error(_.toolUpdateFailed(M,U.error)),y(E.ERROR);return}let H="version"in U&&typeof U.version==="string"?U.version:"unknown",K=q===H;if(J)if(K)$.info(_.toolShimUpToDate(M,H));else $.info(_.toolShimUpdateStarting(M,q,H)),$.info(_.toolShimUpdateSuccess(M,H));else $.info(_.toolUpdated(M,q,H))}function UY($,I,M){let G=$.getSubLogger({name:"registerUpdateCommand"});I.command("update <toolName>").description("Updates a specified tool to its latest version.").option("--shim-mode","Run in shim mode with minimal output",!1).action(async(J,Q)=>{let Y={...Q,...I.opts()},X=await M(),{projectConfig:R,fs:W,configService:q,systemInfo:U}=X;try{let H=await i8(G,q,J,R.paths.toolConfigsDir,W,R,U);if(H.exitCode!==E.SUCCESS){y(H.exitCode);return}if(!H.toolConfig){G.error(_.toolNotFound(J,R.paths.toolConfigsDir)),y(E.ERROR);return}let K=H.toolConfig;if(!Y.shimMode)G.info(_.commandCheckingUpdatesFor(J));await l8(G,X,J,K,Y.shimMode)}catch(H){G.error(_.commandExecutionFailed("update",E.ERROR),H),y(E.ERROR)}})}var a8=[Q1,JY,$Y,W1,Z1,qY,f1,XY,s1,RY,a1];function f6($){let I=$.flag,M=$.description.replace(/'/g,"\\'");if($.hasArg)return`'${I}=[${M}]:${$.argPlaceholder||"arg"}:'`;return`'${I}[${M}]'`}function r8($){let I=[];for(let M of $)I.push(f6(M));return I.push("'1:command:->command'"),I.push("'*::arg:->args'"),I.join(" \\\n")}function s8($){return $.replace(/'/g,"\\'")}function t8($){return $.map((I)=>s8(I)).join(" ")}function o8($,I,M){if(I==="tool"&&M.length>0){let G=t8(M);return`'1:${$}:(${G})'`}return`'1:${$}:'`}function e8(){return"_describe 'command' commands"}function $3($){if($.length===0)return;let I=$.length-1,M=$[I];if(M?.endsWith(" \\"))$[I]=M.slice(0,-2)}function I3($,I){let M=[];if($.options)for(let G of $.options)M.push(f6(G));for(let G of I)M.push(f6(G));return M}function M3($){let I=[];I.push("'1:subcommand:->subcommand'");let M=$.map((G)=>`'${G.name}:${G.description.replace(/'/g,"\\'")}'`).join(" ");return I.push("case $state in"),I.push(" subcommand)"),I.push(` local -a subcommands=(${M})`),I.push(" _describe 'subcommand' subcommands"),I.push(" ;;"),I.push("esac"),I}function G3($,I,M){let G=[];G.push(`${$.name})`);let J=I3($,I);if(J.length>0||$.hasPositionalArg||$.subcommands){G.push(" _arguments \\");for(let Y of J)G.push(` ${Y} \\`);if($.subcommands&&$.subcommands.length>0){let Y=M3($.subcommands);for(let X of Y)G.push(` ${X}`)}else if($.hasPositionalArg){let Y=$.positionalArgDescription||"argument",X=o8(Y,$.positionalArgType,M);G.push(` ${X}`)}else $3(G)}return G.push(" ;;"),G.join(`
363
+ `)}function J3($,I,M){return $.map((J)=>G3(J,I,M)).join(`
364
+ `)}function HY($,I){let M=a8,G=K1.options||[],J=[...I].toSorted((X,R)=>X.localeCompare(R)),Q=M.map((X)=>`'${X.name}:${X.description.replace(/'/g,"\\'")}'`).join(`
365
+ `);return e0(`
366
366
  #compdef {binaryName}
367
367
  # Generated by Dotfiles Management Tool
368
368
  # Do not edit this file manually - it will be overwritten
@@ -391,7 +391,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
391
391
  }
392
392
 
393
393
  _{binaryName} "$@"
394
- `,{binaryName:$,commandDescriptions:G,globalArgs:f3(Q),commandsCase:m3(),argsCases:a3(J,Q,Y)})}var Z7="dotfiles";async function s3($,M,J){let Q=$.getSubLogger({name:"generateCliCompletions"}),{projectConfig:Y,fs:G}=M,X=X7(Z7,J),Z=u6.join(Y.paths.shellScriptsDir,"zsh","completions"),q=u6.join(Z,`_${Z7}`);await G.ensureDir(Z),await G.writeFile(q,X),Q.debug(R.cliCompletionGenerated(q))}function W7($,M,J){let Q=$.getSubLogger({name:"registerGenerateCommand"});M.command("generate").description("Generates shims, shell init files, and symlinks based on tool configurations.").option("--overwrite","Overwrite conflicting files that were not created by the generator").action(async(Y)=>{let G={...Y,...M.opts()},X=await J(),{projectConfig:Z,fs:q,generatorOrchestrator:I,configService:U,systemInfo:K,installer:H}=X;try{Q.debug(R.toolConfigsLoading(Z.paths.toolConfigsDir),q.constructor.name);let _=await U.loadToolConfigs(Q,Z.paths.toolConfigsDir,q,Z,K);Q.debug(R.toolConfigsLoaded(Z.paths.toolConfigsDir,Object.keys(_).length));let O=u6.join(Z.paths.generatedDir,"tool-types.d.ts");await l6(_,O,q),Q.debug(R.toolTypesGenerated(O)),await I.generateAll(_,{overwrite:G.overwrite,installer:H});let B=Object.keys(_).toSorted((j,V)=>j.localeCompare(V));await s3(Q,X,B),Q.info(R.commandCompleted(Boolean(G.dryRun)))}catch(_){Q.error(R.commandExecutionFailed("generate",1)),N(1)}})}import{Database as r3}from"bun:sqlite";import{mkdirSync as t3}from"fs";import o3 from"path";var f6={initialized:()=>W("Initialized SQLite file registry at: %s"),sqlitePragmaConfigFailed:()=>W("Failed to configure SQLite pragmas; continuing with defaults")};class p6{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"RegistryDatabase"});let J=o3.dirname(M);t3(J,{recursive:!0}),this.db=new r3(M),this.configureConnectionPragmas(),this.logger.debug(f6.initialized(),"shared connection")}configureConnectionPragmas(){try{this.db.run("PRAGMA busy_timeout = 5000;"),this.db.run("PRAGMA journal_mode = WAL;"),this.db.run("PRAGMA synchronous = NORMAL;")}catch($){this.logger.warn(f6.sqlitePragmaConfigFailed(),$)}}getConnection(){return this.db}close(){this.db.close()}}var g$={databaseInitialized:()=>W("Database initialized"),toolInstallationRecorded:()=>W("Tool installation recorded: %s version %s"),toolInstallationNotFound:()=>W("Tool installation not found: %s"),toolInstallationsRetrieved:()=>W("Retrieved %d tool installations"),noUpdatesProvided:()=>W("No updates provided for tool: %s"),toolInstallationUpdated:()=>W("Tool installation updated: %s"),toolInstallationRemoved:()=>W("Tool installation removed: %s"),toolInstallationCheckCompleted:()=>W("Tool installation check: %s version %s - installed: %s"),databaseClosed:()=>W("Database closed")};class c6{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"ToolInstallationRegistry"}),this.db=M,this.initializeDatabase()}initializeDatabase(){let $=this.logger.getSubLogger({name:"initializeDatabase"});this.db.run(`
394
+ `,{binaryName:$,commandDescriptions:Q,globalArgs:r8(G),commandsCase:e8(),argsCases:J3(M,G,J)})}var KY="dotfiles";async function Q3($,I,M){let G=$.getSubLogger({name:"generateCliCompletions"}),{projectConfig:J,fs:Q}=I,Y=HY(KY,M),X=p6.join(J.paths.shellScriptsDir,"zsh","completions"),R=p6.join(X,`_${KY}`);await Q.ensureDir(X),await Q.writeFile(R,Y),G.debug(_.cliCompletionGenerated(R))}function _Y($,I,M){let G=$.getSubLogger({name:"registerGenerateCommand"});I.command("generate").description("Generates shims, shell init files, and symlinks based on tool configurations.").option("--overwrite","Overwrite conflicting files that were not created by the generator").action(async(J)=>{let Q={...J,...I.opts()},Y=await M(),{projectConfig:X,fs:R,generatorOrchestrator:W,configService:q,systemInfo:U,installer:H}=Y;try{G.debug(_.toolConfigsLoading(X.paths.toolConfigsDir),R.constructor.name);let K=await q.loadToolConfigs(G,X.paths.toolConfigsDir,R,X,U);G.debug(_.toolConfigsLoaded(X.paths.toolConfigsDir,Object.keys(K).length));let O=p6.join(X.paths.generatedDir,"tool-types.d.ts");await r6(K,O,R),G.debug(_.toolTypesGenerated(O)),await W.generateAll(K,{overwrite:Q.overwrite,installer:H});let B=Object.keys(K).toSorted((j,V)=>j.localeCompare(V));await Q3(G,Y,B),G.info(_.commandCompleted(Boolean(Q.dryRun)))}catch(K){G.error(_.commandExecutionFailed("generate",1)),y(1)}})}import{Database as Y3}from"bun:sqlite";import{mkdirSync as X3}from"fs";import Z3 from"path";var c6={initialized:()=>Z("Initialized SQLite file registry at: %s"),sqlitePragmaConfigFailed:()=>Z("Failed to configure SQLite pragmas; continuing with defaults")};class h6{db;logger;constructor($,I){this.logger=$.getSubLogger({name:"RegistryDatabase"});let M=Z3.dirname(I);X3(M,{recursive:!0}),this.db=new Y3(I),this.configureConnectionPragmas(),this.logger.debug(c6.initialized(),"shared connection")}configureConnectionPragmas(){try{this.db.run("PRAGMA busy_timeout = 5000;"),this.db.run("PRAGMA journal_mode = WAL;"),this.db.run("PRAGMA synchronous = NORMAL;")}catch($){this.logger.warn(c6.sqlitePragmaConfigFailed(),$)}}getConnection(){return this.db}close(){this.db.close()}}var l$={databaseInitialized:()=>Z("Database initialized"),toolInstallationRecorded:()=>Z("Tool installation recorded: %s version %s"),toolInstallationNotFound:()=>Z("Tool installation not found: %s"),toolInstallationsRetrieved:()=>Z("Retrieved %d tool installations"),noUpdatesProvided:()=>Z("No updates provided for tool: %s"),toolInstallationUpdated:()=>Z("Tool installation updated: %s"),toolInstallationRemoved:()=>Z("Tool installation removed: %s"),toolInstallationCheckCompleted:()=>Z("Tool installation check: %s version %s - installed: %s"),databaseClosed:()=>Z("Database closed")};class m6{db;logger;constructor($,I){this.logger=$.getSubLogger({name:"ToolInstallationRegistry"}),this.db=I,this.initializeDatabase()}initializeDatabase(){let $=this.logger.getSubLogger({name:"initializeDatabase"});this.db.run(`
395
395
  CREATE TABLE IF NOT EXISTS tool_installations (
396
396
  id INTEGER PRIMARY KEY AUTOINCREMENT,
397
397
  tool_name TEXT NOT NULL UNIQUE,
@@ -417,33 +417,33 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
417
417
  );
418
418
  `),this.db.run(`
419
419
  CREATE INDEX IF NOT EXISTS idx_tool_usage_tool_name ON tool_usage(tool_name);
420
- `),$.debug(g$.databaseInitialized())}migrateAddInstallMethod(){try{if(!this.db.prepare("PRAGMA table_info(tool_installations)").all().some((J)=>J.name==="install_method"))this.db.run("ALTER TABLE tool_installations ADD COLUMN install_method TEXT")}catch{}}async recordToolInstallation($){let M=this.logger.getSubLogger({name:"recordToolInstallation"});this.db.prepare(`
420
+ `),$.debug(l$.databaseInitialized())}migrateAddInstallMethod(){try{if(!this.db.prepare("PRAGMA table_info(tool_installations)").all().some((M)=>M.name==="install_method"))this.db.run("ALTER TABLE tool_installations ADD COLUMN install_method TEXT")}catch{}}async recordToolInstallation($){let I=this.logger.getSubLogger({name:"recordToolInstallation"});this.db.prepare(`
421
421
  INSERT OR REPLACE INTO tool_installations
422
422
  (tool_name, version, install_path, timestamp, installed_at, binary_paths, download_url, asset_name, configured_version, original_tag, install_method)
423
423
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
424
- `).run($.toolName,$.version,$.installPath,$.timestamp,Date.now(),JSON.stringify($.binaryPaths),$.downloadUrl||null,$.assetName||null,$.configuredVersion||null,$.originalTag||null,$.installMethod||null),M.debug(g$.toolInstallationRecorded(),$.toolName,$.version)}async getToolInstallation($){let M=this.logger.getSubLogger({name:"getToolInstallation"}),Q=this.db.prepare(`
424
+ `).run($.toolName,$.version,$.installPath,$.timestamp,Date.now(),JSON.stringify($.binaryPaths),$.downloadUrl||null,$.assetName||null,$.configuredVersion||null,$.originalTag||null,$.installMethod||null),I.debug(l$.toolInstallationRecorded(),$.toolName,$.version)}async getToolInstallation($){let I=this.logger.getSubLogger({name:"getToolInstallation"}),G=this.db.prepare(`
425
425
  SELECT * FROM tool_installations WHERE tool_name = ?
426
- `).get($);if(!Q)return M.debug(g$.toolInstallationNotFound(),$),null;return{id:Q.id,toolName:Q.tool_name,version:Q.version,installPath:Q.install_path,timestamp:Q.timestamp,installedAt:new Date(Q.installed_at),binaryPaths:JSON.parse(Q.binary_paths),downloadUrl:Q.download_url||void 0,assetName:Q.asset_name||void 0,configuredVersion:Q.configured_version||void 0,originalTag:Q.original_tag||void 0,installMethod:Q.install_method||void 0}}async getAllToolInstallations(){let $=this.logger.getSubLogger({name:"getAllToolInstallations"}),J=this.db.prepare(`
426
+ `).get($);if(!G)return I.debug(l$.toolInstallationNotFound(),$),null;return{id:G.id,toolName:G.tool_name,version:G.version,installPath:G.install_path,timestamp:G.timestamp,installedAt:new Date(G.installed_at),binaryPaths:JSON.parse(G.binary_paths),downloadUrl:G.download_url||void 0,assetName:G.asset_name||void 0,configuredVersion:G.configured_version||void 0,originalTag:G.original_tag||void 0,installMethod:G.install_method||void 0}}async getAllToolInstallations(){let $=this.logger.getSubLogger({name:"getAllToolInstallations"}),M=this.db.prepare(`
427
427
  SELECT * FROM tool_installations ORDER BY tool_name
428
- `).all();return $.debug(g$.toolInstallationsRetrieved(),J.length),J.map((Q)=>({id:Q.id,toolName:Q.tool_name,version:Q.version,installPath:Q.install_path,timestamp:Q.timestamp,installedAt:new Date(Q.installed_at),binaryPaths:JSON.parse(Q.binary_paths),downloadUrl:Q.download_url||void 0,assetName:Q.asset_name||void 0,configuredVersion:Q.configured_version||void 0,originalTag:Q.original_tag||void 0,installMethod:Q.install_method||void 0}))}async updateToolInstallation($,M){let J=this.logger.getSubLogger({name:"updateToolInstallation"}),Q=[],Y=[];if(M.version!==void 0)Q.push("version = ?"),Y.push(M.version);if(M.installPath!==void 0)Q.push("install_path = ?"),Y.push(M.installPath);if(M.timestamp!==void 0)Q.push("timestamp = ?"),Y.push(M.timestamp);if(M.binaryPaths!==void 0)Q.push("binary_paths = ?"),Y.push(JSON.stringify(M.binaryPaths));if(M.downloadUrl!==void 0)Q.push("download_url = ?"),Y.push(M.downloadUrl);if(M.assetName!==void 0)Q.push("asset_name = ?"),Y.push(M.assetName);if(M.configuredVersion!==void 0)Q.push("configured_version = ?"),Y.push(M.configuredVersion);if(M.originalTag!==void 0)Q.push("original_tag = ?"),Y.push(M.originalTag);if(Q.length===0){J.debug(g$.noUpdatesProvided(),$);return}Y.push($),this.db.prepare(`
429
- UPDATE tool_installations SET ${Q.join(", ")} WHERE tool_name = ?
430
- `).run(...Y),J.debug(g$.toolInstallationUpdated(),$)}async removeToolInstallation($){let M=this.logger.getSubLogger({name:"removeToolInstallation"});this.db.prepare(`
428
+ `).all();return $.debug(l$.toolInstallationsRetrieved(),M.length),M.map((G)=>({id:G.id,toolName:G.tool_name,version:G.version,installPath:G.install_path,timestamp:G.timestamp,installedAt:new Date(G.installed_at),binaryPaths:JSON.parse(G.binary_paths),downloadUrl:G.download_url||void 0,assetName:G.asset_name||void 0,configuredVersion:G.configured_version||void 0,originalTag:G.original_tag||void 0,installMethod:G.install_method||void 0}))}async updateToolInstallation($,I){let M=this.logger.getSubLogger({name:"updateToolInstallation"}),G=[],J=[];if(I.version!==void 0)G.push("version = ?"),J.push(I.version);if(I.installPath!==void 0)G.push("install_path = ?"),J.push(I.installPath);if(I.timestamp!==void 0)G.push("timestamp = ?"),J.push(I.timestamp);if(I.binaryPaths!==void 0)G.push("binary_paths = ?"),J.push(JSON.stringify(I.binaryPaths));if(I.downloadUrl!==void 0)G.push("download_url = ?"),J.push(I.downloadUrl);if(I.assetName!==void 0)G.push("asset_name = ?"),J.push(I.assetName);if(I.configuredVersion!==void 0)G.push("configured_version = ?"),J.push(I.configuredVersion);if(I.originalTag!==void 0)G.push("original_tag = ?"),J.push(I.originalTag);if(G.length===0){M.debug(l$.noUpdatesProvided(),$);return}J.push($),this.db.prepare(`
429
+ UPDATE tool_installations SET ${G.join(", ")} WHERE tool_name = ?
430
+ `).run(...J),M.debug(l$.toolInstallationUpdated(),$)}async removeToolInstallation($){let I=this.logger.getSubLogger({name:"removeToolInstallation"});this.db.prepare(`
431
431
  DELETE FROM tool_installations WHERE tool_name = ?
432
- `).run($),M.debug(g$.toolInstallationRemoved(),$)}async isToolInstalled($,M){let J=this.logger.getSubLogger({name:"isToolInstalled"});if(M){let G=this.db.prepare(`
432
+ `).run($),I.debug(l$.toolInstallationRemoved(),$)}async isToolInstalled($,I){let M=this.logger.getSubLogger({name:"isToolInstalled"});if(I){let Q=this.db.prepare(`
433
433
  SELECT 1 FROM tool_installations WHERE tool_name = ? AND version = ?
434
- `).get($,M)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,M,G),G}else{let G=this.db.prepare(`
434
+ `).get($,I)!==null;return M.debug(l$.toolInstallationCheckCompleted(),$,I,Q),Q}else{let Q=this.db.prepare(`
435
435
  SELECT 1 FROM tool_installations WHERE tool_name = ?
436
- `).get($)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,"any",G),G}}async recordToolUsage($,M){let J=Date.now();this.db.prepare(`
436
+ `).get($)!==null;return M.debug(l$.toolInstallationCheckCompleted(),$,"any",Q),Q}}async recordToolUsage($,I){let M=Date.now();this.db.prepare(`
437
437
  INSERT INTO tool_usage (tool_name, binary_name, usage_count, last_used_at)
438
438
  VALUES (?, ?, 1, ?)
439
439
  ON CONFLICT(tool_name, binary_name)
440
440
  DO UPDATE SET
441
441
  usage_count = usage_count + 1,
442
442
  last_used_at = excluded.last_used_at
443
- `).run($,M,J)}async getToolUsage($,M){let Q=this.db.prepare(`
443
+ `).run($,I,M)}async getToolUsage($,I){let G=this.db.prepare(`
444
444
  SELECT tool_name, binary_name, usage_count, last_used_at
445
445
  FROM tool_usage
446
446
  WHERE tool_name = ? AND binary_name = ?
447
- `).get($,M);if(!Q)return null;return{toolName:Q.tool_name,binaryName:Q.binary_name,usageCount:Q.usage_count,lastUsedAt:new Date(Q.last_used_at)}}async close(){let $=this.logger.getSubLogger({name:"close"});this.db.close(),$.debug(g$.databaseClosed())}}import I7 from"os";import M5 from"path";import C0 from"path";var e3=["dotfiles.config.ts"],$5=["project.json",".git"];async function q7($,M,J){let Q=$.getSubLogger({name:"resolveConfigPath"}),{cwd:Y,homeDir:G}=J,X=new z$;if(M.length>0){let I=M.startsWith("~")?M.replace(/^~(?=$|\/|\\)/,G):M,U=C0.resolve(Y,I);return Q.debug(R.configPathResolved(U)),U}let Z=process.env[G$];if(Z){let I=C0.join(Z,HM);if(await X.exists(I))return Q.debug(R.envConfigFromEnvVar(I)),I}let q=Y;while(!0){for(let U of e3){let K=C0.join(q,U);if(await X.exists(K))return Q.debug(R.configPathResolved(K)),K}if(q===G)break;for(let U of $5)if(await X.exists(C0.join(q,U)))return;let I=C0.dirname(q);if(I===q)break;q=I}return}function J5($,M){let J=M.platform||process.platform,Q=M.arch||process.arch;if(M.warnOnPlatformArchOverride){if(M.platform)$.warn(R.configParameterOverridden("platform",M.platform));if(M.arch)$.warn(R.configParameterOverridden("arch",M.arch))}return{platform:$Y(J),arch:MY(Q),homeDir:I7.homedir(),hostname:I7.hostname()}}async function aJ($,M){let J=$.getSubLogger({name:"createBaseRuntimeContext"}),Q=J5($,M),Y=await q7(J,M.config,{cwd:M.cwd,homeDir:Q.homeDir});if(!Y)return null;let G=M.configFileSystem??M.fileSystem,X=await g9(J,G,Y,Q,M.env),Z={...Q,homeDir:X.paths.homeDir},q=M5.join(X.paths.generatedDir,"registry.db"),I=new p6($,q),U=I.getConnection(),K=$.getSubLogger({context:"system"}),H=new zQ(K,U),_=new c6(K,U);return{projectConfig:X,systemInfo:Z,registryPath:q,registryDatabase:I,fileRegistry:H,toolInstallationRegistry:_}}async function U7($,M){let J=new z$,Q=await aJ($,{config:M.config,cwd:M.cwd,env:M.env,platform:M.platform,arch:M.arch,fileSystem:J});if(!Q)return null;return{projectConfig:Q.projectConfig,systemInfo:Q.systemInfo,toolInstallationRegistry:Q.toolInstallationRegistry,close:()=>{Q.registryDatabase.close()}}}function Q5($){let M=$.indexOf("@track-usage");if(M<0)return null;let J=[],Q="",Y,G;for(let q=2;q<$.length;q+=1){let I=$[q];if(!I)continue;if(I==="@track-usage")continue;if(I==="--config"||I==="--platform"||I==="--arch"){let U=$[q+1];if(!U)continue;if(I==="--config")Q=U;if(I==="--platform")Y=U;if(I==="--arch")G=U;q+=1;continue}if(q>M&&!I.startsWith("-"))J.push(I)}let X=J[0],Z=J[1];if(!X||!Z)return null;return{toolName:X,binaryName:Z,config:Q,platform:Y,arch:G}}async function K7($){let M=Q5($);if(!M)return;let J={getSubLogger:()=>J,trace:()=>{return},debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return},fatal:()=>{return},setPrefix:()=>J},Q=await U7(J,{config:M.config,cwd:process.cwd(),env:process.env,platform:M.platform,arch:M.arch});if(!Q)return;try{await Q.toolInstallationRegistry.recordToolUsage(M.toolName,M.binaryName)}finally{Q.close()}}import H7 from"path";async function _7($,M){let J=$.getSubLogger({name:"populateMemFsForDryRun"}),{sourceFs:Q,targetFs:Y,toolConfigsDir:G,homeDir:X}=M;if(J.trace(R.toolConfigsForDryRun()),!await Q.exists(G)){J.warn(R.fsItemNotFound("Tool configs directory",G));return}let Z=await R7(J,Q,G);J.trace(R.toolConfigsLoaded(G,Z.length));for(let q of Z)await Y5(J,Q,Y,q,X)}async function R7($,M,J){let Q=[];try{let Y=await M.readdir(J);for(let G of Y){let X=H7.join(J,G);try{if((await M.stat(X)).isDirectory()){let q=await R7($,M,X);Q.push(...q)}else Q.push(X)}catch(Z){$.debug(R.fsReadFailed(X),Z)}}}catch(Y){$.debug(R.fsReadFailed(J),Y)}return Q}async function Y5($,M,J,Q,Y){try{let G=await M.readFile(Q,"utf8");await J.ensureDir(H7.dirname(Q)),await J.writeFile(Q,G),$.trace(R.fsWrite("memfs",s(Y,Q)))}catch(G){$.error(R.fsReadFailed(Q),G)}}function O7($){return async(M,J)=>{let Q=$(M,J);if(Q instanceof Promise)return Q;return Q}}async function X5($,M=2000){return new Promise((J)=>{let Q=new G5.Socket,Y=()=>{Q.removeAllListeners(),Q.destroy()};Q.setTimeout(M),Q.on("connect",()=>{Y(),J(!0)}),Q.on("timeout",()=>{Y(),J(!1)}),Q.on("error",()=>{Y(),J(!1)}),Q.connect($,"localhost")})}function Z5($){if(typeof $>"u")return{port:void 0,invalidValue:void 0};let M=$.trim();if(!/^\d+$/.test(M))return{port:void 0,invalidValue:$};let Q=Number.parseInt(M,10);if(!(Q>=1&&Q<=65535))return{port:void 0,invalidValue:$};return{port:Q,invalidValue:void 0}}function W5($,M){let J;if(M)$.trace(R.dryRunEnabled()),J=new $J({});else J=new z$;return $.trace(R.componentInitialized("filesystem"),J.constructor.name),J}function q5($,M,J){if(!J.downloader.cache.enabled){$.info(R.cachingDisabled());return}let Q=K0.join(J.paths.generatedDir,"cache","downloads");return new MM($,M,{enabled:!0,defaultTtl:J.downloader.cache.ttl,cacheDir:Q,storageStrategy:"binary"})}function I5($,M,J,Q){let Y=new f($,M,J,f.createContext("system","shim"),Q),G=new f($,M,J,f.createContext("system","init"),Q),X=new f($,M,J,f.createContext("system","symlink"),Q),Z=new f($,M,J,f.createContext("system","copy"),Q),q=new f($,M,J,f.createContext("system","binary"),Q),I=new f($,M,J,f.createContext("system","catalog"),Q),U=new f($,M,J,f.createContext("system","completion"),Q);return{shimTrackedFs:Y,shellInitTrackedFs:G,symlinkTrackedFs:X,copyTrackedFs:Z,installerTrackedFs:q,catalogTrackedFs:I,completionTrackedFs:U}}async function U5($,M){let J=$.getSubLogger({name:"setupServices"}),{dryRun:Q,env:Y,config:G}=M,X=W5(J,Q),Z=!process.env.BUN_TEST,q=Q&&Z?new z$:X,I=await aJ(J,{config:G,cwd:M.cwd,env:Y,platform:M.platform,arch:M.arch,fileSystem:X,configFileSystem:q,warnOnPlatformArchOverride:!0});if(!I)J.error(R.configNotFound()),process.exit(1);let{projectConfig:U,systemInfo:K,registryPath:H,fileRegistry:_,toolInstallationRegistry:O}=I,B=Y.DEV_PROXY,j=Z5(B),V=j.port;if(typeof j.invalidValue==="string")J.error(R.configParameterInvalid("DEV_PROXY",j.invalidValue,"an integer between 1 and 65535")),process.exit(1);if(typeof V==="number"){if(J.debug(R.proxyCheckingAvailability(V)),!await X5(V))J.error(R.proxyUnavailable(V)),process.exit(1);J.warn(R.proxyEnabled(V))}let D=new MJ(X,U.paths.homeDir);if(Q){let u0=new z$;await _7(J,{sourceFs:u0,targetFs:D,toolConfigsDir:U.paths.toolConfigsDir,homeDir:K.homeDir})}let A=q5($,D,U);$.debug(R.registryInitialized(H));let S=new EQ($,D,void 0,A,typeof V==="number"?{enabled:!0,port:V}:void 0),w=W$(),u=new MM($,D,{enabled:U.github.cache.enabled,defaultTtl:U.github.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","github-api"),storageStrategy:"json"}),i=new RJ($,U,S,u),E=new _J($,U,w,u),g=new MM($,D,{enabled:U.github.cache.enabled,defaultTtl:U.github.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","gitea-api"),storageStrategy:"json"}),$$=new MM($,D,{enabled:U.cargo.cratesIo.cache.enabled,defaultTtl:U.cargo.cratesIo.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","cargo","crates-io"),storageStrategy:"json"}),m=new MM($,D,{enabled:U.cargo.githubRaw.cache.enabled,defaultTtl:U.cargo.githubRaw.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","cargo","github-raw"),storageStrategy:"json"}),o=new vQ($,U,S,$$,m),{shimTrackedFs:y,shellInitTrackedFs:I$,symlinkTrackedFs:r$,copyTrackedFs:d0,installerTrackedFs:T$,catalogTrackedFs:sJ,completionTrackedFs:h6}=I5($,D,_,U),kM=$.getSubLogger({context:"system"}),m6=new I6(kM,I$,U),rJ=new w6(kM,r$,U,K),g6=new S6(kM,d0,U,K),j7=new F0(kM,w),SM=new tQ($,D,w),_M=new LQ((u0)=>{process.stdout.write(u0)}),X$=new UQ($);X$.register(new cQ(T$,S,i,E,SM,U,_M)),X$.register(new iQ(T$,S,SM,_M,g)),X$.register(new NQ(w)),X$.register(new yQ(T$,S,o,SM,_M,U.cargo.githubRelease.host)),X$.register(new PQ(T$,S,_M,w)),X$.register(new CQ(T$,S,SM,_M,w)),X$.register(new D6(T$,S,_M,w)),X$.register(new hQ(T$,S,SM,_M,w,i,E)),X$.register(new aQ(T$)),X$.register(new A6(w)),X$.register(new L6(T$,w));let V7=X$.getExternallyManagedMethods(),z7=X$.getMissingBinaryMessagesByMethod(),n6=new T6(kM,y,U,K,V7,z7,O),tJ=new eQ(kM,h6,w,j7,{downloader:S,archiveExtractor:SM}),B7=new B6(kM,n6,m6,rJ,g6,tJ,K,U,_,D,h6),D7=new bQ(J,T$,D,U,O,K,X$,rJ,w,_M,tJ),A7=new b6(J,i),E7=new _6,F7=new V6(J,S,O,D,sJ,K0.join(U.paths.generatedDir,"cache","readme"),X$);return{projectConfig:U,fs:D,configService:E7,readmeService:F7,fileRegistry:_,toolInstallationRegistry:O,downloadCache:A,downloader:S,githubApiCache:u,cargoCratesIoCache:$$,cargoGithubRawCache:m,githubApiClient:i,cargoClient:o,shimGenerator:n6,shellInitGenerator:m6,symlinkGenerator:rJ,copyGenerator:g6,completionGenerator:tJ,generatorOrchestrator:B7,installer:D7,archiveExtractor:SM,versionChecker:A7,pluginRegistry:X$,systemInfo:K}}function K5($,M,J){let Q=$.getSubLogger({name:"registerAllCommands"});YG(Q,M,J),eG(Q,M,J),W7(Q,M,J),iG(Q,M,J),UG(Q,M,J),ZG(Q,M,J),G7(Q,M,J),dG(Q,M,J),M7(Q,M,J),rG(Q,M,J),Q7(Q,M,J),PG(Q,M,J),gG(Q,M)}function H5($,M){return $.includes(M)}var _5=new Set(["--config","--log","--platform","--arch"]);function R5($){for(let M=2;M<$.length;M+=1){let J=$[M];if(!J)continue;if(_5.has(J)){M+=1;continue}if(J.startsWith("-"))continue;return J}return}function O5($,M){let J=H5($,"--shim-mode"),Q=M.quiet||J;return KY(M.log,Q,M.verbose)}async function j5($){let M=HG();M.parseOptions($);let J=M.opts(),Q=O5($,J),G=qQ({name:"cli",level:Q,trace:J.trace}).getSubLogger({name:"main"});G.trace(R.cliStarted(),$),K5(G,M,async()=>{return await U5(G,{...J,cwd:process.cwd(),env:process.env})}),await M.parseAsync($)}async function V5($){if(R5($)==="@track-usage"){await K7($);return}await j5($)}V5(process.argv).catch(($)=>{qQ({name:"cli"}).fatal(R.commandExecutionFailed("main",1),$),process.exit(1)});export{U5 as setupServices,V5 as runCliEntrypoint,O5 as resolveLogLevel,K5 as registerAllCommands,j5 as main,O7 as defineTool,w1 as defineConfig,oJ as dedentTemplate,c as dedentString,E$ as Platform,OM as Architecture};
447
+ `).get($,I);if(!G)return null;return{toolName:G.tool_name,binaryName:G.binary_name,usageCount:G.usage_count,lastUsedAt:new Date(G.last_used_at)}}async close(){let $=this.logger.getSubLogger({name:"close"});this.db.close(),$.debug(l$.databaseClosed())}}import jY from"os";import q3 from"path";import pM from"path";var R3=["dotfiles.config.ts"],W3=["project.json",".git"];async function OY($,I,M){let G=$.getSubLogger({name:"resolveConfigPath"}),{cwd:J,homeDir:Q}=M,Y=new z$;if(I.length>0){let W=I.startsWith("~")?I.replace(/^~(?=$|\/|\\)/,Q):I,q=pM.resolve(J,W);return G.debug(_.configPathResolved(q)),q}let X=process.env[Q$];if(X){let W=pM.join(X,S$);if(await Y.exists(W))return G.debug(_.envConfigFromEnvVar(W)),W}let R=J;while(!0){for(let q of R3){let U=pM.join(R,q);if(await Y.exists(U))return G.debug(_.configPathResolved(U)),U}if(R===Q)break;for(let q of W3)if(await Y.exists(pM.join(R,q)))return;let W=pM.dirname(R);if(W===R)break;R=W}return}function U3($,I){let M=I.platform||process.platform,G=I.arch||process.arch;if(I.warnOnPlatformArchOverride){if(I.platform)$.warn(_.configParameterOverridden("platform",I.platform));if(I.arch)$.warn(_.configParameterOverridden("arch",I.arch))}return{platform:MJ(M),arch:GJ(G),homeDir:jY.homedir(),hostname:jY.hostname()}}async function r0($,I){let M=$.getSubLogger({name:"createBaseRuntimeContext"}),G=U3($,I),J=await OY(M,I.config,{cwd:I.cwd,homeDir:G.homeDir});if(!J)return null;let Q=I.configFileSystem??I.fileSystem,Y=await iQ(M,Q,J,G,I.env),X={...G,homeDir:Y.paths.homeDir},R=q3.join(Y.paths.generatedDir,"registry.db"),W=new h6($,R),q=W.getConnection(),U=$.getSubLogger({context:"system"}),H=new BG(U,q),K=new m6(U,q);return{projectConfig:Y,systemInfo:X,registryPath:R,registryDatabase:W,fileRegistry:H,toolInstallationRegistry:K}}async function VY($,I){let M=new z$,G=await r0($,{config:I.config,cwd:I.cwd,env:I.env,platform:I.platform,arch:I.arch,fileSystem:M});if(!G)return null;return{projectConfig:G.projectConfig,systemInfo:G.systemInfo,toolInstallationRegistry:G.toolInstallationRegistry,close:()=>{G.registryDatabase.close()}}}function H3($){let I=$.indexOf("@track-usage");if(I<0)return null;let M=[],G="",J,Q;for(let R=2;R<$.length;R+=1){let W=$[R];if(!W)continue;if(W==="@track-usage")continue;if(W==="--config"||W==="--platform"||W==="--arch"){let q=$[R+1];if(!q)continue;if(W==="--config")G=q;if(W==="--platform")J=q;if(W==="--arch")Q=q;R+=1;continue}if(R>I&&!W.startsWith("-"))M.push(W)}let Y=M[0],X=M[1];if(!Y||!X)return null;return{toolName:Y,binaryName:X,config:G,platform:J,arch:Q}}async function zY($){let I=H3($);if(!I)return;let M={getSubLogger:()=>M,trace:()=>{return},debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return},fatal:()=>{return},setPrefix:()=>M},G=await VY(M,{config:I.config,cwd:process.cwd(),env:process.env,platform:I.platform,arch:I.arch});if(!G)return;try{await G.toolInstallationRegistry.recordToolUsage(I.toolName,I.binaryName)}finally{G.close()}}import BY from"path";async function xY($,I){let M=$.getSubLogger({name:"populateMemFsForDryRun"}),{sourceFs:G,targetFs:J,toolConfigsDir:Q,homeDir:Y}=I;if(M.trace(_.toolConfigsForDryRun()),!await G.exists(Q)){M.warn(_.fsItemNotFound("Tool configs directory",Q));return}let X=await DY(M,G,Q);M.trace(_.toolConfigsLoaded(Q,X.length));for(let R of X)await K3(M,G,J,R,Y)}async function DY($,I,M){let G=[];try{let J=await I.readdir(M);for(let Q of J){let Y=BY.join(M,Q);try{if((await I.stat(Y)).isDirectory()){let R=await DY($,I,Y);G.push(...R)}else G.push(Y)}catch(X){$.debug(_.fsReadFailed(Y),X)}}}catch(J){$.debug(_.fsReadFailed(M),J)}return G}async function K3($,I,M,G,J){try{let Q=await I.readFile(G,"utf8");await M.ensureDir(BY.dirname(G)),await M.writeFile(G,Q),$.trace(_.fsWrite("memfs",r(J,G)))}catch(Q){$.error(_.fsReadFailed(G),Q)}}function AY($){return async(I,M)=>{let G=$(I,M);if(G instanceof Promise)return await G;return G}}async function O3($,I=2000){return new Promise((M)=>{let G=new _3.Socket,J=()=>{G.removeAllListeners(),G.destroy()};G.setTimeout(I),G.on("connect",()=>{J(),M(!0)}),G.on("timeout",()=>{J(),M(!1)}),G.on("error",()=>{J(),M(!1)}),G.connect($,"localhost")})}function j3($){if(typeof $>"u")return{port:void 0,invalidValue:void 0};let I=$.trim();if(!/^\d+$/.test(I))return{port:void 0,invalidValue:$};let G=Number.parseInt(I,10);if(!(G>=1&&G<=65535))return{port:void 0,invalidValue:$};return{port:G,invalidValue:void 0}}function V3($,I){let M;if(I)$.trace(_.dryRunEnabled()),M=new J0({});else M=new z$;return $.trace(_.componentInitialized("filesystem"),M.constructor.name),M}function z3($,I,M){if(!M.downloader.cache.enabled){$.info(_.cachingDisabled());return}let G=OM.join(M.paths.generatedDir,"cache","downloads");return new JI($,I,{enabled:!0,defaultTtl:M.downloader.cache.ttl,cacheDir:G,storageStrategy:"binary"})}function B3($,I,M,G){let J=new f($,I,M,f.createContext("system","shim"),G),Q=new f($,I,M,f.createContext("system","init"),G),Y=new f($,I,M,f.createContext("system","symlink"),G),X=new f($,I,M,f.createContext("system","copy"),G),R=new f($,I,M,f.createContext("system","binary"),G),W=new f($,I,M,f.createContext("system","catalog"),G),q=new f($,I,M,f.createContext("system","completion"),G);return{shimTrackedFs:J,shellInitTrackedFs:Q,symlinkTrackedFs:Y,copyTrackedFs:X,installerTrackedFs:R,catalogTrackedFs:W,completionTrackedFs:q}}async function x3($,I){let M=$.getSubLogger({name:"setupServices"}),{dryRun:G,env:J,config:Q}=I,Y=V3(M,G),X=!process.env.BUN_TEST,R=G&&X?new z$:Y,W=await r0(M,{config:Q,cwd:I.cwd,env:J,platform:I.platform,arch:I.arch,fileSystem:Y,configFileSystem:R,warnOnPlatformArchOverride:!0});if(!W)M.error(_.configNotFound()),process.exit(1);let{projectConfig:q,systemInfo:U,registryPath:H,fileRegistry:K,toolInstallationRegistry:O}=W,B=J.DEV_PROXY,j=j3(B),V=j.port;if(typeof j.invalidValue==="string")M.error(_.configParameterInvalid("DEV_PROXY",j.invalidValue,"an integer between 1 and 65535")),process.exit(1);if(typeof V==="number"){if(M.debug(_.proxyCheckingAvailability(V)),!await O3(V))M.error(_.proxyUnavailable(V)),process.exit(1);M.warn(_.proxyEnabled(V))}let x=new Q0(Y,q.paths.homeDir);if(G){let hM=new z$;await xY(M,{sourceFs:hM,targetFs:x,toolConfigsDir:q.paths.toolConfigsDir,homeDir:U.homeDir})}let A=z3($,x,q);$.debug(_.registryInitialized(H));let k=new FG($,x,void 0,A,typeof V==="number"?{enabled:!0,port:V}:void 0),w=Z$(),u=new JI($,x,{enabled:q.github.cache.enabled,defaultTtl:q.github.cache.ttl,cacheDir:OM.join(q.paths.generatedDir,"cache","github-api"),storageStrategy:"json"}),h=new j0($,q,k,u),D=new O0($,q,w,u),m=new JI($,x,{enabled:q.github.cache.enabled,defaultTtl:q.github.cache.ttl,cacheDir:OM.join(q.paths.generatedDir,"cache","gitea-api"),storageStrategy:"json"}),e=new JI($,x,{enabled:q.cargo.cratesIo.cache.enabled,defaultTtl:q.cargo.cratesIo.cache.ttl,cacheDir:OM.join(q.paths.generatedDir,"cache","cargo","crates-io"),storageStrategy:"json"}),a=new JI($,x,{enabled:q.cargo.githubRaw.cache.enabled,defaultTtl:q.cargo.githubRaw.cache.ttl,cacheDir:OM.join(q.paths.generatedDir,"cache","cargo","github-raw"),storageStrategy:"json"}),$$=new vG($,q,k,e,a),{shimTrackedFs:N,shellInitTrackedFs:W$,symlinkTrackedFs:e$,copyTrackedFs:cM,installerTrackedFs:k$,catalogTrackedFs:s0,completionTrackedFs:g6}=B3($,x,K,q),bI=$.getSubLogger({context:"system"}),n6=new q6(bI,W$,q),t0=new b6(bI,e$,q,U),i6=new w6(bI,cM,q,U),FY=new SM(bI,w),NI=new oG($,x,w),_I=new EG((hM)=>{process.stdout.write(hM)}),Y$=new UG($);Y$.register(new hG(k$,k,h,D,NI,q,_I)),Y$.register(new lG(k$,k,NI,_I,m)),Y$.register(new yG(w)),Y$.register(new PG(k$,k,$$,NI,_I,q.cargo.githubRelease.host)),Y$.register(new CG(k$,k,_I,w)),Y$.register(new dG(k$,k,NI,_I,w)),Y$.register(new D6(k$,k,_I,w)),Y$.register(new mG(k$,k,NI,_I,w,h,D)),Y$.register(new rG(k$)),Y$.register(new A6(w)),Y$.register(new E6(k$,w));let LY=Y$.getExternallyManagedMethods(),EY=Y$.getMissingBinaryMessagesByMethod(),l6=new S6(bI,N,q,U,LY,EY,O),o0=new $6(bI,g6,w,FY,{downloader:k,archiveExtractor:NI}),TY=new x6(bI,l6,n6,t0,i6,o0,U,q,K,x,g6),SY=new NG(M,k$,x,q,O,U,Y$,t0,w,_I,o0),kY=new N6(M,h),wY=new _6,bY=new z6(M,k,O,x,s0,OM.join(q.paths.generatedDir,"cache","readme"),Y$);return{projectConfig:q,fs:x,configService:wY,readmeService:bY,fileRegistry:K,toolInstallationRegistry:O,downloadCache:A,downloader:k,githubApiCache:u,cargoCratesIoCache:e,cargoGithubRawCache:a,githubApiClient:h,cargoClient:$$,shimGenerator:l6,shellInitGenerator:n6,symlinkGenerator:t0,copyGenerator:i6,completionGenerator:o0,generatorOrchestrator:TY,installer:SY,archiveExtractor:NI,versionChecker:kY,pluginRegistry:Y$,systemInfo:U}}function D3($,I,M){let G=$.getSubLogger({name:"registerAllCommands"});Y1(G,I,M),YY(G,I,M),_Y(G,I,M),r1(G,I,M),H1(G,I,M),R1(G,I,M),UY(G,I,M),p1(G,I,M),ZY(G,I,M),e1(G,I,M),WY(G,I,M),u1(G,I,M),l1(G,I)}function A3($,I){return $.includes(I)}var F3=new Set(["--config","--log","--platform","--arch"]);function L3($){for(let I=2;I<$.length;I+=1){let M=$[I];if(!M)continue;if(F3.has(M)){I+=1;continue}if(M.startsWith("-"))continue;return M}return}function E3($,I){let M=A3($,"--shim-mode"),G=I.quiet||M;return KJ(I.log,G,I.verbose)}async function T3($){let I=_1();I.parseOptions($);let M=I.opts(),G=E3($,M),Q=WG({name:"cli",level:G,trace:M.trace}).getSubLogger({name:"main"});Q.trace(_.cliStarted(),$),D3(Q,I,async()=>{return await x3(Q,{...M,cwd:process.cwd(),env:process.env})}),await I.parseAsync($)}async function S3($){if(L3($)==="@track-usage"){await zY($);return}await T3($)}S3(process.argv).catch(($)=>{WG({name:"cli"}).fatal(_.commandExecutionFailed("main",1),$),process.exit(1)});export{x3 as setupServices,S3 as runCliEntrypoint,E3 as resolveLogLevel,D3 as registerAllCommands,T3 as main,AY as defineTool,u7 as defineConfig,e0 as dedentTemplate,c as dedentString,A$ as Platform,OI as Architecture};
448
448
 
449
- //# debugId=988E990EE48F48C664756E2164756E21
449
+ //# debugId=8E34E4E18FD0B67464756E2164756E21