@alexgorbatchev/dotfiles 0.0.1 → 0.0.4
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 +5 -5
- package/cli.js.map +2 -2
- package/package.json +2 -3
package/cli.js
CHANGED
|
@@ -19,7 +19,7 @@ ${Z}
|
|
|
19
19
|
}`;return[k7,I,"export {};",""].join(`
|
|
20
20
|
|
|
21
21
|
`)}async function iG($,M,J,Q){let G=b7($,Q);await J.ensureDir(T7.dirname(M)),await J.writeFile(M,G,"utf8")}import lG from"path";async function SM($,M,J){let Q=[],G=J!==void 0,Y=J??M,X=await $.readdir(M);for(let Z of X){let q=lG.join(M,Z);if((await $.stat(q)).isDirectory()){let U=await SM($,q,G?Y:void 0);Q.push(...U)}else{let U=G?lG.relative(Y,q):q;Q.push(U)}}return Q}function aM(){if(typeof CLI_BIN_PATH>"u")return process.argv.slice(0,2).join(" ");return CLI_BIN_PATH}async function aG($,M,J){let Q=$ instanceof Request?$.url:$.toString(),G=J?.enabled?`http://localhost:${J.port}/${Q}`:Q;if($ instanceof Request)return fetch(G,{method:$.method,headers:$.headers,body:$.body,mode:$.mode,credentials:$.credentials,cache:$.cache,redirect:$.redirect,referrer:$.referrer,integrity:$.integrity,...M});return fetch(G,M)}async function wM($,M){if(typeof M==="function")return await M($);return M}async function c0($,M,J,Q,G){let Y=G?.mode??"file",X=v7(J),Z=await $.readFile(M,"utf8"),q=Y==="line"?await N7(Z,X,Q):await sG(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 sG($,M,J){let Q=Array.from($.matchAll(M)),G=$,Y=0;for(let X of Q){let Z=X[0]??"",q=X.index??0,I=X.slice(1),U=X.groups,H=await wM({substring:Z,captures:I,offset:q,input:$,groups:U},J),_=q+Y,O=_+Z.length;G=G.slice(0,_)+H+G.slice(O),Y+=H.length-Z.length}return G}async function N7($,M,J){let Q=$.split(/(\r\n|\n)/),G="";for(let Y=0;Y<Q.length;Y+=2){let X=Q[Y]??"",Z=Q[Y+1]??"",q=await sG(X,M,J);G+=q+Z}return G}import{z as rG}from"zod";var A$;((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"})(A$||={});var RM;((G)=>{G[G.None=0]="None";G[G.X86_64=1]="X86_64";G[G.Arm64=2]="Arm64";G[G.All=3]="All"})(RM||={});var tG=rG.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`)."}),oG=rG.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 sM($,M){if(M===0)return $===0;return($&M)===M}function rM($,M){if(M===0)return $===0;return($&M)===M}function eG($){switch($){case"darwin":return 2;case"linux":return 1;case"win32":return 4;default:return 0}}function $6($){switch($){case"x64":return 1;case"arm64":return 2;default:return 0}}function t$($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";case 0:return"none";default:return"unknown"}}function o$($){switch($){case 1:return"x86_64";case 2:return"arm64";case 0:return"none";default:return"unknown"}}import{z as F}from"zod";function y7($){let M=$?.enabled??!0,J=$?.ttl??86400000;return F.object({enabled:F.boolean().default(M),ttl:F.number().default(J)}).strict()}var h0=y7();function n0($){let{defaultHost:M,includeToken:J,includeUserAgent:Q,defaultUserAgent:G="dotfiles-generator",tokenDefault:Y=""}=$;return F.object({host:F.string().default(M),cache:h0.default(h0.parse({})),token:F.string().default(J?Y:""),userAgent:F.string().default(Q?G:"dotfiles-generator")}).strict()}var oJ=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(),eJ=F.object({sudoPrompt:F.string().default("Please enter your password to continue:")}).strict(),$Q=F.object({debug:F.string().default("")}).strict(),MQ=F.object({checkOnRun:F.boolean().default(!0),checkInterval:F.number().default(86400)}).strict(),JQ=n0({defaultHost:"https://api.github.com",includeToken:!0,includeUserAgent:!0}),M6=n0({defaultHost:"https://crates.io"}),J6=n0({defaultHost:"https://raw.githubusercontent.com"}),Q6=n0({defaultHost:"https://github.com"}),QQ=F.object({cratesIo:M6.default(M6.parse({})),githubRaw:J6.default(J6.parse({})),githubRelease:Q6.default(Q6.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(),YQ=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"],P7=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()]),C7=F.object({paths:oJ.required().default(oJ.parse({})),system:eJ.required().default(eJ.parse({})),logging:$Q.required().default($Q.parse({})),updates:MQ.required().default(MQ.parse({})),github:JQ.required().default(JQ.parse({})),cargo:QQ.required().default(QQ.parse({})),downloader:GQ.required().default(GQ.parse({})),features:YQ.default(YQ.parse({}))}).strict(),d7=F.object({paths:oJ.partial().optional(),system:eJ.partial().optional(),logging:$Q.partial().optional(),updates:MQ.partial().optional(),github:JQ.partial().optional(),cargo:QQ.partial().optional(),downloader:GQ.partial().optional(),features:YQ.partial().optional()}).strict(),u7=F.object({match:F.array(P7).nonempty(),get config(){return d7.partial()}}).strict(),XQ=C7.extend({platform:F.array(u7).optional()}).strict(),G6=F.object({configFilePath:F.string(),configFileDir:F.string()});var{Glob:n7}=globalThis.Bun;import jM from"path";function W($){return $}var OM={VERBOSE:1,DEFAULT:3,QUIET:5},ZQ=["verbose","default","quiet"],Y6={verbose:OM.VERBOSE,default:OM.DEFAULT,quiet:OM.QUIET};function X6($){let M=$.toLowerCase();if(!(M in Y6))throw Error(`Invalid log level: ${$}. Valid levels are: ${ZQ.join(", ")}`);return Y6[M]}import{Logger as g7}from"tslog";var f7=/\.tool\.(ts|js)/,p7=/([^/\\]+\.tool\.(?:ts|js)):(\d+)/;function c7($){return f7.test($)}function h7($){let M=p7.exec($);if(!M)return null;return`${M[1]}:${M[2]}`}function m7($){if(!$)return[];let M=$.split(`
|
|
22
|
-
`),J=[];for(let Q of M)if(c7(Q)){let G=h7(Q);if(G)J.push(G)}return J}function Z6($){let M=typeof $.stack==="string"?$.stack:void 0,J=m7(M);if(J.length===0)return null;return`(${J.join(", ")})`}function W6($){return $ instanceof Error}function q6($){let M=[],J=[...$.issues].toSorted((Q,G)=>(Q.path??[]).length-(G.path??[]).length);for(let Q of J)if(M.push(`\u2716 ${Q.message}`),Q.path?.length){let G=Q.path.map(String).join(".");M.push(` \u2192 at ${G}`)}return M}function I6($){return`[${$}]`}class _0 extends g7{_trace;constructor($){let J=($?.prefix??[]).map((Q)=>String(Q));if($?.context)J.push(I6($.context));super({...$,prefix:J});this._trace=$?.trace===!0}isTracingEnabled(){return this._trace}filterErrorArgs($){if(this.isTracingEnabled())return $;let M=[];for(let J of $)if(W6(J)){let Q=Z6(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=q6($);for(let J of M)this.error(J)}setPrefix($){return this.settings.prefix=[I6($)],this}}function WQ($){let M={};if(typeof $==="string")M.name=$;else M={...$};M.level=M.level??OM.DEFAULT;let J=M.trace?"{{logLevelName}}\t{{filePathWithLine}} - ":"{{logLevelName}}\t",Q=process.env.NO_COLOR==="1"
|
|
22
|
+
`),J=[];for(let Q of M)if(c7(Q)){let G=h7(Q);if(G)J.push(G)}return J}function Z6($){let M=typeof $.stack==="string"?$.stack:void 0,J=m7(M);if(J.length===0)return null;return`(${J.join(", ")})`}function W6($){return $ instanceof Error}function q6($){let M=[],J=[...$.issues].toSorted((Q,G)=>(Q.path??[]).length-(G.path??[]).length);for(let Q of J)if(M.push(`\u2716 ${Q.message}`),Q.path?.length){let G=Q.path.map(String).join(".");M.push(` \u2192 at ${G}`)}return M}function I6($){return`[${$}]`}class _0 extends g7{_trace;constructor($){let J=($?.prefix??[]).map((Q)=>String(Q));if($?.context)J.push(I6($.context));super({...$,prefix:J});this._trace=$?.trace===!0}isTracingEnabled(){return this._trace}filterErrorArgs($){if(this.isTracingEnabled())return $;let M=[];for(let J of $)if(W6(J)){let Q=Z6(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=q6($);for(let J of M)this.error(J)}setPrefix($){return this.settings.prefix=[I6($)],this}}function WQ($){let M={};if(typeof $==="string")M.name=$;else M={...$};M.level=M.level??OM.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:`
|
|
23
23
|
{{errorName}} {{errorMessage}}
|
|
24
24
|
error stack:
|
|
25
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 U6($,M,J){if(M)return OM.QUIET;if(J)return OM.VERBOSE;return X6($)}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 qQ($,M){let J=$.getSubLogger({context:M});return{trace:(G)=>{J.trace(G)},debug:(G)=>{J.debug(G)},info:(G)=>{J.info(G)},warn:(G)=>{J.warn(G)},error:(G,Y)=>{if(Y!==void 0)J.error(G,Y);else J.error(G)}}}function R0($,M,J,Q,G,Y){let X=jM.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(G,H,_,O,B);if(!j&&B?.errorMessage){let V=_ instanceof RegExp?_.source:_;Y.error(M$.replaceInFileNoMatch(V,H))}return j},I=(H)=>{let _=jM.isAbsolute(H),O,B;if(_){let A=jM.dirname(H),b=jM.basename(H);if(/[*?[\]{]/.test(A)){let S=H.split(jM.sep),u=[],i=[],E=!1;for(let m of S)if(!E&&!/[*?[\]{]/.test(m))u.push(m);else E=!0,i.push(m);O=u.join(jM.sep)||"/",B=i.join(jM.sep)}else O=A,B=b}else O=Q,B=H;let j=new n7(B),V=[];for(let A of j.scanSync({cwd:O,onlyFiles:!1}))V.push(jM.join(O,A));if(V.length===0)throw Y.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 Y.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 Y.error(M$.resolveNoMatches(H)),new i0(`No matches found for pattern: ${H}`);return D},U=qQ(Y,J);return{toolName:J,toolDir:Q,currentDir:X,projectConfig:$,systemInfo:Z,replaceInFile:q,resolve:I,log:U}}import{z as K6}from"zod";class IQ{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,...G]=M;this.composedToolConfigSchema=K6.discriminatedUnion("installationMethod",[Q,...G])}let J=$.map((Q)=>Q.paramsSchema);if(J.length===1)this.composedInstallParamsSchema=J[0];else{let[Q,G,...Y]=J;this.composedInstallParamsSchema=K6.union([Q,G,...Y])}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 G=`Plugin validation failed: ${Q.errors?.join(", ")}`;return J.error(M$.validationFailed($.method,Q.errors?.join(", ")??"Unknown error")),{success:!1,error:G}}if(Q.warnings&&Q.warnings.length>0)for(let G of Q.warnings)J.warn(M$.validationWarning($.method,G));return null}async install($,M,J,Q,G,Y){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,G,X);if(q)return q;return X.debug(M$.delegatingToPlugin(M)),await Z.install(J,Q,G,Y,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 D6}from"zod";import{z as VM}from"zod";import{z as i7}from"zod";var O0=i7.custom(($)=>typeof $==="function","Must be a function");var r=VM.object({auto:VM.boolean().optional(),env:VM.custom().optional(),hooks:VM.object({"before-install":VM.array(O0).optional(),"after-download":VM.array(O0).optional(),"after-extract":VM.array(O0).optional(),"after-install":VM.array(O0).optional()}).partial().optional()}).strict();import{z as OQ}from"zod";import{z as C$}from"zod";import{z as l7}from"zod";import{z as V$}from"zod";import{z as UQ}from"zod";var H6=UQ.object({kind:UQ.enum(["once","always"]),value:UQ.string()});var l0=V$.object({scripts:V$.array(H6).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 _6=l7.object({zsh:l0.optional(),bash:l0.optional(),powershell:l0.optional()}).strict();import{z as KQ}from"zod";var R6=KQ.object({enabled:KQ.boolean().optional(),constraint:KQ.string().optional()}).strict();import{z as HQ}from"zod";var Z$=HQ.object({name:HQ.string().min(1),pattern:HQ.string().min(1)}).strict();import{z as _Q}from"zod";var O6=_Q.object({source:_Q.string().min(1),target:_Q.string().min(1)}).strict();import{z as RQ}from"zod";var j6=RQ.object({source:RQ.string().min(1),target:RQ.string().min(1)}).strict();var a0=C$.object({binaries:C$.array(C$.union([C$.string().min(1),Z$])).optional(),dependencies:C$.array(C$.string().min(1)).optional(),disabled:C$.boolean().optional(),hostname:C$.string().optional(),version:C$.string().optional(),shellConfigs:_6.optional(),symlinks:C$.array(j6).optional(),copies:C$.array(O6).optional(),updateCheck:R6.optional()}).strict();var V6=a0.extend({name:OQ.string().min(1),version:OQ.string(),configFilePath:OQ.string().optional()}).strict();import{z as a7}from"zod";import{z as z6}from"zod";var B6=z6.object({platforms:tG,architectures:oG.optional(),config:z6.unknown()}).strict();var t=V6.extend({platformConfigs:a7.array(B6).optional()});import{z as j0}from"zod";var uZ=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(Q&&!M)return!1;if(!M&&!J)return!1;return!0},{message:"Invalid completion config: use 'source' alone, 'cmd' alone, or 'url' with 'source'. Cannot combine 'cmd' with 'url' or 'source'. Cannot use 'url' alone."});var MW=a0.extend({installationMethod:D6.string().optional(),installParams:D6.unknown().optional()}).strict();var tM=Symbol("loggingShellBrand");function E6($,M){let J=(Q,...G)=>{let Y=Q[0]||"";for(let X=0;X<G.length;X++){let Z=G[X];if(Array.isArray(Z))Y+=Z.map((q)=>A6(String(q))).join(" ");else Y+=A6(String(Z));Y+=Q[X+1]||""}return M.info(W(`$ ${Y}`)),$(Q,...G)};return Object.assign(J,$),Object.defineProperty(J,tM,{value:!0,enumerable:!1}),J}function A6($){if($===""||/[\s"'`$\\]/.test($))return`'${$.replace(/'/g,"'\\''")}'`;return $}class jQ 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+=`
|
|
@@ -56,7 +56,7 @@ ${J}`}}function W$($={}){return(J,...Q)=>{let G=typeof J==="string"?J:t7(J,Q);re
|
|
|
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
58
|
`),$.debug(l.schemaInitialized())}}var V0=Symbol("resolvedFileSystemBrand");import{Volume as o7}from"memfs";class $J{vol;constructor($){if(this.vol=new o7,$)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 e7,promises as $X}from"fs";class z${fs;constants;constructor($=$X,M=e7){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 MX}from"crypto";import z0 from"path";class f{[V0]=!0;fs;registry;logger;parentLogger;context;projectConfig;suppressLogging=!1;constructor($,M,J,Q,G){this.parentLogger=$,this.logger=$.getSubLogger({name:"TrackedFileSystem",context:Q.toolName}),this.fs=M,this.registry=J,this.context=Q,this.projectConfig=G}static createContext($,M,J){return{toolName:$,fileType:M,operationId:MX(),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($),G=!0;if(Q)try{let X=await this.fs.readFile($,J||"utf8"),Z=typeof M==="string"?M:M.toString();G=X!==Z}catch{G=!0}if(!G)return;await this.fs.writeFile($,M,J);let Y=await this.getFileStats($);if(await this.recordOperation("writeFile",$,{sizeBytes:Y?.sizeBytes,permissions:Y?.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($),G=await this.registry.getFileState(J);if(G&&G.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(` ${$}`)},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,G,Y,X){let Z=X.getSubLogger({name:"createBinaryEntrypoint"}),q=B0.join(Y,M),I=B0.join(q,Q),U=B0.join(I,J),K=B0.join(I,G);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 e$($,M){let J=(Q,...G)=>{if(typeof Q==="string")return $(Q).env(M);return $(Q,...G).env(M)};if(Object.assign(J,$),s0($))Object.defineProperty(J,tM,{value:!0,enumerable:!1});return J}function q$($,M){return $ instanceof f?$.withToolName(M):$}import QJ from"crypto";import i$ from"path";var T={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 G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, 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 $M{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(T.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(T.cachingDisabled("returning null",$)),null;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),null;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),await this.deleteEntry($,G),null;if(G.type==="json")return M.debug(T.cacheHit($,"JSON")),G.data;else{if(!this.binariesDir)throw Error(T.binaryDirectoryNotConfigured());let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.warn(T.binaryFileMissing($,Y)),await this.fileSystem.rm(J).catch(()=>{}),null;let X=await this.fileSystem.readFile(Y),Z=Buffer.isBuffer(X)?X:Buffer.from(X),q=QJ.createHash("sha256").update(Z).digest("hex"),I=G.contentHash;if(q!==I)return M.warn(T.contentHashMismatch($,I,q)),await this.deleteEntry($,G),null;return M.debug(T.cacheHit($,"binary",Z.length)),Z}}catch(J){return M.warn(T.retrievalFailed($,this.getErrorMessage(J))),null}}async set($,M,J){let Q=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){Q.debug(T.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let G=J??this.config.defaultTtl,Y=Date.now();if(this.config.storageStrategy==="json"){let X={type:"json",data:M,timestamp:Y,expiresAt:Y+G},Z=this.getMetadataFilePath($);await this.fileSystem.writeFile(Z,JSON.stringify(X,null,2),"utf8"),Q.debug(T.cacheStored($,"JSON",new Date(X.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(M))throw Error(T.binaryDataRequired());if(!this.binariesDir)throw Error(T.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:Y,expiresAt:Y+G},K=this.getMetadataFilePath($);await this.fileSystem.writeFile(K,JSON.stringify(U,null,2),"utf8"),Q.debug(T.cacheStored($,"binary",new Date(U.expiresAt).toISOString(),X.length))}}catch(G){let Y=this.getErrorMessage(G);throw Q.warn(T.storageFailed($,Y)),Error(`Failed to cache data: ${Y}`,{cause:G})}}async setDownload($,M,J,Q,G){let Y=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){Y.debug(T.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(T.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:G,timestamp:Z,expiresAt:Z+X},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(K,null,2),"utf8"),Y.debug(T.cacheStored($,"download",new Date(K.expiresAt).toISOString(),M.length))}catch(X){let Z=this.getErrorMessage(X);throw Y.warn(T.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(T.cachingDisabled("returning false",$)),!1;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),!1;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),!1;if(G.type==="binary"&&this.binariesDir){let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.debug(T.binaryFileMissing($,Y)),!1}return M.debug(T.cacheEntryExists($)),!0}catch(J){return M.warn(T.checkFailed($,this.getErrorMessage(J))),!1}}async delete($){let M=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){M.debug(T.cachingDisabled("skipping delete",$));return}try{let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J)){let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);await this.deleteEntry($,G),M.debug(T.cacheEntryRemoved($))}else M.debug(T.noEntryToDelete($))}catch(J){let Q=this.getErrorMessage(J);throw M.warn(T.deleteFailed($,Q)),Error(`Failed to delete cache entry: ${Q}`,{cause:J})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(T.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(T.cacheDirectoryMissing());return}let M=await this.fileSystem.readdir(this.metadataDir),J=0;for(let Q of M){if(!Q.endsWith(".json"))continue;let G=i$.join(this.metadataDir,Q);try{let Y=await this.fileSystem.readFile(G,"utf8"),X=JSON.parse(Y);if(this.isExpired(X)){let Z=i$.basename(Q,".json");await this.deleteEntry(Z,X),J++}}catch(Y){$.warn(T.metadataProcessingWarning(Q,this.getErrorMessage(Y))),await this.fileSystem.rm(G).catch(()=>{}),J++}}$.debug(T.expiredEntriesCleared(J))}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.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(T.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(T.cacheCleared());else $.debug(T.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.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(T.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 JX from"crypto";function k6($,M={}){let J={headers:M.headers||{}},Q={url:$,options:J};return`download:${JX.createHash("sha256").update(JSON.stringify(Q)).digest("hex")}`}import QX 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 G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, 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 ${$}`)},MM={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,G,Y)=>W(`HttpError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}`),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,G,Y,X)=>W(`RateLimitError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}, resetTimestamp=${String(X)}`),clientErrorCreated:($,M,J,Q,G)=>W(`ClientError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`),serverErrorCreated:($,M,J,Q,G)=>W(`ServerError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`)};class zQ{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,M,J,Q,G=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=M,this.cache=J,this.underlyingStrategy=Q,this.cacheTtl=G,this.name=`cached-${Q.name}`,this.logger.debug(B$.strategyWrapped(Q.name,G))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,M,J,Q,G){if($.trace(B$.cacheHit(J,"binary",M.length),{url:Q}),G.onProgress)G.onProgress(0,M.length);if(G.destinationPath){if(await this.fileSystem.ensureDir(QX.dirname(G.destinationPath)),await this.fileSystem.writeFile(G.destinationPath,M),$.trace(B$.cachedFileWritten(G.destinationPath)),G.onProgress)G.onProgress(M.length,M.length);return}if(G.onProgress)G.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,G){try{await this.cache.setDownload(J,M,this.cacheTtl,Q,this.extractContentTypeFromHeaders(G.headers)),$.trace(B$.cacheStored(J,"binary","TTL-based",M.length),{url:Q})}catch(Y){$.trace(B$.cacheStorageFailed(J),Y)}}async download($,M={}){let J=this.logger.getSubLogger({name:"download"}),Q=k6($,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 G=await this.underlyingStrategy.download($,M),Y=await this.determineBufferToCache(J,G,M);if(Y)await this.cacheResult(J,Y,Q,$,M);return G}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class BQ extends Error{url;constructor($,M,J){super(M);let Q=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=J,Q.debug(MM.errorCreated("DownloaderError",M,J))}}class I$ extends BQ{originalError;constructor($,M,J,Q){super($,M,J);let G=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=Q,G.debug(MM.networkErrorCreated(M,J,Q),Q)}}class E$ extends BQ{statusCode;statusText;responseBody;responseHeaders;constructor($,M,J,Q,G,Y,X){super($,M,J);let Z=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=Q,this.statusText=G,this.responseBody=Y,this.responseHeaders=X,Z.debug(MM.httpErrorCreated(M,J,Q,G,Y,X),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X})}}class S$ extends E${constructor($,M,J,Q){super($,"Resource not found",M,404,"Not Found",J,Q);let G=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",G.debug(MM.notFoundErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class bM extends E${constructor($,M,J,Q){super($,"Access forbidden",M,403,"Forbidden",J,Q);let G=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",G.debug(MM.forbiddenErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class zM extends E${resetTimestamp;constructor($,M,J,Q,G,Y,X,Z){super($,M,J,Q,G,Y,X);let q=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=Z,q.debug(MM.rateLimitErrorCreated(M,J,Q,G,Y,X,Z),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X,resetTimestamp:Z})}}class vM extends E${constructor($,M,J,Q,G,Y){super($,`Client error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ClientError"});this.name="ClientError",X.debug(MM.clientErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class NM extends E${constructor($,M,J,Q,G,Y){super($,`Server error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ServerError"});this.name="ServerError",X.debug(MM.serverErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class DQ{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 G=Date.parse(J);if(!Number.isNaN(G))return G}return}async setupDownloadRequest($,M,J){let Q=new AbortController,G;if(J)G=setTimeout(()=>{this.logger.debug(k$.downloadTimeout($)),Q.abort()},J);return{response:await aG($,{headers:M,signal:Q.signal},this.proxyConfig),timeoutId:G}}async handleErrorResponse($,M){let J;try{J=await $.text()}catch(Z){this.logger.debug(k$.responseBodyReadFailed(M,Z))}let Q=this.getResponseHeaders($.headers),G=$.status,Y=$.statusText;if(this.logger.debug(k$.downloadFailed(M,G,Y,J?.substring(0,100))),G===404)throw new S$(this.logger,M,J,Q);let X=this.parseRateLimitReset($.headers);if(G===403){if(X)throw new zM(this.logger,"Forbidden: Rate limit likely exceeded",M,G,Y,J,Q,X);throw new bM(this.logger,M,J,Q)}if(G===429)throw new zM(this.logger,"Too Many Requests",M,G,Y,J,Q,X);if(G>=400&&G<500)throw new vM(this.logger,M,G,Y,J,Q);if(G>=500&&G<600)throw new NM(this.logger,M,G,Y,J,Q);throw new E$(this.logger,`HTTP error ${G}`,M,G,Y,J,Q)}async processResponseStream($,M,J){let Q=$.headers.get("content-length"),G=null;if(Q){let q=parseInt(Q,10);if(!Number.isNaN(q))G=q}let Y=0;if(J)J(Y,G);let X=[],Z=$.body?.getReader();if(!Z)throw new I$(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)),Y+=I.length,J)J(Y,G)}}return Buffer.concat(X)}async handleDownloadAttempt($,M,J){let{headers:Q,timeout:G,onProgress:Y,destinationPath:X}=M;this.logger.debug(k$.downloadAttempt(J+1,$));let{response:Z,timeoutId:q}=await this.setupDownloadRequest($,Q,G);if(q)clearTimeout(q);if(!Z.ok)await this.handleErrorResponse(Z,$);let I=await this.processResponseStream(Z,$,Y);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,G){if(this.logger.debug(k$.downloadAttemptError(J+1,M,$)),J>=Q){if($ instanceof E$||$ instanceof I$)throw $;let Y=`Failed to download ${M}`;if($ instanceof Error&&$.name==="AbortError")Y=`Download timed out for ${M}`;else if($ instanceof Error)Y=$.message;throw new I$(this.logger,Y,M,$ instanceof Error?$:void 0)}}async retryDownload($,M,J,Q,G){this.logger.debug(k$.retryingDownload($,M+2,J+1,Q)),await new Promise((Y)=>setTimeout(Y,Q))}async download($,M){let{retryCount:J=0,retryDelay:Q=1000,onProgress:G}=M,Y=0;while(Y<=J)try{return await this.handleDownloadAttempt($,M,Y)}catch(X){if(this.handleDownloadError(X,$,Y,J,G),Y<J)await this.retryDownload($,Y,J,Q,G),Y++}throw this.logger.debug(k$.exhaustedRetries($)),new I$(this.logger,`Download failed for ${$} after ${J} retries.`,$)}}class AQ{strategies=[];fs;logger;constructor($,M,J,Q,G){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=M,typeof J<"u")this.strategies=J;else{let Y=new DQ(this.logger,this.fs,G),X=G?.enabled?` (proxy port ${G.port})`:"";if(Q)this.logger.debug(D0.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${X}`)),this.strategies.push(new zQ(this.logger,this.fs,Q,Y));else this.logger.debug(D0.strategyCreated("NodeFetchStrategy",X||" (no cache)")),this.strategies.push(Y)}}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 G;for(let Y of this.strategies)try{let X=await this.tryDownloadWithStrategy(Y,M,J);if(X.success)return X.buffer}catch(X){G=this.normalizeError(X)}if(G)throw G;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 Y={...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,Y)).success)return}catch(q){X=this.normalizeError(q)}if(X)throw X;throw Error(`No available download strategy succeeded for ${M}.`)}}import*as oM from"cli-progress";class EQ{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 oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.Presets.shades_classic),this.progressBar.start(M,0,{speed:"0 B/s"});else this.progressBar=new oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.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 G=Math.floor(Date.now()/100)%100;this.progressBar.update(G,{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 S6($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.CI==="true"||process.env.CI==="1")return!1;if(process.env.NO_COLOR)return!1;return!0}async function U$($,M,J,Q,G,Y){let X=S6(Y?.quiet),Z=new EQ(Q,{enabled:X});try{await G.download($,M,{destinationPath:J,onProgress:Z.createCallback()})}finally{Z.finish()}}function w6($){return $.installParams?.hooks}async function w$($,M,J,Q,G){let X=w6($)?.["after-download"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-download"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"after-download",q,Z);if(!I.success)return{success:!1,error:`afterDownload hook failed: ${I.error}`}}return{success:!0}}async function eM($,M,J,Q,G){let X=w6($)?.["after-extract"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-extract"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"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 YX($){if(!GX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function b6($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function v6($){if(YX($)){let M=b6($.stderr);if(M.length>0)return M;let J=b6($.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 GJ($){return l$($).map((J)=>J.name)}import{join as XX}from"path";function e($,M){return l$($).map((Q)=>XX(M,Q.name))}import u6 from"path";import{codeFrameColumns as ZX}from"@babel/code-frame";function WX($){return typeof $==="object"&&$!==null}function P6($){if(!WX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function qX($){return $.isTracingEnabled()}function IX($){return $.endsWith(`
|
|
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(` ${$}`)},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,G,Y,X){let Z=X.getSubLogger({name:"createBinaryEntrypoint"}),q=B0.join(Y,M),I=B0.join(q,Q),U=B0.join(I,J),K=B0.join(I,G);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 e$($,M){let J=(Q,...G)=>{if(typeof Q==="string")return $(Q).env(M);return $(Q,...G).env(M)};if(Object.assign(J,$),s0($))Object.defineProperty(J,tM,{value:!0,enumerable:!1});return J}function q$($,M){return $ instanceof f?$.withToolName(M):$}import QJ from"crypto";import i$ from"path";var T={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 G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, 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 $M{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(T.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(T.cachingDisabled("returning null",$)),null;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),null;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),await this.deleteEntry($,G),null;if(G.type==="json")return M.debug(T.cacheHit($,"JSON")),G.data;else{if(!this.binariesDir)throw Error(T.binaryDirectoryNotConfigured());let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.warn(T.binaryFileMissing($,Y)),await this.fileSystem.rm(J).catch(()=>{}),null;let X=await this.fileSystem.readFile(Y),Z=Buffer.isBuffer(X)?X:Buffer.from(X),q=QJ.createHash("sha256").update(Z).digest("hex"),I=G.contentHash;if(q!==I)return M.warn(T.contentHashMismatch($,I,q)),await this.deleteEntry($,G),null;return M.debug(T.cacheHit($,"binary",Z.length)),Z}}catch(J){return M.warn(T.retrievalFailed($,this.getErrorMessage(J))),null}}async set($,M,J){let Q=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){Q.debug(T.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let G=J??this.config.defaultTtl,Y=Date.now();if(this.config.storageStrategy==="json"){let X={type:"json",data:M,timestamp:Y,expiresAt:Y+G},Z=this.getMetadataFilePath($);await this.fileSystem.writeFile(Z,JSON.stringify(X,null,2),"utf8"),Q.debug(T.cacheStored($,"JSON",new Date(X.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(M))throw Error(T.binaryDataRequired());if(!this.binariesDir)throw Error(T.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:Y,expiresAt:Y+G},K=this.getMetadataFilePath($);await this.fileSystem.writeFile(K,JSON.stringify(U,null,2),"utf8"),Q.debug(T.cacheStored($,"binary",new Date(U.expiresAt).toISOString(),X.length))}}catch(G){let Y=this.getErrorMessage(G);throw Q.warn(T.storageFailed($,Y)),Error(`Failed to cache data: ${Y}`,{cause:G})}}async setDownload($,M,J,Q,G){let Y=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){Y.debug(T.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(T.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:G,timestamp:Z,expiresAt:Z+X},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(K,null,2),"utf8"),Y.debug(T.cacheStored($,"download",new Date(K.expiresAt).toISOString(),M.length))}catch(X){let Z=this.getErrorMessage(X);throw Y.warn(T.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(T.cachingDisabled("returning false",$)),!1;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),!1;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),!1;if(G.type==="binary"&&this.binariesDir){let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.debug(T.binaryFileMissing($,Y)),!1}return M.debug(T.cacheEntryExists($)),!0}catch(J){return M.warn(T.checkFailed($,this.getErrorMessage(J))),!1}}async delete($){let M=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){M.debug(T.cachingDisabled("skipping delete",$));return}try{let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J)){let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);await this.deleteEntry($,G),M.debug(T.cacheEntryRemoved($))}else M.debug(T.noEntryToDelete($))}catch(J){let Q=this.getErrorMessage(J);throw M.warn(T.deleteFailed($,Q)),Error(`Failed to delete cache entry: ${Q}`,{cause:J})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(T.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(T.cacheDirectoryMissing());return}let M=await this.fileSystem.readdir(this.metadataDir),J=0;for(let Q of M){if(!Q.endsWith(".json"))continue;let G=i$.join(this.metadataDir,Q);try{let Y=await this.fileSystem.readFile(G,"utf8"),X=JSON.parse(Y);if(this.isExpired(X)){let Z=i$.basename(Q,".json");await this.deleteEntry(Z,X),J++}}catch(Y){$.warn(T.metadataProcessingWarning(Q,this.getErrorMessage(Y))),await this.fileSystem.rm(G).catch(()=>{}),J++}}$.debug(T.expiredEntriesCleared(J))}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.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(T.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(T.cacheCleared());else $.debug(T.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.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(T.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 JX from"crypto";function k6($,M={}){let J={headers:M.headers||{}},Q={url:$,options:J};return`download:${JX.createHash("sha256").update(JSON.stringify(Q)).digest("hex")}`}import QX 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 G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, 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 ${$}`)},MM={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,G,Y)=>W(`HttpError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}`),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,G,Y,X)=>W(`RateLimitError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}, resetTimestamp=${String(X)}`),clientErrorCreated:($,M,J,Q,G)=>W(`ClientError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`),serverErrorCreated:($,M,J,Q,G)=>W(`ServerError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`)};class zQ{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,M,J,Q,G=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=M,this.cache=J,this.underlyingStrategy=Q,this.cacheTtl=G,this.name=`cached-${Q.name}`,this.logger.debug(B$.strategyWrapped(Q.name,G))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,M,J,Q,G){if($.trace(B$.cacheHit(J,"binary",M.length),{url:Q}),G.onProgress)G.onProgress(0,M.length);if(G.destinationPath){if(await this.fileSystem.ensureDir(QX.dirname(G.destinationPath)),await this.fileSystem.writeFile(G.destinationPath,M),$.trace(B$.cachedFileWritten(G.destinationPath)),G.onProgress)G.onProgress(M.length,M.length);return}if(G.onProgress)G.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,G){try{await this.cache.setDownload(J,M,this.cacheTtl,Q,this.extractContentTypeFromHeaders(G.headers)),$.trace(B$.cacheStored(J,"binary","TTL-based",M.length),{url:Q})}catch(Y){$.trace(B$.cacheStorageFailed(J),Y)}}async download($,M={}){let J=this.logger.getSubLogger({name:"download"}),Q=k6($,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 G=await this.underlyingStrategy.download($,M),Y=await this.determineBufferToCache(J,G,M);if(Y)await this.cacheResult(J,Y,Q,$,M);return G}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class BQ extends Error{url;constructor($,M,J){super(M);let Q=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=J,Q.debug(MM.errorCreated("DownloaderError",M,J))}}class I$ extends BQ{originalError;constructor($,M,J,Q){super($,M,J);let G=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=Q,G.debug(MM.networkErrorCreated(M,J,Q),Q)}}class E$ extends BQ{statusCode;statusText;responseBody;responseHeaders;constructor($,M,J,Q,G,Y,X){super($,M,J);let Z=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=Q,this.statusText=G,this.responseBody=Y,this.responseHeaders=X,Z.debug(MM.httpErrorCreated(M,J,Q,G,Y,X),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X})}}class S$ extends E${constructor($,M,J,Q){super($,"Resource not found",M,404,"Not Found",J,Q);let G=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",G.debug(MM.notFoundErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class bM extends E${constructor($,M,J,Q){super($,"Access forbidden",M,403,"Forbidden",J,Q);let G=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",G.debug(MM.forbiddenErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class zM extends E${resetTimestamp;constructor($,M,J,Q,G,Y,X,Z){super($,M,J,Q,G,Y,X);let q=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=Z,q.debug(MM.rateLimitErrorCreated(M,J,Q,G,Y,X,Z),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X,resetTimestamp:Z})}}class vM extends E${constructor($,M,J,Q,G,Y){super($,`Client error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ClientError"});this.name="ClientError",X.debug(MM.clientErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class NM extends E${constructor($,M,J,Q,G,Y){super($,`Server error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ServerError"});this.name="ServerError",X.debug(MM.serverErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class DQ{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 G=Date.parse(J);if(!Number.isNaN(G))return G}return}async setupDownloadRequest($,M,J){let Q=new AbortController,G;if(J)G=setTimeout(()=>{this.logger.debug(k$.downloadTimeout($)),Q.abort()},J);return{response:await aG($,{headers:M,signal:Q.signal},this.proxyConfig),timeoutId:G}}async handleErrorResponse($,M){let J;try{J=await $.text()}catch(Z){this.logger.debug(k$.responseBodyReadFailed(M,Z))}let Q=this.getResponseHeaders($.headers),G=$.status,Y=$.statusText;if(this.logger.debug(k$.downloadFailed(M,G,Y,J?.substring(0,100))),G===404)throw new S$(this.logger,M,J,Q);let X=this.parseRateLimitReset($.headers);if(G===403){if(X)throw new zM(this.logger,"Forbidden: Rate limit likely exceeded",M,G,Y,J,Q,X);throw new bM(this.logger,M,J,Q)}if(G===429)throw new zM(this.logger,"Too Many Requests",M,G,Y,J,Q,X);if(G>=400&&G<500)throw new vM(this.logger,M,G,Y,J,Q);if(G>=500&&G<600)throw new NM(this.logger,M,G,Y,J,Q);throw new E$(this.logger,`HTTP error ${G}`,M,G,Y,J,Q)}async processResponseStream($,M,J){let Q=$.headers.get("content-length"),G=null;if(Q){let q=parseInt(Q,10);if(!Number.isNaN(q))G=q}let Y=0;if(J)J(Y,G);let X=[],Z=$.body?.getReader();if(!Z)throw new I$(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)),Y+=I.length,J)J(Y,G)}}return Buffer.concat(X)}async handleDownloadAttempt($,M,J){let{headers:Q,timeout:G,onProgress:Y,destinationPath:X}=M;this.logger.debug(k$.downloadAttempt(J+1,$));let{response:Z,timeoutId:q}=await this.setupDownloadRequest($,Q,G);if(q)clearTimeout(q);if(!Z.ok)await this.handleErrorResponse(Z,$);let I=await this.processResponseStream(Z,$,Y);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,G){if(this.logger.debug(k$.downloadAttemptError(J+1,M,$)),J>=Q){if($ instanceof E$||$ instanceof I$)throw $;let Y=`Failed to download ${M}`;if($ instanceof Error&&$.name==="AbortError")Y=`Download timed out for ${M}`;else if($ instanceof Error)Y=$.message;throw new I$(this.logger,Y,M,$ instanceof Error?$:void 0)}}async retryDownload($,M,J,Q,G){this.logger.debug(k$.retryingDownload($,M+2,J+1,Q)),await new Promise((Y)=>setTimeout(Y,Q))}async download($,M){let{retryCount:J=0,retryDelay:Q=1000,onProgress:G}=M,Y=0;while(Y<=J)try{return await this.handleDownloadAttempt($,M,Y)}catch(X){if(this.handleDownloadError(X,$,Y,J,G),Y<J)await this.retryDownload($,Y,J,Q,G),Y++}throw this.logger.debug(k$.exhaustedRetries($)),new I$(this.logger,`Download failed for ${$} after ${J} retries.`,$)}}class AQ{strategies=[];fs;logger;constructor($,M,J,Q,G){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=M,typeof J<"u")this.strategies=J;else{let Y=new DQ(this.logger,this.fs,G),X=G?.enabled?` (proxy port ${G.port})`:"";if(Q)this.logger.debug(D0.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${X}`)),this.strategies.push(new zQ(this.logger,this.fs,Q,Y));else this.logger.debug(D0.strategyCreated("NodeFetchStrategy",X||" (no cache)")),this.strategies.push(Y)}}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 G;for(let Y of this.strategies)try{let X=await this.tryDownloadWithStrategy(Y,M,J);if(X.success)return X.buffer}catch(X){G=this.normalizeError(X)}if(G)throw G;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 Y={...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,Y)).success)return}catch(q){X=this.normalizeError(q)}if(X)throw X;throw Error(`No available download strategy succeeded for ${M}.`)}}import*as oM from"cli-progress";class EQ{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 oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.Presets.shades_classic),this.progressBar.start(M,0,{speed:"0 B/s"});else this.progressBar=new oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.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 G=Math.floor(Date.now()/100)%100;this.progressBar.update(G,{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 S6($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.NO_COLOR)return!1;return!0}async function U$($,M,J,Q,G,Y){let X=S6(Y?.quiet),Z=new EQ(Q,{enabled:X});try{await G.download($,M,{destinationPath:J,onProgress:Z.createCallback()})}finally{Z.finish()}}function w6($){return $.installParams?.hooks}async function w$($,M,J,Q,G){let X=w6($)?.["after-download"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-download"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"after-download",q,Z);if(!I.success)return{success:!1,error:`afterDownload hook failed: ${I.error}`}}return{success:!0}}async function eM($,M,J,Q,G){let X=w6($)?.["after-extract"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-extract"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"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 YX($){if(!GX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function b6($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function v6($){if(YX($)){let M=b6($.stderr);if(M.length>0)return M;let J=b6($.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 GJ($){return l$($).map((J)=>J.name)}import{join as XX}from"path";function e($,M){return l$($).map((Q)=>XX(M,Q.name))}import u6 from"path";import{codeFrameColumns as ZX}from"@babel/code-frame";function WX($){return typeof $==="object"&&$!==null}function P6($){if(!WX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function qX($){return $.isTracingEnabled()}function IX($){return $.endsWith(`
|
|
60
60
|
`)?$:`${$}
|
|
61
61
|
`}function C6($,M,J){return{filePath:$,line:M,column:J}}function N6($,M){let J=M.exec($);if(!J)return null;let Q=J[1],G=Number(J[2]),Y=Number(J[3]);if(!Q||Number.isNaN(G)||Number.isNaN(Y))return null;return C6(Q,G,Y)}function UX($){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 C6(J,Q,1)}function KX($){let M=$.split(`
|
|
62
62
|
`);for(let J of M){if(!J.includes(".tool.ts"))continue;let Q=N6(J,/\(([^)]+\.tool\.ts):(\d+):(\d+)\)\s*$/);if(Q)return Q;let G=N6(J,/\s+at\s+([^\s]+\.tool\.ts):(\d+):(\d+)\s*$/);if(G)return G;let Y=UX(J);if(Y)return Y}return null}async function HX($,M){if(!await $.exists(M.filePath))return null;let Q=await $.readFile(M.filePath,"utf8"),G=ZX(Q,{start:{line:M.line,column:M.column}},{linesAbove:2,linesBelow:2,highlightCode:!0,forceColor:!0});return`${M.filePath}:${M.line}:${M.column}
|
|
@@ -66,7 +66,7 @@ ${G}
|
|
|
66
66
|
`)}return J.push(String($)),J.join(`
|
|
67
67
|
`)}async function OX($,M){if(!M)return null;let J=KX(M);if(!J)return null;return await HX($,J)}function jX($,M){if(!M)return[];if(!$||$.length===0)return[];return["stack:",$]}async function VX($,M){let J=[_X($)],Q=typeof $.stack==="string"?$.stack:void 0,G=jX(Q,M);return J.push(...G),J}async function zX($,M){return[RX($,M)]}async function BX($){let M=qX($.logger),J=[],Q=DX($.error),G=await OX($.fileSystem,Q);if(G)J.push("---"),J.push(G),J.push("---");if(M)if(P6($.error)){let X=await VX($.error,!0);J.push(...X)}else{let X=await zX($.error,!0);J.push(...X)}if(J.length===0)return"";return IX(J.join(`
|
|
68
68
|
`))}function DX($){if(P6($))return typeof $.stack==="string"?$.stack:void 0;if($ instanceof Error)return $.stack;return}async function d6($){let M=await BX($);if(M.length>0)$.writeOutput(M)}function AX($){if(typeof $!=="object"||$===null)return!1;return $.name==="ShellError"}function EX($,M){return Object.assign((Q,...G)=>{return $(Q,...G).cwd(M)},$)}function FX($,M,J,Q){if(M.length===0)return $;let G=J===4?";":":",Y=Q.PATH||"",X=[...M,Y].join(G),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 FQ{defaultTimeoutMs=60000;writeOutput;constructor($){this.writeOutput=$}async executeHook($,M,J,Q,G={}){let Y=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHook",context:M}),X=G.timeoutMs??this.defaultTimeoutMs,Z=G.continueOnError??!1,q=Date.now();Y.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 Y.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),_=v6(U);if(Y.error(L.outcome.hookFailed(_),U),AX(U))await d6({fileSystem:Q.fileSystem,logger:Y,hookName:M,toolName:Q.toolName,error:U,writeOutput:this.writeOutput});if(Z)Y.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,G=$.toolConfig?.configFilePath,Y=G?u6.dirname(G):void 0,X="binaryPaths"in $&&Array.isArray($.binaryPaths)?$.binaryPaths:[],Z=[...new Set(X.map((H)=>u6.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=FX(q,Z,$.systemInfo.platform,U);if(Y)q=EX(q,Y);if(I)q=E6(q,J);return{...$,$:q,fileSystem:Q}}async executeHooks($,M,J){let Q=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHooks"}),G=[];for(let X of M){let{name:Z,hook:q,options:I}=X,U=await this.executeHook($,Z,q,J,I);if(G.push(U),!U.success&&!I?.continueOnError){Q.debug(L.hookExecutor.stoppingDueToFailure(Z));break}}return G}}import{minimatch as LX}from"minimatch";import BM from"path";async function DM($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"setupBinariesFromArchive"}),Z=BM.join(Q.projectConfig.paths.generatedDir,"binaries"),q=l$(J.binaries),I=BM.basename(Q.stagingDir);await xX($,M,q,I,G,Z,X)}async function xX($,M,J,Q,G,Y,X){let Z=X.getSubLogger({name:"setupBinariesUsingPatterns"}),q=!1;for(let I of J){let{name:U,pattern:K}=I,H=await SX($,G,K,U,Z);if(!H){Z.error(L.binarySetupService.binaryNotFound(U,K));let O=await f6($,G);if(O.length>0){let B=O.join(`
|
|
69
|
-
`);Z.error(L.binarySetupService.extractedFilesTree(G,B))}continue}let _=BM.relative(G,H);await JJ($,M,U,Q,_,Y,Z),q=!0}return q}async function f6($,M,J="",Q=3,G=0){let Y=[];if(G>=Q)return Y;let X=[];try{X=await $.readdir(M)}catch{return Y}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=BM.join(M,I),H=U?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",_=J+(U?" ":"\u2502 "),O=await TX($,K,I,J,H,_,Q,G);Y.push(...O)}return Y}async function TX($,M,J,Q,G,Y,X,Z){let q=[];try{let I=await $.stat(M),U=I.isDirectory()?`${J}/`:J;if(q.push(`${Q}${G}${U}`),I.isDirectory()&&Z<X-1){let K=await f6($,M,Y,X,Z+1);q.push(...K)}}catch{q.push(`${Q}${G}${J} (inaccessible)`)}return q}async function kX($,M){return((await $.stat(M)).mode&73)!==0}async function SX($,M,J,Q,G){G.getSubLogger({name:"findBinaryUsingPattern"}).debug(L.binarySetupService.searchingWithPattern(J,M));let Z=(await SM($,M,M)).filter((K)=>LX(K,J));if(Z.length===0)return null;let q=[];for(let K of Z){let H=BM.join(M,K);if(await kX($,H))q.push(K)}if(q.length===0)return null;let I=q.find((K)=>BM.basename(K)===Q);if(I)return BM.join(M,I);let U=q[0];if(U)return BM.join(M,U);return null}import LQ from"path";async function $0($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"setupBinariesFromDirectDownload"}),Z=l$(J.binaries),q=Z[0]?.name||M;await $.chmod(G,493);let I=LQ.join(Q.projectConfig.paths.generatedDir,"binaries"),U=LQ.basename(G),K=LQ.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(G){return J.error(L.outcome.installFailed($),G),{success:!1,error:G instanceof Error?G.message:String(G)}}}class xQ{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??e$(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),G=$.$shell??e$(this.$shell,process.env),Y=(I={})=>({...Q,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:G,fileSystem:this.fileSystem,installEnv:$.installEnv,...I}),X=Y(),Z=async(I,U)=>{await this.emitInstallEvent({type:I,toolName:$.toolName,context:{...Y(U),emitEvent:Z,logger:J}})};return X.emitEvent=Z,{context:X,logger:J}}getToolDirectory($){return $.configFilePath?wX.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function YJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function bX($){return Array.isArray($)&&$.every((M)=>typeof M==="function")}function vX($){if(!YJ($))return!1;return typeof $.getSubLogger==="function"}function TQ($){if(!YJ($))return;let M=$.installParams;if(!YJ(M))return;let J=M.hooks;if(!YJ(J))return;let Q=Object.entries(J);if(Q.length===0)return;let G={};for(let[Y,X]of Q){if(!bX(X))return;G[Y]=X}return G}class kQ{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,M,J){if(!M)return;let Q=TQ(M);if(!Q)return;let G=Q[$.type];if(!G)return;let Y=$.context.logger,X=vX(Y)?Y:J,Z=$.context.fileSystem,q=this.hookExecutor.createEnhancedContext($.context,Z,X);for(let I of G){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 G=Q.getSubLogger({name:"executeBeforeInstallHook"}),X=TQ($)?.["before-install"];if(!X)return null;G.debug(L.lifecycle.hookExecution("before-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X){let I=await this.hookExecutor.executeHook(G,"before-install",q,Z);if(!I.success)return{success:!1,error:`beforeInstall hook failed: ${I.error}`}}return null}async executeAfterInstallHook($,M,J,Q){let G=Q.getSubLogger({name:"executeAfterInstallHook"}),X=TQ($)?.["after-install"];if(!X)return;G.debug(L.lifecycle.hookExecution("after-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X)await this.hookExecutor.executeHook(G,"after-install",q,Z,{continueOnError:!0})}}import JM from"path";function NX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yX($){let M={};if(!$.success)return M;if(!("metadata"in $))return M;let J=$.metadata;if(!NX(J))return M;let{method:Q,...G}=J;if(typeof Q==="string")return{...G,installMethod:Q};return J}class SQ{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"recordInstallation"});if(!G.success)return;try{let Z="version"in G&&G.version?G.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 G&&typeof G.originalTag==="string"?G.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:Z,installPath:J,timestamp:Q.timestamp,binaryPaths:G.binaryPaths,configuredVersion:I,originalTag:U,...yX(G)}),X.debug(L.outcome.installSuccess($,Z,"registry-recorded"))}catch(Z){X.error(L.outcome.installFailed("registry-record"),Z)}}async createBinaryEntrypoints($,M,J,Q,G,Y){let X=Q.getSubLogger({name:"createBinaryEntrypoints"}),Z=JM.join(this.projectConfig.paths.binariesDir,$);if(await J.ensureDir(Z),Y){let q=JM.join(Z,"external");await J.ensureDir(q);for(let I of M){let U=JM.basename(I),K=JM.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=JM.basename(q),U=JM.join(G,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,G){let Y=J.getSubLogger({name:"updateCurrentSymlink"}),X=JM.join(this.projectConfig.paths.binariesDir,$),Z=JM.join(X,"current");await M.ensureDir(X);let q=G?"external":JM.basename(Q);try{if(await M.exists(Z))await M.rm(Z,{force:!0,recursive:!0})}catch(I){throw Y.error(L.lifecycle.removingExistingSymlink(Z),I),I}try{await M.withFileType("symlink").symlink(q,Z,"dir")}catch(I){throw Y.error(L.lifecycle.creatingExternalSymlink(Z,q),I),I}try{let I=await M.readlink(Z);if(I!==q)throw Y.error(L.lifecycle.symlinkVerificationFailed(Z)),Error(`Symlink verification failed: ${Z} points to ${I}, expected ${q}`)}catch(I){throw Y.error(L.lifecycle.symlinkVerificationFailed(Z),I),I}}}class wQ{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;installContextFactory;currentToolConfig;constructor($,M,J,Q,G,Y,X,Z,q,I){this.logger=$.getSubLogger({name:"Installer"}),this.fs=M,this.resolvedFs=J,this.projectConfig=Q,this.hookExecutor=I,this.hookLifecycle=new kQ(I),this.toolInstallationRegistry=G,this.systemInfo=Y,this.registry=X,this.installationStateWriter=new SQ({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:Z}),this.$=q,this.installContextFactory=new xQ({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 shouldSkipInstallation($,M,J,Q){let G=Q.getSubLogger({name:"shouldSkipInstallation"});if(J?.force||J?.skipVersionCheck)return null;let Y=await this.toolInstallationRegistry.getToolInstallation($);if(!Y)return null;let X=M0.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(Y.version===U)return G.debug(L.outcome.installSuccess($,U,"already-installed")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I};return G.debug(L.outcome.outdatedVersion($,Y.version,U)),null}return G.debug(L.outcome.installSuccess($,Y.version,"already-installed-latest")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I}}async executeInstallationMethod($,M,J,Q,G){return await this.registry.install(G,M.installationMethod,$,M,J,Q)}async install($,M,J){let Q=this.logger.getSubLogger({name:"install",context:$}),G=this.getSystemInfo(),Y=G$(M,G);this.currentToolConfig=Y;let X=this.fs.withToolName($);if(J?.shimMode)X.setSuppressLogging(!0);try{let Z=await this.shouldSkipInstallation($,Y,J,Q);if(Z)return Z;let q=this.registry.get(Y.installationMethod),I=q?.externallyManaged===!0,U=this.projectConfig.paths.binariesDir,K=M0.join(U,$);await X.ensureDir(K);let H=nG(),_=H;if(Y.version&&Y.version!=="latest")_=Y.version;if(!I&&q?.resolveVersion){let m=this.createMinimalContext($,Y,Q);try{let $$=await q.resolveVersion($,Y,m,Q);if($$)_=$$,Q.debug(L.lifecycle.versionResolved($$));else Q.debug(L.lifecycle.versionFallbackToTimestamp())}catch($$){Q.debug(L.lifecycle.versionResolutionFailed($$))}}let O=PX(),B=M0.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="/Users/alex/development/projects/dotfiles-installer/packages/build:/Users/alex/development/projects/dotfiles-installer/packages/build/src/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/src/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/src/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/go/bin:/Users/alex/Applications/cmux.app/Contents/Resources/bin:/Users/alex/.local/state/fnm_multishells/7266_1772222045270/bin:/Users/alex/.fly/bin:/Users/alex/.cache/.bun/bin:node_modules/.bin:/Users/alex/.orbstack/bin:/Users/alex/.cargo/bin:/Users/alex/.dotfiles/.generated/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/pmk/env/global/bin:/Library/Apple/usr/bin:/opt/homebrew/bin:/Users/alex/.local/bin:/Users/alex/.dotfiles/bin:/Users/alex/.local/bin",D=G.platform===4?";":":",A=I?V:`${B}${D}${V}`,b={...process.env,[j]:"true",PATH:A},k=e$(this.$,b),{context:S,logger:u}=this.createBaseInstallContext($,B,H,Y,Q,k,b),i=await this.hookLifecycle.executeBeforeInstallHook(Y,S,X,u);if(i)return i;let E;try{E=await this.executeInstallationMethod($,Y,S,J,u),E.installationMethod=Y.installationMethod;let m=E.success&&"version"in E?E.version:void 0,$$=_===H&&m&&m!==H?m:_,g=I?M0.join(K,"external"):M0.join(K,$$);if(E.success&&!I){if(await X.exists(g))await X.rm(g,{recursive:!0,force:!0});if(await X.rename(B,g),Q.debug(L.lifecycle.directoryRenamed(B,g)),E.success&&"binaryPaths"in E&&E.binaryPaths)E.binaryPaths=E.binaryPaths.map((y)=>y.startsWith(B)?y.replace(B,g):y)}if(E.success&&I)await X.ensureDir(g);let o=E.success&&"binaryPaths"in E?E.binaryPaths:void 0;if(E.success&&o){let y=[];for(let O$ of o)if(await X.exists(O$))y.push(O$);if(y.length>0)await this.installationStateWriter.createBinaryEntrypoints($,y,X,Q,g,I)}if(E.success)await this.installationStateWriter.updateCurrentSymlink($,X,Q,g,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=M0.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:[],O$="version"in E?E.version:void 0,r$=I?V:`${g}${D}${V}`,d0={...process.env,[j]:"true",PATH:r$},T$=e$(this.$,d0),sJ={...S,$:T$,installedDir:g,binaryPaths:y,version:O$,installEnv:d0};await this.hookLifecycle.executeAfterInstallHook(Y,sJ,X,u),await this.installationStateWriter.recordInstallation($,Y,g,S,E,u)}return E}catch(m){return E={success:!1,error:m instanceof Error?m.message:String(m),installationMethod:Y.installationMethod},Q.error(W(E.error)),E}}catch(Z){let q={success:!1,error:Z instanceof Error?Z.message:String(Z),installationMethod:Y.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,G,Y=e$(this.$,process.env),X){let Z=G.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:M,timestamp:J,toolConfig:Q,parentLogger:Z,$shell:Y,installEnv:X})}getSystemInfo(){return this.systemInfo}}import{z as yM}from"zod";var d$={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 CX=yM.object({name:yM.string(),versions:yM.object({stable:yM.string(),head:yM.string().optional(),bottle:yM.boolean().optional()})});async function p6($,M,J,Q,G,Y,X){let Z=G.getSubLogger({name:"installFromBrew"});if(Z.debug(d$.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 fX(I,U,K,Q?.force,Z,Y,_);let O=await uX(I,Z,Y),B=e(M.binaries,`${O}/bin`),j,V=B[0];if(q.versionArgs&&q.versionRegex&&V)j=await D$({binaryPath:V,args:q.versionArgs,regex:q.versionRegex,shellExecutor:Y});else j=await dX(I,Z,Y);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:I,isCask:U,tap:K}}})}async function dX($,M,J){try{M.debug(d$.fetchingVersion($));let G=(await J`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),Y=JSON.parse(G),X=yM.array(CX).parse(Y);if(X.length>0&&X[0]?.versions.stable){let Z=X[0].versions.stable,q=j$(Z);return M.debug(d$.versionFetched($,q)),q}M.debug(d$.versionNotFound($));return}catch(Q){M.debug(d$.versionFetchFailed($),Q);return}}async function uX($,M,J){try{let G=(await J`brew --prefix ${$}`.quiet()).stdout.toString().trim();return M.debug(d$.prefixFetched($,G)),G}catch(Q){M.debug(d$.prefixFetchFailed($),Q);let Y=`${(await J`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return M.debug(d$.prefixFallback($,Y)),Y}}async function fX($,M,J,Q,G,Y,X){if(J){let q=Array.isArray(J)?J:[J];for(let I of q)G.debug(d$.executingCommand(`brew tap ${I}`)),await Y`brew tap ${I}`.quiet()}let Z=["install"];if(M)Z.push("--cask");if(Q)Z.push("--force");Z.push($),G.info(d$.executingCommand(`brew ${Z.join(" ")}`)),await X`brew ${Z}`}import{z as QM}from"zod";var XJ=r.extend({formula:QM.string().optional(),cask:QM.boolean().optional(),tap:QM.union([QM.string(),QM.array(QM.string())]).optional(),versionArgs:QM.array(QM.string()).optional(),versionRegex:QM.string().optional()});import{z as pX}from"zod";var c6=t.extend({installationMethod:pX.literal("brew"),installParams:XJ});var cX="1.0.0";class bQ{shell;method="brew";displayName="Homebrew Installer";version=cX;paramsSchema=XJ;toolConfigSchema=c6;constructor($){this.shell=$}externallyManaged=!0;async install($,M,J,Q,G){let Y=await p6($,M,J,Q,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as hX}from"smol-toml";import{z as u$}from"zod";class J0 extends Error{statusCode;cause;constructor($,M,J){super($);if(this.name="CargoClientError",this.statusCode=M,this.cause=J,Error.captureStackTrace)Error.captureStackTrace(this,J0)}}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 mX=u$.object({package:u$.object({name:u$.string(),version:u$.string(),edition:u$.string().optional(),description:u$.string().optional(),authors:u$.array(u$.string()).optional(),license:u$.string().optional(),repository:u$.string().optional(),homepage:u$.string().optional()})});class vQ{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,M,J,Q,G){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=J,this.cratesIoCache=Q,this.githubRawCache=G,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:G,cacheKey:Y,cacheTtl:X}=this.resolveCacheOptions($,M),Z=await this.tryReadCache(Y,G);if(Z)return Z;let q=await this.performDownload($,Q),I=this.parseJson(q,$);return await this.tryStoreCache(Y,I,X,G),I}resolveCacheOptions($,M){if(!M)return{useCache:!1,cacheTtl:0};let J=M.kind,Q=J==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,G=J==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,Y=Q?`cargo:${J}:${$}`:void 0;return{useCache:Q,cacheKey:Y,cacheTtl:G}}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 G=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!Q||!$||!G)return;try{await G.set($,M,J)}catch{}}parseJson($,M){let J=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw J.error(b$.errors.emptyResponse(M)),new I$(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 J0(`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 I$(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 G=await this.tryReadCache(Q,J);if(G)return G}try{let G=await this.downloader.download(M,$,{headers:this.buildRequestHeaders()});if(!G||G.length===0)return M.error(b$.errors.emptyResponse($)),null;let Y=this.parseCargoToml(G);return await this.tryStoreCache(Q,Y,this.githubRawCacheTtl,J),Y}catch(G){if(G instanceof J0)throw G;if(G instanceof S$)return null;throw M.error(b$.parsing.cargoTomlParseError($),G),G}}parseCargoToml($){let M=this.logger.getSubLogger({name:"parseCargoToml"}),J=$.toString("utf-8"),Q=hX(J),G=mX.safeParse(Q);if(!G.success)throw M.zodErrors(G.error),new J0("Could not parse version from Cargo.toml [package] section",void 0);return G.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import gX from"path";var K$={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 h6($,M,J,Q,G,Y,X,Z,q,I,U){let K=I.getSubLogger({name:"installFromCargo"});if(K.debug(K$.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$(G,$),j=await lX(_,H,X,K);K.debug(K$.foundVersion(_,j.version));let V=await sX(_,j.version,H,J,U);K.debug(K$.downloadingAsset(`${_}-${j.version}`,V));let D=`${_}-${j.version}.tar.gz`,A=gX.join(J.stagingDir,D);await U$(K,V,A,D,Y,Q);let b={...J,version:j.version},k=await nX(M,q,b,A,B,K);if(!k.success)return k;let S=await Z.extract(K,A,{targetDir:J.stagingDir});K.debug(K$.archiveExtracted(),S),await DM(G,$,M,J,J.stagingDir,K);let u=await iX(M,q,b,S,B,K);if(!u.success)return u;if(await G.exists(A))await G.rm(A),K.debug(K$.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 nX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-download"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,downloadPath:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterDownload",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function iX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-install"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,extractResult:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterInstall",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function lX($,M,J,Q){let G=M.versionSource||"cargo-toml";switch(G){case"cargo-toml":{let Y=M.cargoTomlUrl||J.buildCargoTomlUrl(M.githubRepo||`${$}-community/${$}`);Q.debug(K$.parsingMetadata(Y));let X=await J.getCargoTomlPackage(Y);if(!X)throw Error(`Failed to fetch or parse Cargo.toml from ${Y}`);return{version:j$(X.version)}}case"crates-io":{Q.debug(K$.queryingCratesIo($));let Y=await J.getLatestVersion($);if(!Y)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(Y)}}case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases version source");return aX(M.githubRepo,Q)}default:throw Error(`Unknown version source: ${G}`)}}async function aX($,M){throw M.debug(K$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function sX($,M,J,Q,G){let Y=J.binarySource||"cargo-quickinstall",X=rX(Q.systemInfo.platform),Z=tX(Q.systemInfo.arch);switch(Y){case"cargo-quickinstall":return`${G}/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`${G}/${J.githubRepo}/releases/download/v${M}/${I}`}default:throw Error(`Unknown binary source: ${Y}`)}}function rX($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function tX($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as Q0}from"zod";var ZJ=r.extend({crateName:Q0.string(),binarySource:Q0.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:Q0.string().optional(),assetPattern:Q0.string().optional(),versionSource:Q0.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:Q0.string().optional()});import{z as oX}from"zod";var m6=t.extend({installationMethod:oX.literal("cargo"),installParams:ZJ});var eX="1.0.0";class NQ{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=eX;paramsSchema=ZJ;toolConfigSchema=m6;constructor($,M,J,Q,G,Y){this.fs=$;this.downloader=M;this.cargoClient=J;this.archiveExtractor=Q;this.hookExecutor=G;this.githubHost=Y}async install($,M,J,Q,G){let Y=await h6($,M,J,Q,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,G,this.githubHost);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}async resolveVersion($,M,J,Q){let G=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.crateName;if(!X)return G.debug(K$.versionResolutionFailed($,"Missing crateName in install params")),null;let Z=await this.cargoClient.getLatestVersion(X);if(!Z)return G.debug(K$.versionResolutionFailed($,`Could not fetch version for crate: ${X}`)),null;let q=AM(Z);return G.debug(K$.versionResolutionResolved($,q)),q}catch(Y){return G.debug(K$.versionResolutionException($,Y)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let Y=M.installParams?.crateName;if(!Y)return{success:!1,error:"Missing crateName in install params"};let X=await this.cargoClient.getLatestVersion(Y);if(!X)return{success:!1,error:`Could not fetch latest version for crate: ${Y}`};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(G){return Q.error(K$.updateCheckFailed($),G),{success:!1,error:G instanceof Error?G.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 $8($,M,J,Q){let G=GJ($.binaries);for(let Y of G){let X=WJ.join(M.stagingDir,Y);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,Y);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(Y,`${M.stagingDir}, ${Z.join(", ")}`))}}async function g6($,M,J,Q,G,Y,X,Z,q,I){let U=q$(G,$),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 U$(K,_,j,`${$}-install.sh`,Y,Q),await U.chmod(j,493);let V={...J,downloadPath:j},D=await w$(M,V,X,G,K);if(!D.success)return D;K.debug(GM.executingScript(O));let A={projectConfig:J.projectConfig,scriptPath:j,stagingDir:J.stagingDir},b=H.args?await wM(A,H.args):[],k=H.env?await wM(A,H.env):{},S={...process.env,...k},u=I??W$({logger:K,skipCommandLog:!0}),i="";if(O==="bash"){let y=await u`bash ${j} ${b}`.env(S);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
69
|
+
`);Z.error(L.binarySetupService.extractedFilesTree(G,B))}continue}let _=BM.relative(G,H);await JJ($,M,U,Q,_,Y,Z),q=!0}return q}async function f6($,M,J="",Q=3,G=0){let Y=[];if(G>=Q)return Y;let X=[];try{X=await $.readdir(M)}catch{return Y}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=BM.join(M,I),H=U?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",_=J+(U?" ":"\u2502 "),O=await TX($,K,I,J,H,_,Q,G);Y.push(...O)}return Y}async function TX($,M,J,Q,G,Y,X,Z){let q=[];try{let I=await $.stat(M),U=I.isDirectory()?`${J}/`:J;if(q.push(`${Q}${G}${U}`),I.isDirectory()&&Z<X-1){let K=await f6($,M,Y,X,Z+1);q.push(...K)}}catch{q.push(`${Q}${G}${J} (inaccessible)`)}return q}async function kX($,M){return((await $.stat(M)).mode&73)!==0}async function SX($,M,J,Q,G){G.getSubLogger({name:"findBinaryUsingPattern"}).debug(L.binarySetupService.searchingWithPattern(J,M));let Z=(await SM($,M,M)).filter((K)=>LX(K,J));if(Z.length===0)return null;let q=[];for(let K of Z){let H=BM.join(M,K);if(await kX($,H))q.push(K)}if(q.length===0)return null;let I=q.find((K)=>BM.basename(K)===Q);if(I)return BM.join(M,I);let U=q[0];if(U)return BM.join(M,U);return null}import LQ from"path";async function $0($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"setupBinariesFromDirectDownload"}),Z=l$(J.binaries),q=Z[0]?.name||M;await $.chmod(G,493);let I=LQ.join(Q.projectConfig.paths.generatedDir,"binaries"),U=LQ.basename(G),K=LQ.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(G){return J.error(L.outcome.installFailed($),G),{success:!1,error:G instanceof Error?G.message:String(G)}}}class xQ{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??e$(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),G=$.$shell??e$(this.$shell,process.env),Y=(I={})=>({...Q,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:G,fileSystem:this.fileSystem,installEnv:$.installEnv,...I}),X=Y(),Z=async(I,U)=>{await this.emitInstallEvent({type:I,toolName:$.toolName,context:{...Y(U),emitEvent:Z,logger:J}})};return X.emitEvent=Z,{context:X,logger:J}}getToolDirectory($){return $.configFilePath?wX.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function YJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function bX($){return Array.isArray($)&&$.every((M)=>typeof M==="function")}function vX($){if(!YJ($))return!1;return typeof $.getSubLogger==="function"}function TQ($){if(!YJ($))return;let M=$.installParams;if(!YJ(M))return;let J=M.hooks;if(!YJ(J))return;let Q=Object.entries(J);if(Q.length===0)return;let G={};for(let[Y,X]of Q){if(!bX(X))return;G[Y]=X}return G}class kQ{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,M,J){if(!M)return;let Q=TQ(M);if(!Q)return;let G=Q[$.type];if(!G)return;let Y=$.context.logger,X=vX(Y)?Y:J,Z=$.context.fileSystem,q=this.hookExecutor.createEnhancedContext($.context,Z,X);for(let I of G){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 G=Q.getSubLogger({name:"executeBeforeInstallHook"}),X=TQ($)?.["before-install"];if(!X)return null;G.debug(L.lifecycle.hookExecution("before-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X){let I=await this.hookExecutor.executeHook(G,"before-install",q,Z);if(!I.success)return{success:!1,error:`beforeInstall hook failed: ${I.error}`}}return null}async executeAfterInstallHook($,M,J,Q){let G=Q.getSubLogger({name:"executeAfterInstallHook"}),X=TQ($)?.["after-install"];if(!X)return;G.debug(L.lifecycle.hookExecution("after-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X)await this.hookExecutor.executeHook(G,"after-install",q,Z,{continueOnError:!0})}}import JM from"path";function NX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yX($){let M={};if(!$.success)return M;if(!("metadata"in $))return M;let J=$.metadata;if(!NX(J))return M;let{method:Q,...G}=J;if(typeof Q==="string")return{...G,installMethod:Q};return J}class SQ{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"recordInstallation"});if(!G.success)return;try{let Z="version"in G&&G.version?G.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 G&&typeof G.originalTag==="string"?G.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:Z,installPath:J,timestamp:Q.timestamp,binaryPaths:G.binaryPaths,configuredVersion:I,originalTag:U,...yX(G)}),X.debug(L.outcome.installSuccess($,Z,"registry-recorded"))}catch(Z){X.error(L.outcome.installFailed("registry-record"),Z)}}async createBinaryEntrypoints($,M,J,Q,G,Y){let X=Q.getSubLogger({name:"createBinaryEntrypoints"}),Z=JM.join(this.projectConfig.paths.binariesDir,$);if(await J.ensureDir(Z),Y){let q=JM.join(Z,"external");await J.ensureDir(q);for(let I of M){let U=JM.basename(I),K=JM.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=JM.basename(q),U=JM.join(G,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,G){let Y=J.getSubLogger({name:"updateCurrentSymlink"}),X=JM.join(this.projectConfig.paths.binariesDir,$),Z=JM.join(X,"current");await M.ensureDir(X);let q=G?"external":JM.basename(Q);try{if(await M.exists(Z))await M.rm(Z,{force:!0,recursive:!0})}catch(I){throw Y.error(L.lifecycle.removingExistingSymlink(Z),I),I}try{await M.withFileType("symlink").symlink(q,Z,"dir")}catch(I){throw Y.error(L.lifecycle.creatingExternalSymlink(Z,q),I),I}try{let I=await M.readlink(Z);if(I!==q)throw Y.error(L.lifecycle.symlinkVerificationFailed(Z)),Error(`Symlink verification failed: ${Z} points to ${I}, expected ${q}`)}catch(I){throw Y.error(L.lifecycle.symlinkVerificationFailed(Z),I),I}}}class wQ{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;installContextFactory;currentToolConfig;constructor($,M,J,Q,G,Y,X,Z,q,I){this.logger=$.getSubLogger({name:"Installer"}),this.fs=M,this.resolvedFs=J,this.projectConfig=Q,this.hookExecutor=I,this.hookLifecycle=new kQ(I),this.toolInstallationRegistry=G,this.systemInfo=Y,this.registry=X,this.installationStateWriter=new SQ({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:Z}),this.$=q,this.installContextFactory=new xQ({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 shouldSkipInstallation($,M,J,Q){let G=Q.getSubLogger({name:"shouldSkipInstallation"});if(J?.force||J?.skipVersionCheck)return null;let Y=await this.toolInstallationRegistry.getToolInstallation($);if(!Y)return null;let X=M0.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(Y.version===U)return G.debug(L.outcome.installSuccess($,U,"already-installed")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I};return G.debug(L.outcome.outdatedVersion($,Y.version,U)),null}return G.debug(L.outcome.installSuccess($,Y.version,"already-installed-latest")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I}}async executeInstallationMethod($,M,J,Q,G){return await this.registry.install(G,M.installationMethod,$,M,J,Q)}async install($,M,J){let Q=this.logger.getSubLogger({name:"install",context:$}),G=this.getSystemInfo(),Y=G$(M,G);this.currentToolConfig=Y;let X=this.fs.withToolName($);if(J?.shimMode)X.setSuppressLogging(!0);try{let Z=await this.shouldSkipInstallation($,Y,J,Q);if(Z)return Z;let q=this.registry.get(Y.installationMethod),I=q?.externallyManaged===!0,U=this.projectConfig.paths.binariesDir,K=M0.join(U,$);await X.ensureDir(K);let H=nG(),_=H;if(Y.version&&Y.version!=="latest")_=Y.version;if(!I&&q?.resolveVersion){let m=this.createMinimalContext($,Y,Q);try{let $$=await q.resolveVersion($,Y,m,Q);if($$)_=$$,Q.debug(L.lifecycle.versionResolved($$));else Q.debug(L.lifecycle.versionFallbackToTimestamp())}catch($$){Q.debug(L.lifecycle.versionResolutionFailed($$))}}let O=PX(),B=M0.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=G.platform===4?";":":",A=I?V:`${B}${D}${V}`,b={...process.env,[j]:"true",PATH:A},k=e$(this.$,b),{context:S,logger:u}=this.createBaseInstallContext($,B,H,Y,Q,k,b),i=await this.hookLifecycle.executeBeforeInstallHook(Y,S,X,u);if(i)return i;let E;try{E=await this.executeInstallationMethod($,Y,S,J,u),E.installationMethod=Y.installationMethod;let m=E.success&&"version"in E?E.version:void 0,$$=_===H&&m&&m!==H?m:_,g=I?M0.join(K,"external"):M0.join(K,$$);if(E.success&&!I){if(await X.exists(g))await X.rm(g,{recursive:!0,force:!0});if(await X.rename(B,g),Q.debug(L.lifecycle.directoryRenamed(B,g)),E.success&&"binaryPaths"in E&&E.binaryPaths)E.binaryPaths=E.binaryPaths.map((y)=>y.startsWith(B)?y.replace(B,g):y)}if(E.success&&I)await X.ensureDir(g);let o=E.success&&"binaryPaths"in E?E.binaryPaths:void 0;if(E.success&&o){let y=[];for(let O$ of o)if(await X.exists(O$))y.push(O$);if(y.length>0)await this.installationStateWriter.createBinaryEntrypoints($,y,X,Q,g,I)}if(E.success)await this.installationStateWriter.updateCurrentSymlink($,X,Q,g,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=M0.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:[],O$="version"in E?E.version:void 0,r$=I?V:`${g}${D}${V}`,d0={...process.env,[j]:"true",PATH:r$},T$=e$(this.$,d0),sJ={...S,$:T$,installedDir:g,binaryPaths:y,version:O$,installEnv:d0};await this.hookLifecycle.executeAfterInstallHook(Y,sJ,X,u),await this.installationStateWriter.recordInstallation($,Y,g,S,E,u)}return E}catch(m){return E={success:!1,error:m instanceof Error?m.message:String(m),installationMethod:Y.installationMethod},Q.error(W(E.error)),E}}catch(Z){let q={success:!1,error:Z instanceof Error?Z.message:String(Z),installationMethod:Y.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,G,Y=e$(this.$,process.env),X){let Z=G.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:M,timestamp:J,toolConfig:Q,parentLogger:Z,$shell:Y,installEnv:X})}getSystemInfo(){return this.systemInfo}}import{z as yM}from"zod";var d$={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 CX=yM.object({name:yM.string(),versions:yM.object({stable:yM.string(),head:yM.string().optional(),bottle:yM.boolean().optional()})});async function p6($,M,J,Q,G,Y,X){let Z=G.getSubLogger({name:"installFromBrew"});if(Z.debug(d$.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 fX(I,U,K,Q?.force,Z,Y,_);let O=await uX(I,Z,Y),B=e(M.binaries,`${O}/bin`),j,V=B[0];if(q.versionArgs&&q.versionRegex&&V)j=await D$({binaryPath:V,args:q.versionArgs,regex:q.versionRegex,shellExecutor:Y});else j=await dX(I,Z,Y);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:I,isCask:U,tap:K}}})}async function dX($,M,J){try{M.debug(d$.fetchingVersion($));let G=(await J`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),Y=JSON.parse(G),X=yM.array(CX).parse(Y);if(X.length>0&&X[0]?.versions.stable){let Z=X[0].versions.stable,q=j$(Z);return M.debug(d$.versionFetched($,q)),q}M.debug(d$.versionNotFound($));return}catch(Q){M.debug(d$.versionFetchFailed($),Q);return}}async function uX($,M,J){try{let G=(await J`brew --prefix ${$}`.quiet()).stdout.toString().trim();return M.debug(d$.prefixFetched($,G)),G}catch(Q){M.debug(d$.prefixFetchFailed($),Q);let Y=`${(await J`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return M.debug(d$.prefixFallback($,Y)),Y}}async function fX($,M,J,Q,G,Y,X){if(J){let q=Array.isArray(J)?J:[J];for(let I of q)G.debug(d$.executingCommand(`brew tap ${I}`)),await Y`brew tap ${I}`.quiet()}let Z=["install"];if(M)Z.push("--cask");if(Q)Z.push("--force");Z.push($),G.info(d$.executingCommand(`brew ${Z.join(" ")}`)),await X`brew ${Z}`}import{z as QM}from"zod";var XJ=r.extend({formula:QM.string().optional(),cask:QM.boolean().optional(),tap:QM.union([QM.string(),QM.array(QM.string())]).optional(),versionArgs:QM.array(QM.string()).optional(),versionRegex:QM.string().optional()});import{z as pX}from"zod";var c6=t.extend({installationMethod:pX.literal("brew"),installParams:XJ});var cX="1.0.0";class bQ{shell;method="brew";displayName="Homebrew Installer";version=cX;paramsSchema=XJ;toolConfigSchema=c6;constructor($){this.shell=$}externallyManaged=!0;async install($,M,J,Q,G){let Y=await p6($,M,J,Q,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as hX}from"smol-toml";import{z as u$}from"zod";class J0 extends Error{statusCode;cause;constructor($,M,J){super($);if(this.name="CargoClientError",this.statusCode=M,this.cause=J,Error.captureStackTrace)Error.captureStackTrace(this,J0)}}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 mX=u$.object({package:u$.object({name:u$.string(),version:u$.string(),edition:u$.string().optional(),description:u$.string().optional(),authors:u$.array(u$.string()).optional(),license:u$.string().optional(),repository:u$.string().optional(),homepage:u$.string().optional()})});class vQ{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,M,J,Q,G){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=J,this.cratesIoCache=Q,this.githubRawCache=G,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:G,cacheKey:Y,cacheTtl:X}=this.resolveCacheOptions($,M),Z=await this.tryReadCache(Y,G);if(Z)return Z;let q=await this.performDownload($,Q),I=this.parseJson(q,$);return await this.tryStoreCache(Y,I,X,G),I}resolveCacheOptions($,M){if(!M)return{useCache:!1,cacheTtl:0};let J=M.kind,Q=J==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,G=J==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,Y=Q?`cargo:${J}:${$}`:void 0;return{useCache:Q,cacheKey:Y,cacheTtl:G}}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 G=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!Q||!$||!G)return;try{await G.set($,M,J)}catch{}}parseJson($,M){let J=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw J.error(b$.errors.emptyResponse(M)),new I$(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 J0(`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 I$(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 G=await this.tryReadCache(Q,J);if(G)return G}try{let G=await this.downloader.download(M,$,{headers:this.buildRequestHeaders()});if(!G||G.length===0)return M.error(b$.errors.emptyResponse($)),null;let Y=this.parseCargoToml(G);return await this.tryStoreCache(Q,Y,this.githubRawCacheTtl,J),Y}catch(G){if(G instanceof J0)throw G;if(G instanceof S$)return null;throw M.error(b$.parsing.cargoTomlParseError($),G),G}}parseCargoToml($){let M=this.logger.getSubLogger({name:"parseCargoToml"}),J=$.toString("utf-8"),Q=hX(J),G=mX.safeParse(Q);if(!G.success)throw M.zodErrors(G.error),new J0("Could not parse version from Cargo.toml [package] section",void 0);return G.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import gX from"path";var K$={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 h6($,M,J,Q,G,Y,X,Z,q,I,U){let K=I.getSubLogger({name:"installFromCargo"});if(K.debug(K$.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$(G,$),j=await lX(_,H,X,K);K.debug(K$.foundVersion(_,j.version));let V=await sX(_,j.version,H,J,U);K.debug(K$.downloadingAsset(`${_}-${j.version}`,V));let D=`${_}-${j.version}.tar.gz`,A=gX.join(J.stagingDir,D);await U$(K,V,A,D,Y,Q);let b={...J,version:j.version},k=await nX(M,q,b,A,B,K);if(!k.success)return k;let S=await Z.extract(K,A,{targetDir:J.stagingDir});K.debug(K$.archiveExtracted(),S),await DM(G,$,M,J,J.stagingDir,K);let u=await iX(M,q,b,S,B,K);if(!u.success)return u;if(await G.exists(A))await G.rm(A),K.debug(K$.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 nX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-download"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,downloadPath:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterDownload",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function iX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-install"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,extractResult:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterInstall",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function lX($,M,J,Q){let G=M.versionSource||"cargo-toml";switch(G){case"cargo-toml":{let Y=M.cargoTomlUrl||J.buildCargoTomlUrl(M.githubRepo||`${$}-community/${$}`);Q.debug(K$.parsingMetadata(Y));let X=await J.getCargoTomlPackage(Y);if(!X)throw Error(`Failed to fetch or parse Cargo.toml from ${Y}`);return{version:j$(X.version)}}case"crates-io":{Q.debug(K$.queryingCratesIo($));let Y=await J.getLatestVersion($);if(!Y)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(Y)}}case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases version source");return aX(M.githubRepo,Q)}default:throw Error(`Unknown version source: ${G}`)}}async function aX($,M){throw M.debug(K$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function sX($,M,J,Q,G){let Y=J.binarySource||"cargo-quickinstall",X=rX(Q.systemInfo.platform),Z=tX(Q.systemInfo.arch);switch(Y){case"cargo-quickinstall":return`${G}/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`${G}/${J.githubRepo}/releases/download/v${M}/${I}`}default:throw Error(`Unknown binary source: ${Y}`)}}function rX($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function tX($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as Q0}from"zod";var ZJ=r.extend({crateName:Q0.string(),binarySource:Q0.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:Q0.string().optional(),assetPattern:Q0.string().optional(),versionSource:Q0.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:Q0.string().optional()});import{z as oX}from"zod";var m6=t.extend({installationMethod:oX.literal("cargo"),installParams:ZJ});var eX="1.0.0";class NQ{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=eX;paramsSchema=ZJ;toolConfigSchema=m6;constructor($,M,J,Q,G,Y){this.fs=$;this.downloader=M;this.cargoClient=J;this.archiveExtractor=Q;this.hookExecutor=G;this.githubHost=Y}async install($,M,J,Q,G){let Y=await h6($,M,J,Q,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,G,this.githubHost);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}async resolveVersion($,M,J,Q){let G=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.crateName;if(!X)return G.debug(K$.versionResolutionFailed($,"Missing crateName in install params")),null;let Z=await this.cargoClient.getLatestVersion(X);if(!Z)return G.debug(K$.versionResolutionFailed($,`Could not fetch version for crate: ${X}`)),null;let q=AM(Z);return G.debug(K$.versionResolutionResolved($,q)),q}catch(Y){return G.debug(K$.versionResolutionException($,Y)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let Y=M.installParams?.crateName;if(!Y)return{success:!1,error:"Missing crateName in install params"};let X=await this.cargoClient.getLatestVersion(Y);if(!X)return{success:!1,error:`Could not fetch latest version for crate: ${Y}`};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(G){return Q.error(K$.updateCheckFailed($),G),{success:!1,error:G instanceof Error?G.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 $8($,M,J,Q){let G=GJ($.binaries);for(let Y of G){let X=WJ.join(M.stagingDir,Y);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,Y);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(Y,`${M.stagingDir}, ${Z.join(", ")}`))}}async function g6($,M,J,Q,G,Y,X,Z,q,I){let U=q$(G,$),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 U$(K,_,j,`${$}-install.sh`,Y,Q),await U.chmod(j,493);let V={...J,downloadPath:j},D=await w$(M,V,X,G,K);if(!D.success)return D;K.debug(GM.executingScript(O));let A={projectConfig:J.projectConfig,scriptPath:j,stagingDir:J.stagingDir},b=H.args?await wM(A,H.args):[],k=H.env?await wM(A,H.env):{},S={...process.env,...k},u=I??W$({logger:K,skipCommandLog:!0}),i="";if(O==="bash"){let y=await u`bash ${j} ${b}`.env(S);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
70
70
|
`)}else{let y=await u`sh ${j} ${b}`.env(S);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
71
71
|
`)}await $8(M,J,G,K);let E=e(M.binaries,J.stagingDir),m=[];for(let y of E)if(await G.exists(y))m.push(y);if(m.length===0){let y=E.join(", ");if(K.error(GM.noBinariesInstalled(y)),i.trim()){K.error(GM.scriptOutput());for(let O$ of i.trim().split(`
|
|
72
72
|
`))K.error(W(O$))}return{success:!1,error:`Installation script completed but no binaries were found at expected locations: ${y}`}}let $$,g=E[0];if(g)$$=await D$({shellExecutor:q,binaryPath:g,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 n6=t.extend({installationMethod:IJ.literal("curl-script"),installParams:qJ,binaries:IJ.array(IJ.union([IJ.string().min(1),Z$])).min(1)});var M8="1.0.0";class yQ{fs;downloader;hookExecutor;shell;method="curl-script";displayName="Curl Script Installer";version=M8;paramsSchema=qJ;toolConfigSchema=n6;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,G){let Y=await g6($,M,J,Q,this.fs,this.downloader,this.hookExecutor,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,metadata:Y.metadata,version:Y.version}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import J8 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 i6($,M,J,Q,G,Y,X,Z,q,I){let U=q$(G,$),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=J8.join(J.stagingDir,`${$}.tar.gz`);await U$(K,B,V,`${$}.tar.gz`,Y,Q),H={...J,downloadPath:V};let D=await w$(M,H,Z,G,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 b=await eM(M,_,Z,G,K);if(!b.success)return{success:!1,error:b.error};if(await DM(U,$,M,J,J.stagingDir,K),await U.exists(V))K.debug(G0.cleaningArchive(V)),await U.rm(V);let k=e(M.binaries,J.stagingDir),S,u=k[0];if(u)S=await D$({binaryPath:u,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});return{success:!0,binaryPaths:k,metadata:{method:"curl-tar",downloadUrl:B,tarballUrl:B},version:S||(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 l6=t.extend({installationMethod:HJ.literal("curl-tar"),installParams:KJ,binaries:HJ.array(HJ.union([HJ.string().min(1),Z$])).min(1)});var Q8="1.0.0";class PQ{fs;downloader;archiveExtractor;hookExecutor;shell;method="curl-tar";displayName="Curl Tar Installer";version=Q8;paramsSchema=KJ;toolConfigSchema=l6;constructor($,M,J,Q,G){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=G}async install($,M,J,Q,G){let Y=await i6($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function a6($){let M=/\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?/,J=$.match(M);if(!J||J.index===void 0)return"";return $.slice(0,J.index)}function s6($){let M=/(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)/,J=$.match(M);if(!J)return $;let Q=J[1];if(!Q)return $;return Q}function r6($,M){let J=a6($),Q=s6(M);return`${J}${Q}`}import G8 from"crypto";import CQ 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 G=this.logger.getSubLogger({name:"constructor"});if(G.debug(z.ghCli.initialized(this.hostname)),this.cache&&this.cacheEnabled)G.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)G.debug(z.cache.disabled());else G.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),G=await this.tryGetFromCache(Q,M,$);if(G)return G;J.debug(z.ghCli.executing($));let Y=this.buildGhApiArgs($,M);try{let X=await this.executeGhCommand($,Y);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(" "),G=await this.shell(Q).quiet().noThrow();if(G.code!==0)throw J.debug(z.ghCli.commandFailed(G.code)),this.parseGhError(G.stderr,G.code,$);try{return JSON.parse(G.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 G=await this.cache.get($);if(G)return Q.debug(z.ghCli.cacheHit(J)),G;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(G){if(G instanceof a&&G.statusCode===404)return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),G),G}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let G=J?.perPage||30,Y=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${G}&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<G)q=!1;if(Y!==void 0&&Z.length>=Y)Z=Z.slice(0,Y),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 G=null,Y=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,G,Y);if(U.release)G=U.release,Y=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,G),G}async fetchReleasesPage($,M,J,Q,G){let Y=`/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(Y)}catch(Z){return X.debug(z.errors.constraintError(G,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let G=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Y=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))Y=Z,X=q,G.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:Y,version:X}}isVersionSatisfying($,M){return Boolean(CQ.valid($))&&CQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||CQ.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 Y=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(Y.length)),Y}catch(G){return Q.debug(z.releases.fetchTagsError($,M),G),[]}}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,G){let Y=this.logger.getSubLogger({name:"downloadAsset"});Y.debug(z.ghCli.downloadingAsset(Q,`${$}/${M}`,J));let X=G.substring(0,G.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 Y.debug(z.ghCli.downloadFailed(Q,I.code)),new a(`gh release download failed for ${Q}: ${I.stderr.trim()||`exit code ${I.code}`}`,void 0);Y.debug(z.ghCli.downloadComplete(Q))}}import Y8 from"crypto";import dQ 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 G=this.logger.getSubLogger({name:"constructor"});if(G.debug(z.constructor.initialized(this.baseUrl,this.userAgent)),this.githubToken)G.debug(z.constructor.authTokenPresent());else G.debug(z.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)G.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)G.debug(z.cache.disabled());else G.debug(z.cache.missing())}generateCacheKey($,M){let J=`${M}:${$}`;if(this.githubToken&&typeof this.githubToken==="string"&&this.githubToken.length>0){let Q=Y8.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}${$}`,G=this.generateCacheKey($,M),Y=await this.tryGetFromCache(G,M);if(Y)return Y;J.debug(z.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(G,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 I$(this.logger,"Empty response received from API",$);let G=Q.toString("utf-8");return JSON.parse(G)}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 zM)return this.handleRateLimitError($,M);if($ instanceof bM)return this.handleForbiddenError($,M);if($ instanceof vM)return this.handleClientError($,M);if($ instanceof NM)return this.handleServerError($,M);if($ instanceof E$)return this.handleHttpError($,M);if($ instanceof I$)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(G){if(G instanceof Error&&G.message.includes("GitHub resource not found"))return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),G),G}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let G=J?.perPage||30,Y=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${G}&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<G)q=!1;if(Y!==void 0&&Z.length>=Y)Z=Z.slice(0,Y),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 G=null,Y=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,G,Y);if(U.release)G=U.release,Y=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,G),G}async fetchReleasesPage($,M,J,Q,G){let Y=`/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(Y)}catch(Z){return X.debug(z.errors.constraintError(G,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let G=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Y=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))Y=Z,X=q,G.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:Y,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 Y=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(Y.length)),Y}catch(G){return Q.debug(z.releases.fetchTagsError($,M),G),[]}}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 Y=(await fetch(Q,{method:"HEAD",redirect:"manual"})).headers.get("location");if(!Y)return J.debug(z.tagPattern.noRedirect($,M)),null;let Z=Y.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(G){return J.debug(z.tagPattern.probeFailed($,M),G),null}}}function uQ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t6($){let M=$.system.length>0?`(${$.system.map(uQ).join("|")})`:"",J=$.cpu.length>0?`(${$.cpu.map(uQ).join("|")})`:"",Q=$.variants.length>0?`(${$.variants.map(uQ).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 o6($){let M=OJ($);return t6(M)}var X8=[/\.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 Z8($){let M=$.filter((J)=>!X8.some((Q)=>Q.test(J)));return M.length>0?M:$}function W8($,M){let J=new RegExp(M,"i"),Q=$.filter((G)=>J.test(G.toLowerCase()));return Q.length>0?Q:$}function jJ($,M){let J=o6(M),Q=OJ(M),G=Z8($),Y;if(J.systemPattern){let Z=new RegExp(J.systemPattern,"i");Y=G.filter((q)=>Z.test(q.toLowerCase()))}else Y=[...G];if(Y.length===0)return;let X=[];if(J.cpuPattern)X.push(J.cpuPattern);X.push(...Q.variants);for(let Z of X){if(Y.length<=1)break;Y=W8(Y,Z)}return Y[0]}import U8 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 q8}from"minimatch";function I8($){return/^[dgimsuvy]*$/.test($)}function e6($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function $Y($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!I8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function MY($){if(!e6($))return!0;try{return $Y($),!0}catch{return!1}}function JY($){if(typeof $==="string")return $;return $.toString()}function QY($,M){if(typeof M==="string"){if(e6(M))return $Y(M).test($);return q8($,M)}return M.test($)}async function YY($,M,J,Q,G,Y,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 fQ(V.data,H,J,K);if(!D.success)return D;let A=O8(D.data.browser_download_url,q,K);if(!A.success)return A;let b=U8.join(J.stagingDir,D.data.name),k=await B8(A.data,D.data,Y,X,B,j,V.data.tag_name,b,Q,K);if(!k.success)return k;let S={...J,downloadPath:k.data.downloadPath},u=await D8(M,S,I,G,K);if(!u.success)return u;let i=j$(V.data.tag_name),E=await A8(D.data,k.data.downloadPath,$,M,J,S,G,Z,I,G,K);if(!E.success)return E;let m=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:m,version:i,originalTag:V.data.tag_name,metadata:$$}}catch(V){return{success:!1,error:V instanceof Error?V.message:String(V)}}}var K8=5;async function A0($,M,J,Q,G){let Y=G.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(Y.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}}Y.debug(P.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};let I=await H8(X,Z,M,Q,Y);if(I)return{success:!0,data:I};return await _8(X,Z,Q,Y),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function H8($,M,J,Q,G){let Y=G.getSubLogger({name:"fetchWithTagPatternDetection"});Y.debug(P.detectingTagPattern());let X=await Q.probeLatestTag($,M);if(!X)return Y.debug(P.tagPatternDetectionFailed()),null;let Z=r6(X,J);if(Z!==J){Y.debug(P.tryingCorrectedTag(Z,J));let q=await Q.getReleaseByTag($,M,Z);if(q)return Y.info(P.usingCorrectedTag(Z,J)),q}return null}async function _8($,M,J,Q){let G=Q.getSubLogger({name:"showAvailableReleaseTags"}),Y=await J.getLatestReleaseTags($,M,K8);if(Y.length===0){G.error(P.noReleaseTagsAvailable());return}G.info(P.availableReleaseTags());for(let X of Y)G.info(P.releaseTagItem(X))}async function fQ($,M,J,Q){let G;if(M.assetSelector){Q.debug(P.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};G=M.assetSelector(X)}else if(M.assetPattern){Q.debug(P.assetPatternMatch(JY(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>QY(q.name,X));if(G=GY(Z,J.systemInfo),!G&&Z.length>0)G=Z[0]}else Q.debug(P.assetPlatformMatch(t$(J.systemInfo.platform),o$(J.systemInfo.arch))),G=GY($.assets,J.systemInfo);if(!G)return{success:!1,error:R8($,M,J)};return{success:!0,data:G}}function GY($,M){let J=$.map((G)=>G.name),Q=jJ(J,M);if(!Q)return;return $.find((G)=>G.name===Q)}function R8($,M,J){let Q=$.assets.map((q)=>q.name),G=t$(J.systemInfo.platform),Y=o$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${G}/${Y}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${G}/${Y}.`;else X=`for platform "${G}" and architecture "${Y}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
|
|
@@ -220,7 +220,7 @@ ${A}`)}return D.data}async function h1($){return XQ.parse({})}async function pY(
|
|
|
220
220
|
fi
|
|
221
221
|
fi
|
|
222
222
|
`);X.debug(H$.generateShim.generatedContent(Q)),await this.fs.ensureDir(FG.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(H$.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 xG 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 TG{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 G in $){let Y=$[G];if(!Y)continue;let X=G$(Y,this.systemInfo);if(!this.shouldProcessTool(X,G,J))continue;let Z=J.getSubLogger({context:G}),q=this.fs instanceof f?this.fs.withToolName(G):this.fs;Z.debug(h.copy.processingTool(G));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,G){let Y=G.getSubLogger({name:"processCopy"}),{overwrite:X=!1,backup:Z=!1}=Q,q=_M($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=_M($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(Y.debug(h.copy.copyDetails(M.source,q,M.target,I)),!await J.exists(q))return Y.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(Y.debug(h.copy.targetExists(I)),!X)return Y.debug(h.copy.skipExistingTarget(I)),{success:!0,sourcePath:q,targetPath:I,status:"skipped_exists"};let K=await this.handleOverwrite(I,J,Z,Y);if(K.failed)return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:K.error};return this.performCopy(q,I,J,K.status,Y)}return this.performCopy(q,I,J,"created",Y)}async handleOverwrite($,M,J,Q){if(J){let G=`${$}.bak`;try{if(await M.exists(G))await M.rm(G,{recursive:!0,force:!0});return await M.rename($,G),{failed:!1,status:"backed_up"}}catch{let Y=h.filesystem.backupFailed($);return Q.error(Y),{failed:!0,error:Y}}}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 G=h.filesystem.deleteFailed($);return Q.error(G),{failed:!0,error:G}}}async performCopy($,M,J,Q,G){let Y=G.getSubLogger({name:"performCopy"}),X=xG.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return Y.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 Y.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 G of Q){let Y=xG.join($,G),X=xG.join(M,G);if((await J.stat(Y)).isDirectory())await this.copyDirectory(Y,X,J);else await J.copyFile(Y,X)}}}import a$ from"path";class kG{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 Y=await this.fs.readlink(J),X=a$.resolve(a$.dirname(J),Y),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 G in $){let Y=$[G];if(!Y)continue;let X=G$(Y,this.systemInfo);if(!this.shouldProcessTool(X,G,J))continue;let Z=J.getSubLogger({context:G}),q=this.fs instanceof f?this.fs.withToolName(G):this.fs;Z.debug(h.generate.processingTool(G));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,G){let Y=G.getSubLogger({name:"processSymlink"}),{overwrite:X=!1,backup:Z=!1}=Q,q=_M($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=_M($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(Y.debug(h.process.symlinkDetails(M.source,q,M.target,I),M.source,q,M.target,I),!await J.exists(q))return Y.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},Y);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,Y)}async handleExistingTarget($,M,J,Q,G){let Y=G.getSubLogger({name:"handleExistingTarget"});if(!await J.exists(M)){let q=await this.removeBrokenSymlink(M,J,Y);if(q.failed)return{shouldSkip:!0,status:"failed",error:q.error};return{shouldSkip:!1,status:"created"}}if(Y.debug(h.process.targetExists(M)),(await this.checkCorrectSymlink($,M,J)).isCorrect)return{shouldSkip:!0,status:"skipped_correct"};if(!Q.overwrite)return Y.debug(h.process.skipExistingTarget(M)),{shouldSkip:!0,status:"skipped_exists"};return await this.handleOverwrite(M,J,Q.backup,Y)}async checkCorrectSymlink($,M,J){try{if((await J.lstat(M)).isSymbolicLink()){let G=await J.readlink(M),Y=a$.resolve(a$.dirname(M),G),X=a$.resolve($);return{isCorrect:Y===X}}}catch{}return{isCorrect:!1}}async handleOverwrite($,M,J,Q){let G=Q.getSubLogger({name:"handleOverwrite"}),Y="updated_target";if(J){let X=await this.createBackup($,M,G);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error};Y="backed_up"}else{let X=await this.deleteTarget($,M,G);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error}}return{shouldSkip:!1,status:Y}}async createBackup($,M,J){let Q=J.getSubLogger({name:"createBackup"}),G=`${$}.bak`;try{if(await M.exists(G))await M.rm(G,{recursive:!0,force:!0});return await M.rename($,G),{failed:!1}}catch{let Y=h.filesystem.backupFailed($);return Q.error(Y),{failed:!0,error:Y}}}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 G=h.filesystem.deleteFailed($);return Q.error(G),{failed:!0,error:G}}}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,G){let Y=G.getSubLogger({name:"createSymlink"}),X=a$.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return Y.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 Y.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}}import{eq as j4,gt as V4,valid as M9}from"semver";var N$={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 SG{githubClient;logger;constructor($,M){this.logger=$.getSubLogger({name:"VersionChecker"}),this.logger.debug(N$.initializing()),this.githubClient=M}async getLatestToolVersion($,M){let J=this.logger.getSubLogger({name:"getLatestToolVersion"});J.debug(N$.fetchingLatestRelease($,M));try{let Q=await this.githubClient.getLatestRelease($,M);if(Q?.tag_name){let G=Q.tag_name.replace(/^v/,"");return J.debug(N$.latestReleaseFound(G)),G}return J.debug(N$.noLatestRelease($,M)),null}catch(Q){return J.debug(N$.latestReleaseError($,M),Q),null}}async checkVersionStatus($,M){let J=this.logger.getSubLogger({name:"checkVersionStatus"});J.debug(N$.comparingVersions($,M));let Q=$.replace(/^v/,""),G=M.replace(/^v/,"");if(!M9(Q))return J.debug(N$.invalidConfiguredVersion(Q)),"INVALID_CURRENT_VERSION";if(!M9(G))return J.debug(N$.invalidLatestVersion(G)),"INVALID_LATEST_VERSION";if(V4(G,Q))return J.debug(N$.versionComparisonResult("NEWER_AVAILABLE")),"NEWER_AVAILABLE";if(j4(G,Q))return J.debug(N$.versionComparisonResult("UP_TO_DATE")),"UP_TO_DATE";return J.debug(N$.versionComparisonResult("AHEAD_OF_LATEST")),"AHEAD_OF_LATEST"}}import G5 from"net";import K0 from"path";import{realpath as z4}from"fs/promises";import B4 from"path";var J9={name:"bin",description:"Print the real path to a binary",hasPositionalArg:!0,positionalArgDescription:"binary name",positionalArgType:"tool"};async function D4($,M,J,Q,G,Y,X){let Z=await Y.loadSingleToolConfig($,M,J,Q,G,X);if(Z){let K=(G$(Z,X).binaries??[])[0],H=K?typeof K==="string"?K:K.name:M;return{toolName:M,binaryName:H}}let q=await Y.loadToolConfigByBinary($,M,J,Q,G,X);if(q&&!("error"in q))return{toolName:q.name,binaryName:M};return}async function A4($,M,J){let{projectConfig:Q,fs:G,configService:Y,systemInfo:X}=J,Z=$.getSubLogger({minLevel:7}),q=await D4(Z,M,Q.paths.toolConfigsDir,G,Q,Y,X);if(!q)return x.ERROR;let{toolName:I,binaryName:U}=q,K=B4.join(Q.paths.binariesDir,I,"current",U);try{let H=await z4(K);return process.stdout.write(H),x.SUCCESS}catch{return x.ERROR}}function Q9($,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(G)=>{let Y=await J(),X=await A4(Q,G,Y);v(X)})}import G9 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,G)=>W(`${$} ${M} [${J}] - ${Q}${G}`),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 Y9={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function E4($,M,J,Q,G,Y){let X={};if(J){$.debug(R.commandCheckingUpdatesFor(J));try{let Z=await M.loadSingleToolConfig($,J,Q.paths.toolConfigsDir,G,Q,Y);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,G,Q,Y),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 F4($,M,J,Q,G){let Y=new Date().toISOString().replace(/:/g,"-").split(".")[0],X=$.configFilePath?G9.dirname($.configFilePath):M.paths.toolConfigsDir,Z=G9.join(M.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:X,currentDir:Z,stagingDir:"",timestamp:Y||"",systemInfo:J,toolConfig:$,projectConfig:M,$:e$(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:qQ(G,$.name)}}async function L4($,M,J,Q,G,Y){if(Q==="latest"){$.info(R.toolConfiguredToLatest(J.name,G));return}if(Y){$.info(R.toolUpdateAvailable(J.name,Q,G));return}let X=await M.checkVersionStatus(Q,G);if(X==="UP_TO_DATE")$.info(R.toolUpToDate(J.name,Q,G));else if(X==="AHEAD_OF_LATEST")$.info(R.toolAheadOfLatest(J.name,Q,G));else $.warn(R.toolVersionComparisonFailed(J.name,Q,G))}async function x4($,M,J){let{projectConfig:Q,versionChecker:G,pluginRegistry:Y,systemInfo:X,fs:Z}=J,q=F4(M,Q,X,Z,$),I=Y.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 L4($,G,M,K,H,U.hasUpdate)}async function T4($,M,J){$.trace(R.commandActionStarted("check-updates",M||"all"));let Q=await E4($,J.configService,M,J.projectConfig,J.fs,J.systemInfo);if(!Q)return;for(let G of Object.values(Q))await x4($,G,J)}function X9($,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(G)=>{try{let Y=await J();await T4(Q,G,Y)}catch(Y){Q.error(R.commandExecutionFailed("check-updates",x.ERROR),Y),v(x.ERROR)}})}var Z9={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 k4($,M,J,Q,G){$.info(R.cleanupAllTrackedFiles());let Y=await J.getRegisteredTools();for(let X of Y)await W9($,M,J,X,Q,void 0,G);if(!G){for(let X of Y)await J.removeToolOperations(X);$.info(R.cleanupRegistryDatabase())}else $.info(R.cleanupRegistryDryRun())}async function S4($,M,J,Q,G,Y,X){if($.info(R.cleanupToolFiles(Q)),await W9($,M,J,Q,G,Y,X),!X)await J.removeToolOperations(Q),$.info(R.cleanupRegistryTool(Q,!1));else $.info(R.cleanupRegistryTool(Q,!0))}async function w4($,M,J,Q,G,Y){$.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 q9($,M,Z.filePath,G,Y)}}async function b4($,M,J){let{fs:Q,fileRegistry:G}=M,{dryRun:Y,tool:X,type:Z,all:q}=J,I=M.projectConfig.paths.homeDir;if(q)await k4($,Q,G,I,Y);else if(X)await S4($,Q,G,X,I,Z,Y);else if(Z)await w4($,Q,G,Z,I,Y);else $.warn(R.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function W9($,M,J,Q,G,Y,X){let Z=await J.getFileStatesForTool(Q),q=Z;if(Y)q=Z.filter((I)=>I.fileType===Y);$.trace(R.cleanupFoundFiles(q.length,Q,Y));for(let I of q)if(I.lastOperation!=="rm"){let U=I.fileType==="symlink"&&I.targetPath?I.targetPath:I.filePath;await q9($,M,U,G,X||!1)}}async function q9($,M,J,Q,G){try{if(await M.exists(J))if(!G)await M.rm(J,{force:!0}),$.info(R.cleanupFileRemoved(s(Q,J)));else $.info(R.fileCleanupDryRun(J));else $.debug(R.cleanupFileNotFound(J))}catch(Y){$.error(R.cleanupDeleteFailed(J),Y)}}async function v4($,M,J){let{dryRun:Q,tool:G,type:Y,all:X}=M;try{$.trace(R.cleanupProcessStarted(Q),M);let Z={...M,all:X||!G&&!Y};await b4($,J,Z),$.trace(R.cleanupProcessFinished(Q))}catch(Z){$.error(R.commandExecutionFailed("cleanup",1),Z),v(1)}}function I9($,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(G)=>{let Y={...G,...M.opts()},X=await J();await v4(Q,Y,X)})}import{Command as N4}from"commander";var U9={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 K9(){return new N4().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.2").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 (${ZQ.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 s4 from"fs";import r4 from"path";var w={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 y4($){let M=[];if($&1)M.push("Linux");if($&2)M.push("macOS");if($&4)M.push("Windows");return M}function P4($){let M=[];if($&1)M.push("x86_64");if($&2)M.push("arm64");return M}function H9($){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 C4($){let M={};if("installParams"in $&&$.installParams){let Q=$.installParams;Object.assign(M,H9(Q))}let J;if($.platformConfigs&&$.platformConfigs.length>0)J=$.platformConfigs.map((Q)=>{let G={platforms:y4(Q.platforms)};if(Q.architectures!==void 0)G.architectures=P4(Q.architectures);let Y=Q.config;if(Y.installationMethod)G.installationMethod=Y.installationMethod;if(Y.installParams)G.installParams=H9(Y.installParams);if(Y.binaries)G.binaries=Y.binaries;if(Y.symlinks)G.symlinks=Y.symlinks;return G});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:M,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:J}}function d4($,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 _9($,M,J,Q,G,Y){return{config:C4($),runtime:d4($.name,M),files:J,binaryDiskSize:G,usage:Y}}function y$($){return new Date($).toISOString()}function U0($){let J=Date.now()-$,Q=Math.floor(J/1000);if(Q<60)return"just now";let G=Math.floor(Q/60);if(G<60)return`${G} minute${G===1?"":"s"} ago`;let Y=Math.floor(G/60);if(Y<24)return`${Y} hour${Y===1?"":"s"} ago`;let X=Math.floor(Y/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 R9($,M,J=20){try{let G=(await M.fileRegistry.getOperations()).toSorted((Z,q)=>q.createdAt-Z.createdAt),Y=G.length;return{success:!0,data:{activities:G.slice(0,J).map((Z)=>({id:Z.id,toolName:Z.toolName,action:Z.operationType,description:`${Z.operationType} ${Z.fileType}: ${Z.filePath}`,timestamp:y$(Z.createdAt),relativeTime:U0(Z.createdAt)})),totalCount:Y}}}catch(Q){return $.error(w.apiError("getActivity"),Q),{success:!1,error:"Failed to retrieve activity feed"}}}async function O9($,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(w.apiError("getConfig"),J),{success:!1,error:"Failed to retrieve configuration"}}}import y0 from"path";async function u4($){let{fs:M,projectConfig:J}=$,Q=J.paths.binariesDir,G=[];if(!await M.exists(Q))return[];let Y=await M.readdir(Q);for(let X of Y){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!==_)G.push(_)}}return G}async function j9($,M){try{let J=[],Q=await u4(M);if(Q.length>0)J.push({name:"Unused Binaries",status:"warn",message:"",details:Q});let Y=await M.fileRegistry.validate();J.push({name:"Registry Integrity",status:Y.valid?"pass":"warn",message:Y.valid?"Registry is healthy":`Found ${Y.issues.length} issues`,details:Y.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(w.apiError("getHealth"),J),{success:!1,error:"Failed to retrieve health status"}}}import wG from"path";async function V9($,M){let J=$.fs,Q=0;try{if(!await J.exists(M))return 0;let G=await J.readdir(M);for(let Y of G){let X=wG.join(M,Y),Z=await J.stat(X);if(Z.isDirectory())Q+=await V9($,X);else if(Z.isFile())Q+=Z.size}}catch{}return Q}async function bG($,M){let J=wG.join($.projectConfig.paths.generatedDir,"binaries"),Q=wG.join(J,M);return V9($,Q)}var hJ=null;async function f4(){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 G=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),Y=await new Response(G.stdout).text();if(await G.exited!==0)return $;let Z=Y.split(`
|
|
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,G)=>W(`${$} ${M} [${J}] - ${Q}${G}`),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 Y9={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function E4($,M,J,Q,G,Y){let X={};if(J){$.debug(R.commandCheckingUpdatesFor(J));try{let Z=await M.loadSingleToolConfig($,J,Q.paths.toolConfigsDir,G,Q,Y);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,G,Q,Y),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 F4($,M,J,Q,G){let Y=new Date().toISOString().replace(/:/g,"-").split(".")[0],X=$.configFilePath?G9.dirname($.configFilePath):M.paths.toolConfigsDir,Z=G9.join(M.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:X,currentDir:Z,stagingDir:"",timestamp:Y||"",systemInfo:J,toolConfig:$,projectConfig:M,$:e$(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:qQ(G,$.name)}}async function L4($,M,J,Q,G,Y){if(Q==="latest"){$.info(R.toolConfiguredToLatest(J.name,G));return}if(Y){$.info(R.toolUpdateAvailable(J.name,Q,G));return}let X=await M.checkVersionStatus(Q,G);if(X==="UP_TO_DATE")$.info(R.toolUpToDate(J.name,Q,G));else if(X==="AHEAD_OF_LATEST")$.info(R.toolAheadOfLatest(J.name,Q,G));else $.warn(R.toolVersionComparisonFailed(J.name,Q,G))}async function x4($,M,J){let{projectConfig:Q,versionChecker:G,pluginRegistry:Y,systemInfo:X,fs:Z}=J,q=F4(M,Q,X,Z,$),I=Y.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 L4($,G,M,K,H,U.hasUpdate)}async function T4($,M,J){$.trace(R.commandActionStarted("check-updates",M||"all"));let Q=await E4($,J.configService,M,J.projectConfig,J.fs,J.systemInfo);if(!Q)return;for(let G of Object.values(Q))await x4($,G,J)}function X9($,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(G)=>{try{let Y=await J();await T4(Q,G,Y)}catch(Y){Q.error(R.commandExecutionFailed("check-updates",x.ERROR),Y),v(x.ERROR)}})}var Z9={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 k4($,M,J,Q,G){$.info(R.cleanupAllTrackedFiles());let Y=await J.getRegisteredTools();for(let X of Y)await W9($,M,J,X,Q,void 0,G);if(!G){for(let X of Y)await J.removeToolOperations(X);$.info(R.cleanupRegistryDatabase())}else $.info(R.cleanupRegistryDryRun())}async function S4($,M,J,Q,G,Y,X){if($.info(R.cleanupToolFiles(Q)),await W9($,M,J,Q,G,Y,X),!X)await J.removeToolOperations(Q),$.info(R.cleanupRegistryTool(Q,!1));else $.info(R.cleanupRegistryTool(Q,!0))}async function w4($,M,J,Q,G,Y){$.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 q9($,M,Z.filePath,G,Y)}}async function b4($,M,J){let{fs:Q,fileRegistry:G}=M,{dryRun:Y,tool:X,type:Z,all:q}=J,I=M.projectConfig.paths.homeDir;if(q)await k4($,Q,G,I,Y);else if(X)await S4($,Q,G,X,I,Z,Y);else if(Z)await w4($,Q,G,Z,I,Y);else $.warn(R.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function W9($,M,J,Q,G,Y,X){let Z=await J.getFileStatesForTool(Q),q=Z;if(Y)q=Z.filter((I)=>I.fileType===Y);$.trace(R.cleanupFoundFiles(q.length,Q,Y));for(let I of q)if(I.lastOperation!=="rm"){let U=I.fileType==="symlink"&&I.targetPath?I.targetPath:I.filePath;await q9($,M,U,G,X||!1)}}async function q9($,M,J,Q,G){try{if(await M.exists(J))if(!G)await M.rm(J,{force:!0}),$.info(R.cleanupFileRemoved(s(Q,J)));else $.info(R.fileCleanupDryRun(J));else $.debug(R.cleanupFileNotFound(J))}catch(Y){$.error(R.cleanupDeleteFailed(J),Y)}}async function v4($,M,J){let{dryRun:Q,tool:G,type:Y,all:X}=M;try{$.trace(R.cleanupProcessStarted(Q),M);let Z={...M,all:X||!G&&!Y};await b4($,J,Z),$.trace(R.cleanupProcessFinished(Q))}catch(Z){$.error(R.commandExecutionFailed("cleanup",1),Z),v(1)}}function I9($,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(G)=>{let Y={...G,...M.opts()},X=await J();await v4(Q,Y,X)})}import{Command as N4}from"commander";var U9={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 K9(){return new N4().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.4").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 (${ZQ.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 s4 from"fs";import r4 from"path";var w={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 y4($){let M=[];if($&1)M.push("Linux");if($&2)M.push("macOS");if($&4)M.push("Windows");return M}function P4($){let M=[];if($&1)M.push("x86_64");if($&2)M.push("arm64");return M}function H9($){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 C4($){let M={};if("installParams"in $&&$.installParams){let Q=$.installParams;Object.assign(M,H9(Q))}let J;if($.platformConfigs&&$.platformConfigs.length>0)J=$.platformConfigs.map((Q)=>{let G={platforms:y4(Q.platforms)};if(Q.architectures!==void 0)G.architectures=P4(Q.architectures);let Y=Q.config;if(Y.installationMethod)G.installationMethod=Y.installationMethod;if(Y.installParams)G.installParams=H9(Y.installParams);if(Y.binaries)G.binaries=Y.binaries;if(Y.symlinks)G.symlinks=Y.symlinks;return G});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:M,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:J}}function d4($,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 _9($,M,J,Q,G,Y){return{config:C4($),runtime:d4($.name,M),files:J,binaryDiskSize:G,usage:Y}}function y$($){return new Date($).toISOString()}function U0($){let J=Date.now()-$,Q=Math.floor(J/1000);if(Q<60)return"just now";let G=Math.floor(Q/60);if(G<60)return`${G} minute${G===1?"":"s"} ago`;let Y=Math.floor(G/60);if(Y<24)return`${Y} hour${Y===1?"":"s"} ago`;let X=Math.floor(Y/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 R9($,M,J=20){try{let G=(await M.fileRegistry.getOperations()).toSorted((Z,q)=>q.createdAt-Z.createdAt),Y=G.length;return{success:!0,data:{activities:G.slice(0,J).map((Z)=>({id:Z.id,toolName:Z.toolName,action:Z.operationType,description:`${Z.operationType} ${Z.fileType}: ${Z.filePath}`,timestamp:y$(Z.createdAt),relativeTime:U0(Z.createdAt)})),totalCount:Y}}}catch(Q){return $.error(w.apiError("getActivity"),Q),{success:!1,error:"Failed to retrieve activity feed"}}}async function O9($,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(w.apiError("getConfig"),J),{success:!1,error:"Failed to retrieve configuration"}}}import y0 from"path";async function u4($){let{fs:M,projectConfig:J}=$,Q=J.paths.binariesDir,G=[];if(!await M.exists(Q))return[];let Y=await M.readdir(Q);for(let X of Y){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!==_)G.push(_)}}return G}async function j9($,M){try{let J=[],Q=await u4(M);if(Q.length>0)J.push({name:"Unused Binaries",status:"warn",message:"",details:Q});let Y=await M.fileRegistry.validate();J.push({name:"Registry Integrity",status:Y.valid?"pass":"warn",message:Y.valid?"Registry is healthy":`Found ${Y.issues.length} issues`,details:Y.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(w.apiError("getHealth"),J),{success:!1,error:"Failed to retrieve health status"}}}import wG from"path";async function V9($,M){let J=$.fs,Q=0;try{if(!await J.exists(M))return 0;let G=await J.readdir(M);for(let Y of G){let X=wG.join(M,Y),Z=await J.stat(X);if(Z.isDirectory())Q+=await V9($,X);else if(Z.isFile())Q+=Z.size}}catch{}return Q}async function bG($,M){let J=wG.join($.projectConfig.paths.generatedDir,"binaries"),Q=wG.join(J,M);return V9($,Q)}var hJ=null;async function f4(){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 G=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),Y=await new Response(G.stdout).text();if(await G.exited!==0)return $;let Z=Y.split(`
|
|
224
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 p4($){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 G=J.trim().split(`
|
|
225
225
|
`)[0];if(!G)return null;return new Date(G)}catch{return null}}async function vG($){if(!hJ)hJ=await f4();let M=hJ.get($);if(M)return M;let J=await p4($);if(J)hJ.set($,J);return J}var mJ=null;async function _$($,M){if(mJ)return mJ;let{projectConfig:J,fs:Q,configService:G,systemInfo:Y}=M;return mJ=await G.loadToolConfigs($,J.paths.toolConfigsDir,Q,J,Y),mJ}async function z9($,M,J=10){try{let Q=M.projectConfig.paths.toolConfigsDir,G=[];async function Y(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 Y(H);else if(K.endsWith(".tool.ts")){let O=K.replace(/\.tool\.ts$/,"");G.push({name:O,configFilePath:H})}}}return await Y(Q),{success:!0,data:{tools:(await Promise.all(G.map(async(I)=>{let U=await vG(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:y$(I.timestamp),relativeTime:U0(I.timestamp),timestampSource:I.source}))}}}catch(Q){return $.error(w.apiError("getRecentTools"),Q),{success:!1,error:"Failed to retrieve recent tools"}}}async function B9($,M){try{let J=await M.fileRegistry.getOperations({fileType:"completion"}),Q=await M.fileRegistry.getOperations({fileType:"init"}),G=new Map;for(let I of J){let U=G.get(I.filePath);if(!U||I.createdAt>U.createdAt)G.set(I.filePath,I)}let Y=new Map;for(let I of Q){let U=Y.get(I.filePath);if(!U||I.createdAt>U.createdAt)Y.set(I.filePath,I)}let X=Array.from(G.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"completion",lastModified:y$(I.createdAt)})),Z=Array.from(Y.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"init",lastModified:y$(I.createdAt)}));return{success:!0,data:{completions:X,initScripts:Z,totalFiles:X.length+Z.length}}}catch(J){return $.error(w.apiError("getShellIntegration"),J),{success:!1,error:"Failed to retrieve shell integration"}}}async function D9($,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?y$(J.oldestOperation):null,newestOperation:J.newestOperation>0?y$(J.newestOperation):null}}}catch(J){return $.error(w.apiError("getStats"),J),{success:!1,error:"Failed to retrieve statistics"}}}async function A9($,M,J){let Q=$.getSubLogger({name:"checkToolUpdate",context:J});try{let Y=(await _$($,M))[J];if(!Y)return{success:!1,error:`Tool "${J}" not found in configuration`};let X=M.pluginRegistry.get(Y.installationMethod);if(!X||!X.supportsUpdateCheck||!X.supportsUpdateCheck())return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!1,error:`Update checking is not supported for installation method "${Y.installationMethod}"`}};let Z=await X.checkUpdate?.(J,Y,{},Q);if(!Z)return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!1,error:"Update check returned no result"}};if(!Z.success)return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!0,error:Z.error}};return Q.info(w.checkUpdateCompleted(Z.hasUpdate,Z.currentVersion??"unknown",Z.latestVersion??"unknown")),{success:!0,data:{hasUpdate:Z.hasUpdate,currentVersion:Z.currentVersion??Y.version??"unknown",latestVersion:Z.latestVersion??"unknown",supported:!0}}}catch(G){let Y=G instanceof Error?G.message:String(G);return Q.error(w.checkUpdateFailed(Y),G),{success:!1,error:`Failed to check for updates: ${Y}`}}}async function E9($,M){try{let J=M.projectConfig.paths.toolConfigsDir,Q=await _$($,M),G=new Map;for(let Z of Object.values(Q))if(Z.configFilePath)G.set(Z.configFilePath,Z.name);async function Y(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 Y(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:G.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 Y(J);return{success:!0,data:{rootPath:J,entries:X}}}catch(J){return $.error(w.apiError("getToolConfigsTree"),J),{success:!1,error:"Failed to retrieve tool configs tree"}}}async function F9($,M,J){try{let G=(await M.fileRegistry.getOperations({toolName:J})).toSorted((Z,q)=>q.createdAt-Z.createdAt),Y=await M.toolInstallationRegistry.getToolInstallation(J),X=G.map((Z)=>({id:Z.id,operationType:Z.operationType,fileType:Z.fileType,filePath:Z.filePath,timestamp:y$(Z.createdAt),relativeTime:U0(Z.createdAt)}));return{success:!0,data:{entries:X,totalCount:X.length,installedAt:Y?.installedAt.toISOString()??null,dotfilesDir:M.projectConfig.paths.dotfilesDir}}}catch(Q){return $.error(w.apiError("getToolHistory"),Q),{success:!1,error:"Failed to retrieve tool history"}}}async function L9($,M,J,Q){let G=$.getSubLogger({name:"installTool",context:J});try{let X=(await _$($,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 G.error(w.installFailed(Z.error??"Unknown error")),{success:!0,data:{installed:!1,error:Z.error??"Installation failed"}};return G.info(w.installSucceeded()),{success:!0,data:{installed:!0,version:Z.version,alreadyInstalled:Z.installationMethod==="already-installed"}}}catch(Y){let X=Y instanceof Error?Y.message:String(Y);return G.error(w.installFailed(X),Y),{success:!1,error:`Failed to install tool: ${X}`}}}function x9($){if(!$)return null;let M=$.repo;return typeof M==="string"?M:null}function m4($,M){if(M.platform===0)return!1;if(!sM($.platforms,M.platform))return!1;if($.architectures===void 0)return!0;if(M.arch===0)return!1;return rM($.architectures,M.arch)}function g4($,M){let J=x9($.installParams);if(J)return J;for(let Q of $.platformConfigs??[]){if(!m4(Q,M))continue;let G=x9(Q.config?.installParams);if(G)return G}return null}async function T9($,M,J){try{let G=(await _$($,M))[J];if(!G)return{success:!1,error:"Tool not found"};let Y=g4(G,M.systemInfo);if(!Y)return{success:!1,error:"Tool does not have a GitHub repository"};let X=G.version?[G.version,"main","master"]:["main","master"];for(let Z of X){let q=`https://raw.githubusercontent.com/${Y}/${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(w.apiError("getToolReadme"),Q),{success:!1,error:"Failed to retrieve README"}}}async function k9($,M,J){try{let G=(await _$($,M))[J];if(!G)return{success:!1,error:"Tool not found"};let Y=G.configFilePath;if(!Y)return{success:!1,error:"Tool configuration file path not available"};return{success:!0,data:{content:await M.fs.readFile(Y,"utf-8"),filePath:Y}}}catch(Q){return $.error(w.apiError("getToolSource"),Q),{success:!1,error:"Failed to retrieve tool source"}}}async function S9($,M,J){let Q=$.getSubLogger({name:"updateTool",context:J});try{let Y=(await _$($,M))[J];if(!Y)return{success:!1,error:`Tool "${J}" not found in configuration`};if(Y.version!=="latest")return{success:!0,data:{updated:!1,supported:!1,error:`Tool is pinned to version "${Y.version}". Only tools with version "latest" can be updated.`}};let X=M.pluginRegistry.get(Y.installationMethod);if(!X||!X.supportsUpdate())Q.warn(w.updateNotSupported(Y.installationMethod));let q=(await M.toolInstallationRegistry.getToolInstallation(J))?.version??"unknown",I=await M.installer.install(J,Y,{force:!0});if(!I.success)return Q.error(w.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(w.updateSucceeded(q,U)),{success:!0,data:{updated:!0,oldVersion:q,newVersion:U,supported:!0}}}catch(G){let Y=G instanceof Error?G.message:String(G);return Q.error(w.updateFailed(Y),G),{success:!1,error:`Failed to update tool: ${Y}`}}}async function n4($,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 i4($){if(!$.binaries||$.binaries.length===0)return[];return $.binaries.map((M)=>typeof M==="string"?M:M.name)}async function l4($,M,J){let Q=await Promise.all(J.map(async(Y)=>{let X=await $.toolInstallationRegistry.getToolUsage(M,Y);return{binaryName:Y,count:X?.usageCount??0,lastUsedAt:X?.lastUsedAt?X.lastUsedAt.toISOString():null}}));return{totalCount:Q.reduce((Y,X)=>Y+X.count,0),binaries:Q}}async function w9($,M){try{let J=await _$($,M),Q=await M.toolInstallationRegistry.getAllToolInstallations(),G=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 n4(q,M.fs),U=await bG(M,Z.name),K=i4(Z),H=await l4(M,Z.name,K);return _9(Z,G,I,M.systemInfo,U,H)}))).toSorted((Z,q)=>Z.config.name.localeCompare(q.config.name))}}catch(J){return $.error(w.apiError("getTools"),J),{success:!1,error:"Failed to retrieve tools"}}}function b9($,M){let J=$.getSubLogger({name:"api"});return{getTools:()=>w9(J,M),getStats:()=>D9(J,M),getHealth:()=>j9(J,M),getConfig:()=>O9(J,M),getToolConfigsTree:()=>E9(J,M),getShellIntegration:()=>B9(J,M),getActivity:(Q)=>R9(J,M,Q),getToolHistory:(Q)=>F9(J,M,Q),getToolReadme:(Q)=>T9(J,M,Q),getToolSource:(Q)=>k9(J,M,Q),getRecentTools:(Q)=>z9(J,M,Q),installTool:(Q,G)=>L9(J,M,Q,G),checkToolUpdate:(Q)=>A9(J,M,Q),updateTool:(Q)=>S9(J,M,Q)}}var N9=v9("{\"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 t4=import.meta.dir,gJ=!1,o4=gJ&&process.env.DOTFILES_IS_RELOAD==="1";function e4($){let M={};try{let J=s4.readdirSync($);for(let Q of J)if(Q.endsWith(".js")){let G=r4.join($,Q);M[`/${Q}`]=()=>{return new Response(Bun.file(G),{headers:{"Content-Type":"text/javascript"}})}}}catch{}return M}function NG($,M,J){let Q=$.getSubLogger({name:"DashboardServer"}),G=b9(Q,M),Y=null;return{async start(){if(process.env.DOTFILES_IS_RELOAD="1",!gJ)process.chdir(t4);let X=gJ?{}:e4(process.cwd());return Y=Bun.serve({port:J.port,hostname:J.host,development:gJ,routes:{...X,"/api/tools":async()=>{let Z=await G.getTools();return Response.json(Z)},"/api/stats":async()=>{let Z=await G.getStats();return Response.json(Z)},"/api/health":async()=>{let Z=await G.getHealth();return Response.json(Z)},"/api/config":async()=>{let Z=await G.getConfig();return Response.json(Z)},"/api/tool-configs-tree":async()=>{let Z=await G.getToolConfigsTree();return Response.json(Z)},"/api/shell":async()=>{let Z=await G.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 G.getActivity(U);return Response.json(K)},"/api/tools/:name/history":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.getToolHistory(q);return Response.json(I)},"/api/tools/:name/readme":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.getToolReadme(q);return Response.json(I)},"/api/tools/:name/source":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.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 G.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 G.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 G.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 G.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)},"/*":N9},fetch(Z){let q=new URL(Z.url);return Q.debug(w.requestReceived(Z.method,q.pathname)),new Response("Not Found",{status:404})}}),Q.info(w.serverStarted(this.getUrl())),o4},async stop(){if(Q.info(w.serverStopping()),Y)Y.stop(),Y=null;Q.info(w.serverStopped())},getUrl(){return`http://${J.host}:${J.port}`}}}var{$:$3}=globalThis.Bun;var M3=async($,M)=>{let J=M===2?"open":M===4?"start":"xdg-open";await $3`${J} ${$}`.nothrow().quiet()};function y9($,M,J,Q={}){let G=Q.openBrowser??M3,Y=Q.createServer??NG,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 Y(X,H,{port:q,host:I}).start();if(U&&!O){let B=`http://${I}:${q}`;try{await G(B,K.systemInfo.platform)}catch(j){X.warn(R.dashboardBrowserOpenFailed(),j)}}})}import lM from"path";var P9={name:"detect-conflicts",description:"Detect file conflicts before generating"};async function J3($,M,J,Q,G){try{let Y=await Q.loadToolConfigs($,M.paths.toolConfigsDir,J,M,G);return{toolConfigs:Object.values(Y),exitCode:x.SUCCESS}}catch(Y){return $.error(R.configLoadFailed("tool configurations"),Y),{toolConfigs:[],exitCode:x.ERROR}}}async function Q3($,M,J,Q,G){if(!J.binaries)return;for(let Y of J.binaries){let X=typeof Y==="string"?Y:Y.name,Z=lM.join(Q,X);if(await M.exists(Z))try{if(!(await M.readFile(Z)).includes("# Generated by Dotfiles Management Tool"))G.push(`[${J.name}]: ${Z} (exists but is not a generator shim)`)}catch(q){$.warn(R.fsReadFailed(Z),q),G.push(`[${J.name}]: ${Z} (exists but could not be read/verified)`)}}}async function G3($,M,J,Q,G,Y){if(!J.symlinks)return;for(let X of J.symlinks){let Z=lM.join(Q,X.target),q=lM.join(G,X.source);try{let I=await M.lstat(Z);if(I)if(I.isSymbolicLink()){let U=await M.readlink(Z);if(lM.resolve(lM.dirname(Z),U)!==q)Y.push(`[${J.name}]: ${Z} (points to '${U}', expected '${q}')`)}else Y.push(`[${J.name}]: ${Z} (exists but is not a symlink)`)}catch(I){if(I.code!=="ENOENT")$.warn(R.fsReadFailed(Z),I)}}}function Y3($,M){if(M.length>0){let Q=M.map((G)=>` - ${G}`).join(`
|
|
226
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 X3($,M,J){let{projectConfig:Q,fs:G,configService:Y,systemInfo:X}=J,Z=[],q=await J3($,Q,G,Y,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 Q3($,G,U,Q.paths.targetDir,Z),await G3($,G,U,Q.paths.homeDir,Q.paths.dotfilesDir,Z);return Y3($,Z)}function C9($,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 G=M.opts(),Y;try{let X=await J();Y=await X3(Q,G,X)}catch(X){Q.error(R.commandExecutionFailed("detect-conflicts",x.ERROR),X),Y=x.ERROR}v(Y)})}var Y$="DOTFILES_ENV_DIR",xM="DOTFILES_ENV_NAME",P0="env",nJ="source",d9="source.ps1",KM="config.ts",yG="tools";function u9(){let $=p0();return c(`
|
|
@@ -446,4 +446,4 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
446
446
|
WHERE tool_name = ? AND binary_name = ?
|
|
447
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 q7 from"os";import $5 from"path";import C0 from"path";var o3=["dotfiles.config.ts"],e3=["project.json",".git"];async function W7($,M,J){let Q=$.getSubLogger({name:"resolveConfigPath"}),{cwd:G,homeDir:Y}=J,X=new z$;if(M.length>0){let I=M.startsWith("~")?M.replace(/^~(?=$|\/|\\)/,Y):M,U=C0.resolve(G,I);return Q.debug(R.configPathResolved(U)),U}let Z=process.env[Y$];if(Z){let I=C0.join(Z,KM);if(await X.exists(I))return Q.debug(R.envConfigFromEnvVar(I)),I}let q=G;while(!0){for(let U of o3){let K=C0.join(q,U);if(await X.exists(K))return Q.debug(R.configPathResolved(K)),K}if(q===Y)break;for(let U of e3)if(await X.exists(C0.join(q,U)))return;let I=C0.dirname(q);if(I===q)break;q=I}return}function M5($,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:eG(J),arch:$6(Q),homeDir:q7.homedir(),hostname:q7.hostname()}}async function aJ($,M){let J=$.getSubLogger({name:"createBaseRuntimeContext"}),Q=M5($,M),G=await W7(J,M.config,{cwd:M.cwd,homeDir:Q.homeDir});if(!G)return null;let Y=M.configFileSystem??M.fileSystem,X=await mY(J,Y,G,Q,M.env),Z={...Q,homeDir:X.paths.homeDir},q=$5.join(X.paths.generatedDir,"registry.db"),I=new uG($,q),U=I.getConnection(),K=$.getSubLogger({context:"system"}),H=new VQ(K,U),_=new fG(K,U);return{projectConfig:X,systemInfo:Z,registryPath:q,registryDatabase:I,fileRegistry:H,toolInstallationRegistry:_}}async function I7($,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 J5($){let M=$.indexOf("@track-usage");if(M<0)return null;let J=[],Q="",G,Y;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")G=U;if(I==="--arch")Y=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:G,arch:Y}}async function U7($){let M=J5($);if(!M)return;let J={getSubLogger:()=>J,trace:()=>{return},debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return},fatal:()=>{return},setPrefix:()=>J},Q=await I7(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 K7 from"path";async function H7($,M){let J=$.getSubLogger({name:"populateMemFsForDryRun"}),{sourceFs:Q,targetFs:G,toolConfigsDir:Y,homeDir:X}=M;if(J.trace(R.toolConfigsForDryRun()),!await Q.exists(Y)){J.warn(R.fsItemNotFound("Tool configs directory",Y));return}let Z=await _7(J,Q,Y);J.trace(R.toolConfigsLoaded(Y,Z.length));for(let q of Z)await Q5(J,Q,G,q,X)}async function _7($,M,J){let Q=[];try{let G=await M.readdir(J);for(let Y of G){let X=K7.join(J,Y);try{if((await M.stat(X)).isDirectory()){let q=await _7($,M,X);Q.push(...q)}else Q.push(X)}catch(Z){$.debug(R.fsReadFailed(X),Z)}}}catch(G){$.debug(R.fsReadFailed(J),G)}return Q}async function Q5($,M,J,Q,G){try{let Y=await M.readFile(Q,"utf8");await J.ensureDir(K7.dirname(Q)),await J.writeFile(Q,Y),$.trace(R.fsWrite("memfs",s(G,Q)))}catch(Y){$.error(R.fsReadFailed(Q),Y)}}function R7($){return async(M,J)=>{let Q=$(M,J);if(Q instanceof Promise)return Q;return Q}}async function Y5($,M=2000){return new Promise((J)=>{let Q=new G5.Socket,G=()=>{Q.removeAllListeners(),Q.destroy()};Q.setTimeout(M),Q.on("connect",()=>{G(),J(!0)}),Q.on("timeout",()=>{G(),J(!1)}),Q.on("error",()=>{G(),J(!1)}),Q.connect($,"localhost")})}function X5($){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 Z5($,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 W5($,M,J){if(!J.downloader.cache.enabled){$.info(R.cachingDisabled());return}let Q=K0.join(J.paths.generatedDir,"cache","downloads");return new $M($,M,{enabled:!0,defaultTtl:J.downloader.cache.ttl,cacheDir:Q,storageStrategy:"binary"})}function q5($,M,J,Q){let G=new f($,M,J,f.createContext("system","shim"),Q),Y=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:G,shellInitTrackedFs:Y,symlinkTrackedFs:X,copyTrackedFs:Z,installerTrackedFs:q,catalogTrackedFs:I,completionTrackedFs:U}}async function I5($,M){let J=$.getSubLogger({name:"setupServices"}),{dryRun:Q,env:G,config:Y}=M,X=Z5(J,Q),Z=!process.env.BUN_TEST,q=Q&&Z?new z$:X,I=await aJ(J,{config:Y,cwd:M.cwd,env:G,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=G.DEV_PROXY,j=X5(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 Y5(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 H7(J,{sourceFs:u0,targetFs:D,toolConfigsDir:U.paths.toolConfigsDir,homeDir:K.homeDir})}let A=W5($,D,U);$.debug(R.registryInitialized(H));let k=new AQ($,D,void 0,A,typeof V==="number"?{enabled:!0,port:V}:void 0),S=W$(),u=new $M($,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,k,u),E=new _J($,U,S,u),m=new $M($,D,{enabled:U.github.cache.enabled,defaultTtl:U.github.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","gitea-api"),storageStrategy:"json"}),$$=new $M($,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"}),g=new $M($,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,k,$$,g),{shimTrackedFs:y,shellInitTrackedFs:O$,symlinkTrackedFs:r$,copyTrackedFs:d0,installerTrackedFs:T$,catalogTrackedFs:sJ,completionTrackedFs:pG}=q5($,D,_,U),TM=$.getSubLogger({context:"system"}),cG=new qG(TM,O$,U),rJ=new kG(TM,r$,U,K),hG=new TG(TM,d0,U,K),O7=new F0(TM,S),kM=new rQ($,D,S),HM=new FQ((u0)=>{process.stdout.write(u0)}),X$=new IQ($);X$.register(new pQ(T$,k,i,E,kM,U,HM)),X$.register(new nQ(T$,k,kM,HM,m)),X$.register(new bQ(S)),X$.register(new NQ(T$,k,o,kM,HM,U.cargo.githubRelease.host)),X$.register(new yQ(T$,k,HM,S)),X$.register(new PQ(T$,k,kM,HM,S)),X$.register(new zG(T$,k,HM,S)),X$.register(new cQ(T$,k,kM,HM,S,i,E)),X$.register(new lQ(T$)),X$.register(new BG(S)),X$.register(new EG(T$,S));let j7=X$.getExternallyManagedMethods(),V7=X$.getMissingBinaryMessagesByMethod(),mG=new LG(TM,y,U,K,j7,V7,O),gG=new oQ(TM,pG,S,O7,{downloader:k,archiveExtractor:kM}),z7=new VG(TM,mG,cG,rJ,hG,gG,K,U,_,D,pG),B7=new wQ(J,T$,D,U,O,K,X$,rJ,S,HM),D7=new SG(J,i),A7=new HG,E7=new OG(J,k,O,D,sJ,K0.join(U.paths.generatedDir,"cache","readme"),X$);return{projectConfig:U,fs:D,configService:A7,readmeService:E7,fileRegistry:_,toolInstallationRegistry:O,downloadCache:A,downloader:k,githubApiCache:u,cargoCratesIoCache:$$,cargoGithubRawCache:g,githubApiClient:i,cargoClient:o,shimGenerator:mG,shellInitGenerator:cG,symlinkGenerator:rJ,copyGenerator:hG,completionGenerator:gG,generatorOrchestrator:z7,installer:B7,archiveExtractor:kM,versionChecker:D7,pluginRegistry:X$,systemInfo:K}}function U5($,M,J){let Q=$.getSubLogger({name:"registerAllCommands"});Q9(Q,M,J),o9(Q,M,J),Z7(Q,M,J),n9(Q,M,J),I9(Q,M,J),X9(Q,M,J),G7(Q,M,J),C9(Q,M,J),$7(Q,M,J),s9(Q,M,J),J7(Q,M,J),y9(Q,M,J),m9(Q,M)}function K5($,M){return $.includes(M)}var H5=new Set(["--config","--log","--platform","--arch"]);function _5($){for(let M=2;M<$.length;M+=1){let J=$[M];if(!J)continue;if(H5.has(J)){M+=1;continue}if(J.startsWith("-"))continue;return J}return}function R5($,M){let J=K5($,"--shim-mode"),Q=M.quiet||J;return U6(M.log,Q,M.verbose)}async function O5($){let M=K9();M.parseOptions($);let J=M.opts(),Q=R5($,J),Y=WQ({name:"cli",level:Q,trace:J.trace}).getSubLogger({name:"main"});Y.trace(R.cliStarted(),$),U5(Y,M,async()=>{return await I5(Y,{...J,cwd:process.cwd(),env:process.env})}),await M.parseAsync($)}async function j5($){if(_5($)==="@track-usage"){await U7($);return}await O5($)}j5(process.argv).catch(($)=>{WQ({name:"cli"}).fatal(R.commandExecutionFailed("main",1),$),process.exit(1)});export{I5 as setupServices,j5 as runCliEntrypoint,R5 as resolveLogLevel,U5 as registerAllCommands,O5 as main,R7 as defineTool,S1 as defineConfig,tJ as dedentTemplate,c as dedentString,A$ as Platform,RM as Architecture};
|
|
448
448
|
|
|
449
|
-
//# debugId=
|
|
449
|
+
//# debugId=94EAE9E90B5FC5C964756E2164756E21
|