@stacksjs/dtsx
Version:
A modern, fast .d.ts generation tool, powered by Bun.
79 lines (69 loc) • 67.3 kB
JavaScript
// @bun
import"./chunk-p0p65mbf.js";import{existsSync as EZ}from"fs";import HJ from"fs/promises";import CJ from"os";import KJ from"path";import p from"process";import{EventEmitter as IZ}from"events";import m from"process";import kJ from"process";import MJ from"process";import qJ from"process";import vJ from"process";import o from"process";import SJ from"tty";import zZ,{stdin as j0,stdout as G0}from"process";import*as c from"readline";import{ReadStream as yJ,WriteStream as H0}from"tty";import gJ,{stdin as P0,stdout as N0}from"process";import w0 from"readline";import A0 from"process";import S0 from"process";import{WriteStream as y0}from"tty";import f0 from"process";import xJ from"process";import d0 from"process";import{stripVTControlCharacters as WJ}from"util";import{existsSync as c0,lstatSync as dJ,readdirSync as p0}from"fs";import{dirname as uJ,join as i0}from"path";import n0 from"process";import b from"process";import e from"process";import{stripVTControlCharacters as DJ}from"util";import r0 from"process";import{Buffer as iJ}from"buffer";import y from"fs/promises";import a0 from"os";import XJ from"path";import w from"process";import{Readable as s0,Writable as t0}from"stream";class nJ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let J=CJ.homedir(),Z=KJ.join(J,".config","clapp");this.configPath=KJ.join(Z,"telemetry.json")}async isEnabled(){if(p.env.DO_NOT_TRACK==="1"||p.env.DO_NOT_TRACK==="true")return!1;if(p.env.NO_TELEMETRY==="1"||p.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let J=await this.loadConfig();if(J.enabled=!0,!J.userId)J.userId=this.generateUserId();await this.saveConfig(J)}async disable(){let J=await this.loadConfig();J.enabled=!1,await this.saveConfig(J)}async track(J,Z){if(!await this.isEnabled())return;let Q={event:J,...Z,timestamp:Date.now(),platform:CJ.platform(),nodeVersion:p.version};if(this.events.push(Q),this.events.length>=10)await this.send()}async trackCommand(J,Z){await this.track("command",{command:J,duration:Z})}async trackError(J,Z){await this.track("error",{error:J,command:Z})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let Z=await this.loadConfig();return Z.lastSent=Date.now(),await this.saveConfig(Z),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let Z=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(Z),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(J){return new Promise((Z)=>setTimeout(Z,J))}async status(){let J=await this.loadConfig();return{enabled:J.enabled,doNotTrack:p.env.DO_NOT_TRACK==="1"||p.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:J.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(EZ(this.configPath)){let J=await HJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(J),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(J){this.config=J;try{let Z=KJ.dirname(this.configPath);await HJ.mkdir(Z,{recursive:!0}),await HJ.writeFile(this.configPath,JSON.stringify(J,null,2),"utf-8")}catch{}}generateUserId(){let J=Math.random().toString(36).substring(2,15),Z=Date.now().toString(36);return`${J}-${Z}`}}var Y$=new nJ;function AZ(J,Z={}){let $={_:[]},Q=Z.alias||{},Y=new Set(Z.boolean||[]),q={};for(let F of Object.keys(Q))for(let X of Q[F])q[X]=F;for(let F of Y)if(Q[F])for(let X of Q[F])Y.add(X);function U(F,X){let j=q[F]||F;if($[j]=X,Q[j])for(let G of Q[j])$[G]=X;if(q[F]&&Q[q[F]])for(let G of Q[q[F]])$[G]=X;$[F]=X}for(let F=0;F<J.length;F++){let X=J[F];if(X==="--"){$._.push(...J.slice(F+1));break}if(X.startsWith("--")){let j=X.indexOf("=");if(j!==-1){let G=X.slice(2,j),V=X.slice(j+1);U(G,V)}else{let G=X.slice(2);if(G.startsWith("no-")){let W=G.slice(3);U(W,!1);continue}let V=q[G]||G;if(Y.has(V)||Y.has(G))U(G,!0);else{let W=J[F+1];if(W!==void 0&&!W.startsWith("-"))U(G,W),F++;else U(G,!0)}}}else if(X.startsWith("-")&&X.length>1){let j=X.slice(1);for(let G=0;G<j.length;G++){let V=j[G],W=q[V]||V;if(G===j.length-1&&!Y.has(W)&&!Y.has(V)){let K=J[F+1];if(K!==void 0&&!K.startsWith("-"))U(V,K),F++;else U(V,!0)}else U(V,!0)}}else $._.push(X)}return $}function LJ(J){return J.replace(/[<[].+/,"").trim()}function RZ(J){let Z=/<([^>]+)>/g,$=/\[([^\]]+)\]/g,Q=[],Y=(F)=>{let X=!1,j=F[1];if(j.startsWith("..."))j=j.slice(3),X=!0;return{required:F[0].startsWith("<"),value:j,variadic:X}},q;while(q=Z.exec(J))Q.push(Y(q));let U;while(U=$.exec(J))Q.push(Y(U));return Q}function xZ(J){let Z={alias:{},boolean:[]};for(let[$,Q]of J.entries()){if(Q.names.length>1)Z.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!J.some((q,U)=>{return U!==$&&q.names.some((F)=>Q.names.includes(F))&&typeof q.required==="boolean"}))Z.boolean.push(Q.names[0])}else Z.boolean.push(Q.names[0])}return Z}function hJ(J){return J.reduce((Z,$)=>Z.length>=$.length?Z:$,"")}function VJ(J,Z){return J.length>=Z?J:`${J}${" ".repeat(Z-J.length)}`}function CZ(J){return J.replace(/([a-z])-([a-z])/g,(Z,$,Q)=>{return $+Q.toUpperCase()})}function kZ(J,Z,$){let Q=0,Y=Z.length,q=J,U;for(;Q<Y;++Q)U=q[Z[Q]],q=q[Z[Q]]=Q===Y-1?$:U!=null?U:!!~Z[Q+1].indexOf(".")||!(+Z[Q+1]>-1)?{}:[]}function hZ(J,Z){for(let $ of Object.keys(Z)){let Q=Z[$];if(Q.shouldTransform){if(J[$]=Array.prototype.concat.call([],J[$]),typeof Q.transformFunction==="function")J[$]=J[$].map(Q.transformFunction)}}}function bZ(J){let Z=/([^\\/]+)$/.exec(J);return Z?Z[1]:""}function lJ(J){return J.split(".").map((Z,$)=>{return $===0?CZ(Z):Z}).join(".")}class YJ extends Error{exitCode=2;isUsageError=!0;constructor(J){super(J);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(J).stack}format(J=!1){if(J&&this.stack)return`${this.message}
Stack trace:
${this.stack}`;return this.message}}function vZ(){let{env:J}=kJ,{TERM:Z,TERM_PROGRAM:$}=J;if(kJ.platform!=="win32")return Z!=="linux";return Boolean(J.WT_SESSION)||Boolean(J.TERMINUS_SUBLIME)||J.ConEmuTask==="{cmd::Cmder}"||$==="Terminus-Sublime"||$==="vscode"||Z==="xterm-256color"||Z==="alacritty"||Z==="rxvt-unicode"||Z==="rxvt-unicode-256color"||J.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var UJ="\x1B",T=`${UJ}[`,F$="\x07",C={to(J,Z){if(!Z)return`${T}${J+1}G`;return`${T}${Z+1};${J+1}H`},move(J,Z){let $="";if(J<0)$+=`${T}${-J}D`;else if(J>0)$+=`${T}${J}C`;if(Z<0)$+=`${T}${-Z}A`;else if(Z>0)$+=`${T}${Z}B`;return $},up:(J=1)=>`${T}${J}A`,down:(J=1)=>`${T}${J}B`,forward:(J=1)=>`${T}${J}C`,backward:(J=1)=>`${T}${J}D`,nextLine:(J=1)=>`${T}E`.repeat(J),prevLine:(J=1)=>`${T}F`.repeat(J),left:`${T}G`,hide:`${T}?25l`,show:`${T}?25h`,save:`${UJ}7`,restore:`${UJ}8`},j$={up:(J=1)=>`${T}S`.repeat(J),down:(J=1)=>`${T}T`.repeat(J)},JJ={screen:`${T}2J`,up:(J=1)=>`${T}1J`.repeat(J),down:(J=1)=>`${T}J`.repeat(J),line:`${T}2K`,lineEnd:`${T}K`,lineStart:`${T}1K`,lines(J){let Z="";for(let $=0;$<J;$++)Z+=this.line+($<J-1?C.up():"");if(J)Z+=C.left;return Z}},G$={screen:`${UJ}c`};function SZ(J,Z){let $=[];for(let Q=0;Q<=Z.length;Q++)$[Q]=[Q];for(let Q=0;Q<=J.length;Q++)$[0][Q]=Q;for(let Q=1;Q<=Z.length;Q++)for(let Y=1;Y<=J.length;Y++)if(Z.charAt(Q-1)===J.charAt(Y-1))$[Q][Y]=$[Q-1][Y-1];else $[Q][Y]=Math.min($[Q-1][Y-1]+1,$[Q][Y-1]+1,$[Q-1][Y]+1);return $[Z.length][J.length]}function rJ(J,Z,$=2,Q=3){return Z.map((Y)=>({cmd:Y,distance:SZ(J,Y)})).filter(({distance:Y})=>Y<=$).sort((Y,q)=>Y.distance-q.distance).slice(0,Q).map(({cmd:Y})=>Y)}class aJ{rawName;description;name;names;isBoolean;required;config;negated;constructor(J,Z,$){if(this.rawName=J,this.description=Z,this.config=Object.assign({},$),J=J.replace(/\.\*/g,""),this.negated=!1,this.names=LJ(J).split(",").map((Q)=>{let Y=Q.trim().replace(/^-{1,2}/,"");if(Y.startsWith("no-"))this.negated=!0,Y=Y.replace(/^no-/,"");return lJ(Y)}).sort((Q,Y)=>Q.length>Y.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(J.includes("<"))this.required=!0;else if(J.includes("["))this.required=!1;else this.isBoolean=!0}}var K$=MJ.argv,yZ=`${MJ.platform}-${MJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,bJ=qJ.argv,gZ=`${qJ.platform}-${qJ.arch} node-${qJ.version}`;class BJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(J,Z,$,Q){this.rawName=J,this.description=Z,this.config=$,this.cli=Q,this.options=[],this.aliasNames=[],this.name=LJ(J);let Y=LJ(J),q=Y.indexOf(":");if(q>0)this.namespace=Y.substring(0,q),this.name=Y.substring(q+1);if(this.args=RZ(J),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!$)this.config={}}usage(J){return this.usageText=J,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(J,Z="-v, --version"){return this.versionNumber=J,this.option(Z,"Display version number"),this}example(J){return this.examples.push(J),this}option(J,Z,$){let Q=new aJ(J,Z,$);return this.options.push(Q),this}alias(J){return this.aliasNames.push(J),this}action(J){return this.commandAction=J,this}before(J){return this.beforeHooks.push(J),this}after(J){return this.afterHooks.push(J),this}use(J){return this.middleware.push(J),this}isMatched(J){return this.name===J||this.aliasNames.includes(J)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof EJ}hasOption(J){return J=J.split(".")[0],!!this.options.find((Z)=>{return Z.names.includes(J)})}outputHelp(){let{name:J,commands:Z}=this.cli,{versionNumber:$,options:Q,helpCallback:Y}=this.cli.globalCommand,q=[{body:`${J}${$?`/${$}`:""}`}];if(q.push({title:"Usage",body:` $ ${J} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&Z.length>0){let X=hJ(Z.map((K)=>K.rawName)),j=new Map,G=[];for(let K of Z)if(K.namespace){if(!j.has(K.namespace))j.set(K.namespace,[]);j.get(K.namespace).push(K)}else G.push(K);let V="";if(G.length>0)V+=G.map((K)=>{return` ${VJ(K.rawName,X.length)} ${K.description}`}).join(`
`);let W=Array.from(j.keys()).sort();for(let K of W){let L=j.get(K);if(V.length>0)V+=`
`;V+=` ${K}:
`,V+=L.map((P)=>{return` ${VJ(P.rawName,X.length-2)} ${P.description}`}).join(`
`)}q.push({title:"Commands",body:V}),q.push({title:"For more info, run any command with the `--help` flag",body:Z.map((K)=>` $ ${J}${K.name===""?"":` ${K.name}`} --help`).join(`
`)})}let F=this.isGlobalCommand?Q:[...this.options,...Q||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)F=F.filter((X)=>X.name!=="version");if(F.length>0){let X=hJ(F.map((j)=>j.rawName));q.push({title:"Options",body:F.map((j)=>{return` ${VJ(j.rawName,X.length)} ${j.description} ${j.config.default===void 0?"":`(default: ${j.config.default})`}`}).join(`
`)})}if(this.examples.length>0)q.push({title:"Examples",body:this.examples.map((X)=>{if(typeof X==="function")return X(J);return X}).join(`
`)});if(Y)q=Y(q)||q;console.log(q.map((X)=>{return X.title?`${X.title}:
${X.body}`:X.body}).join(`
`))}outputVersion(){let{name:J}=this.cli,{versionNumber:Z}=this.cli.globalCommand;if(Z)console.log(`${J}/${Z} ${typeof Bun<"u"?yZ:gZ}`)}checkRequiredArgs(){let J=this.args.filter((Z)=>Z.required).length;if(this.cli.args.length<J){let $=this.args.filter((Y)=>Y.required).slice(this.cli.args.length),Q=$.map((Y)=>`<${Y.value}>`).join(" ");throw new YJ(`Missing required argument${$.length>1?"s":""}: ${Q}
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:J,globalCommand:Z}=this.cli;if(!this.config.allowUnknownOptions){for(let $ of Object.keys(J))if($!=="--"&&!this.hasOption($)&&!Z.hasOption($)){let Y=[...Z.options,...this.options].flatMap((X)=>X.names),q=$.length>1?`--${$}`:`-${$}`,U=rJ($,Y),F=`Unknown option \`${q}\``;if(U.length>0)F+=`
Did you mean one of these?`,U.forEach((X)=>{let j=X.length>1?`--${X}`:`-${X}`;F+=`
\u2022 ${j}`});throw F+=`
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new YJ(F)}}}checkOptionValue(){let{options:J,globalCommand:Z}=this.cli,$=[...Z.options,...this.options];for(let Q of $){let Y=J[Q.name.split(".")[0]];if(Q.required){let q=$.some((U)=>U.negated&&U.names.includes(Q.name));if(Y===!0||Y===!1&&!q)throw new YJ(`Option \`${Q.rawName}\` requires a value.
Example: ${this.cli.name} ${this.rawName} ${Q.rawName} <value>`)}}}}class EJ extends BJ{constructor(J){super("@@global@@","",{},J)}}var _Z=BJ,d={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]},PJ={default:{primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"},dracula:{primary:"magenta",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"blue",muted:"gray"},nord:{primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"cyan",muted:"gray"},solarized:{primary:"cyan",secondary:"blue",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"},monokai:{primary:"magenta",secondary:"blue",success:"green",warning:"yellow",error:"red",info:"cyan",muted:"gray"}},a={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function fZ(){return!0}function mZ(){let J={};J.supportsColor=fZ();function Z(Q,Y=[]){let q=Q===""?[]:[...Y,Q],U=function(X){if(!J.supportsColor)return X;let j="",G="";for(let V of q)if(V in a&&a[V]in d){let W=a[V];j+=d[W][0],G=d[W][1]+G}else if(V in d)j+=d[V][0],G=d[V][1]+G;return j+X+G},F=[...Object.keys(d),...Object.keys(a)];for(let X of F)if(!(X in U))Object.defineProperty(U,X,{get(){return Z(X,q)}});return U}let $=[...Object.keys(d),...Object.keys(a)];for(let Q of $)if(!(Q in J))Object.defineProperty(J,Q,{get(){return Z(Q)}});return J}var i=mZ();function dZ(J){for(let Z in J)if(J[Z]!==void 0)a[Z]=J[Z]}function W$(J){if(J in PJ)dZ(PJ[J])}function D$(){return Object.keys(PJ)}function L$(J){if(J.colors!==void 0)i.supportsColor=J.colors}function M$(J,Z){let $=Z?.title?` ${Z.title} `:"",Q=Z?.padding||0,Y=" ".repeat(Q),q=J.split(`
`),F=Math.max(...q.map((j)=>j.length))+Q*2,X=F;console.log(`\u250C${$?"\u2500".repeat(Math.floor((X-$.length)/2))+$+"\u2500".repeat(Math.ceil((X-$.length)/2)):"\u2500".repeat(X)}\u2510`),console.log(`\u2502${" ".repeat(X)}\u2502`);for(let j of q){let G=F-j.length-Q;console.log(`\u2502${Y}${j}${" ".repeat(G)}\u2502`)}console.log(`\u2502${" ".repeat(X)}\u2502`),console.log(`\u2514${"\u2500".repeat(X)}\u2518`)}function P$(J){let Z=J?.title?` ${J.title} `:"",Q=J.content.split(`
`),q=Math.max(...Q.map((U)=>U.length))+2;console.log(`\u2554${Z?"\u2550".repeat(Math.floor((q-Z.length)/2))+Z+"\u2550".repeat(Math.ceil((q-Z.length)/2)):"\u2550".repeat(q)}\u2557`),console.log(`\u2551${" ".repeat(q)}\u2551`);for(let U of Q){let F=q-U.length-1;console.log(`\u2551 ${U}${" ".repeat(F)}\u2551`)}console.log(`\u2551${" ".repeat(q)}\u2551`),console.log(`\u255A${"\u2550".repeat(q)}\u255D`)}function N$(J,Z){if(!J||J.length===0)return;let $=Array.from({length:J[0].length},()=>0);for(let Y of J)for(let q=0;q<Y.length;q++)$[q]=Math.max($[q],String(Y[q]).length);if(Z?.border)console.log(`\u250C${$.map((Y)=>"\u2500".repeat(Y+2)).join("\u252C")}\u2510`);if(Z?.header&&J.length>0)if(console.log((Z.border?"\u2502 ":"")+J[0].map((Y,q)=>`${Y}${" ".repeat($[q]-String(Y).length)}`).join(" \u2502 ")+(Z.border?" \u2502":"")),Z.border)console.log(`\u251C${$.map((Y)=>"\u2500".repeat(Y+2)).join("\u253C")}\u2524`);else console.log(`${$.map((Y)=>"\u2500".repeat(Y)).join("\u2500\u253C\u2500")}`);let Q=Z?.header?1:0;for(let Y=Q;Y<J.length;Y++)console.log((Z?.border?"\u2502 ":"")+J[Y].map((q,U)=>`${q}${" ".repeat($[U]-String(q).length)}`).join(" \u2502 ")+(Z?.border?" \u2502":""));if(Z?.border)console.log(`\u2514${$.map((Y)=>"\u2500".repeat(Y+2)).join("\u2534")}\u2518`)}class sJ extends IZ{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(J=""){super();this.name=J,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new EJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(J){if(this.signalHandlersSet)return this;let Z=async($)=>{if(console.log(`
Received ${$}, cleaning up...`),J)try{await J()}catch(Q){console.error("Error during cleanup:",Q)}m.exit(0)};return m.on("SIGINT",()=>Z("SIGINT")),m.on("SIGTERM",()=>Z("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(J=!0){return this.enableDidYouMean=J,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(J){return this.globalCommand.usage(J),this}command(J,Z,$){if(!$)$={};let Q=new _Z(J,Z||"",$,this);return Q.globalCommand=this.globalCommand,this.commands.push(Q),Q}option(J,Z,$){return this.globalCommand.option(J,Z,$),this}help(J){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=J,this.showHelpOnExit=!0,this}version(J,Z="-v, --version"){return this.globalCommand.version(J,Z),this.showVersionOnExit=!0,this}example(J){return this.globalCommand.example(J),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:J,options:Z},$,Q){if(this.args=J,this.options=Z,$)this.matchedCommand=$;if(Q)this.matchedCommandName=Q;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(J){if(console.log(i.red(`
\u2717 Command "${J}" not found.
`)),this.enableDidYouMean){let Z=[];for(let Q of this.commands){if(Q.name)Z.push(Q.name);if(Q.aliasNames)Z.push(...Q.aliasNames)}let $=rJ(J,Z);if($.length>0)console.log(i.yellow("Did you mean one of these?")),$.forEach((Q)=>console.log(` ${i.dim("\u2022")} ${this.name} ${Q}`)),console.log("")}console.log(i.dim("Run"),`${this.name} --help`,i.dim("to see all available commands")),m.exit(1)}async parse(J=bJ,Z={}){let{run:$=!0,exitOnError:Q=!1}=Z;if(Q)try{return await this.parse(J,{run:$})}catch(X){throw this.handleUsageError(X),X}if(this.rawArgs=J,!this.name)this.name=J[1]?bZ(J[1]):"cli";let Y=!0,q=J.slice(2),U=q[0];if(U&&!U.startsWith("-")){for(let X of this.commands)if(X.isMatched(U)){let j=this.mri(q,X);Y=!1;let G={...j,args:j.args.slice(1)};this.setParsedInfo(G,X,U),this.emit(`command:${U}`,X);break}}if(Y){for(let X of this.commands)if(X.name===""){Y=!1;let j=this.mri(q,X);this.setParsedInfo(j,X),this.emit("command:!",X);break}}if(Y){let X=this.mri(J.slice(2));this.setParsedInfo(X)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),$=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),$=!1,this.unsetMatchedCommand();let F={args:this.args,options:this.options};if($)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return F}mri(J,Z){let $=[...this.globalCommand.options,...Z?Z.options:[]],Q=xZ($),Y=[],q=J.indexOf("--");if(q>-1)Y=J.slice(q+1),J=J.slice(0,q);let U=AZ(J,Q),F={_:U._};for(let W of Object.keys(U))if(W!=="_")F[lJ(W)]=U[W];let X=F._,j={"--":Y},G=Z&&Z.config.ignoreOptionDefaultValue?Z.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,V=Object.create(null);for(let W of $){if(!G&&W.config.default!==void 0)for(let K of W.names)j[K]=W.config.default;if(Array.isArray(W.config.type)){if(V[W.name]===void 0)V[W.name]={shouldTransform:!0,transformFunction:W.config.type[0]}}}for(let W of Object.keys(F))if(W!=="_"){let K=W.split(".");kZ(j,K,F[W]),hZ(j,V)}return{args:X,options:j}}async run(J=bJ){return this.parse(J,{run:!0,exitOnError:!0})}handleUsageError(J){if(!(!!J&&typeof J==="object"&&J.name==="ClappError"&&J.isUsageError!==!1))return;let Q=J,Y=Q.message??"command-line error",q=this.name?`${this.name}: `:"",U=/--help/.test(Y)?"":`
Run \`${this.name??"cli"} --help\` for usage.`;m.stderr.write(`${q}${Y}${U}
`),m.exit(Q.exitCode??2)}async runMatchedCommand(){let{args:J,options:Z,matchedCommand:$}=this;if(!$||!$.commandAction)return;$.checkUnknownOptions(),$.checkOptionValue(),$.checkRequiredArgs();let Q=[];$.args.forEach((F,X)=>{if(F.variadic)Q.push(J.slice(X));else Q.push(J[X])}),Q.push(Z);let Y={command:$,args:Q,options:Z};for(let F of $.beforeHooks)await F(Y);let q,U=async()=>{let F=$.commandAction.apply(this,Q);if(F instanceof Promise)q=await F;else q=F;return q};if($.middleware.length>0){let F=0,X=async()=>{if(F<$.middleware.length){let j=$.middleware[F++];await j({...Y,next:X})}else await U()};await X()}else await U();for(let F of $.afterHooks)await F(Y);return q}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return m.removeAllListeners("SIGINT"),m.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}var tJ=(J="")=>new sJ(J);class oJ{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(J){if(!this.enabled){this.misses++;return}let Z=this.cache.get(J);if(!Z){this.misses++;return}if(Date.now()-Z.timestamp>Z.ttl){this.cache.delete(J),this.misses++;return}return this.hits++,Z.value}set(J,Z,$=5000){if(!this.enabled)return;this.cache.set(J,{value:Z,timestamp:Date.now(),ttl:$})}has(J){if(!this.enabled)return!1;let Z=this.cache.get(J);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete(J),!1;return!0}delete(J){this.cache.delete(J)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let J=Date.now();for(let[Z,$]of this.cache.entries())if(J-$.timestamp>$.ttl)this.cache.delete(Z)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var w$=new oJ;function T$(J,Z){J.on(`${Z}:*`,()=>{let $=J.args??[];vJ.stderr.write(`Unknown ${Z} subcommand: ${[...$].join(" ")}
Run \`${J.name??"cli"} ${Z} --help\` to see available subcommands.
`),vJ.exit(64)})}function uZ(){if("FORCE_COLOR"in o.env)return o.env.FORCE_COLOR!=="0";if("NO_COLOR"in o.env||o.env.TERM==="dumb")return!1;if(o.platform==="win32")return!0;return SJ.isatty(1)&&SJ.isatty(2)}var eJ=uZ();function B(J,Z){if(!eJ)return($)=>$;return($)=>J+$+Z}var cZ=B("\x1B[0m","\x1B[0m"),pZ=B("\x1B[31m","\x1B[39m"),JZ=B("\x1B[32m","\x1B[39m"),iZ=B("\x1B[33m","\x1B[39m"),nZ=B("\x1B[34m","\x1B[39m"),lZ=B("\x1B[35m","\x1B[39m"),rZ=B("\x1B[36m","\x1B[39m"),aZ=B("\x1B[37m","\x1B[39m"),ZZ=B("\x1B[90m","\x1B[39m"),$Z=B("\x1B[1m","\x1B[22m"),sZ=B("\x1B[3m","\x1B[23m"),tZ=B("\x1B[4m","\x1B[24m"),QZ=B("\x1B[2m","\x1B[22m"),oZ=B("\x1B[7m","\x1B[27m"),eZ=B("\x1B[8m","\x1B[28m"),J0=B("\x1B[9m","\x1B[29m"),Z0=B("\x1B[41m","\x1B[49m"),$0=B("\x1B[42m","\x1B[49m"),Q0=B("\x1B[43m","\x1B[49m"),z0=B("\x1B[44m","\x1B[49m"),Y0=B("\x1B[45m","\x1B[49m"),q0=B("\x1B[46m","\x1B[49m"),X0=B("\x1B[47m","\x1B[49m"),U0=eJ,F0={reset:cZ,red:pZ,green:JZ,yellow:iZ,blue:nZ,magenta:lZ,cyan:rZ,white:aZ,gray:ZZ,bold:$Z,italic:sZ,underline:tZ,dim:QZ,inverse:oZ,hidden:eZ,strikethrough:J0,bgRed:Z0,bgGreen:$0,bgYellow:Q0,bgBlue:z0,bgMagenta:Y0,bgCyan:q0,bgWhite:X0,isColorSupported:U0},z=F0,K0=["up","down","left","right","space","enter","cancel"],v={actions:new Set(K0),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function R$(J){if(J.aliases!==void 0){let Z=J.aliases;for(let $ in Z){if(!Object.hasOwn(Z,$))continue;let Q=Z[$];if(!v.actions.has(Q))continue;if(!v.aliases.has($))v.aliases.set($,Q)}}if(J.messages!==void 0){let Z=J.messages;if(Z.cancel!==void 0)v.messages.cancel=Z.cancel;if(Z.error!==void 0)v.messages.error=Z.error}}function IJ(J,Z){if(typeof J==="string")return v.aliases.get(J)===Z;for(let $ of J){if($===void 0)continue;if(IJ($,Z))return!0}return!1}function V0(J,Z){if(J===Z)return[];let $=J.split(`
`),Q=Z.split(`
`),Y=[];for(let q=0;q<Math.max($.length,Q.length);q++)if($[q]!==Q[q])Y.push(q);return Y}var W0=zZ.platform.startsWith("win"),NJ=Symbol("clapp:cancel");function D0(J){return J===NJ}function zJ(J,Z){let $=J;if($.isTTY)$.setRawMode(Z)}function L0(J){let{input:Z=j0,output:$=G0,overwrite:Q=!0,hideCursor:Y=!0}=J||{},q=c.createInterface({input:Z,output:$,prompt:"",tabSize:1});if(c.emitKeypressEvents(Z,q),Z instanceof yJ&&Z.isTTY)Z.setRawMode(!0);let U=(F,{name:X,sequence:j})=>{let G=String(F);if(IJ([G,X,j],"cancel")){if(Y)$.write(C.show);zZ.exit(0);return}if(!Q)return;c.moveCursor($,X==="return"?0:-1,X==="return"?-1:0,()=>{c.clearLine($,1,()=>{Z.once("keypress",U)})})};if(Y)$.write(C.hide);return Z.once("keypress",U),()=>{if(Z.off("keypress",U),Y)$.write(C.show);if(Z instanceof yJ&&Z.isTTY&&!W0)Z.setRawMode(!1);q.terminal=!1,q.close()}}function M0(J){if(J instanceof H0&&J.columns)return J.columns;return 80}function O0(J){return J.replace(/\x1b\[[0-9;]*m/g,"")}function T0(J){return O0(J).length}function _J(J,Z,$){if(!Z||Z<1)return J;let Q=$?.hard??!1,Y=$?.trim??!0,q=J.split(`
`),U=[];for(let F of q){if(T0(F)<=Z){U.push(Y?F.trimEnd():F);continue}if(Q){let X="",j=0,G=0;while(G<F.length){let V=F.slice(G).match(/^\x1b\[[0-9;]*m/);if(V){X+=V[0],G+=V[0].length;continue}if(j>=Z)U.push(Y?X.trimEnd():X),X="",j=0;X+=F[G],j++,G++}if(X)U.push(Y?X.trimEnd():X)}else U.push(Y?F.trimEnd():F)}return U.join(`
`)}class _{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(J,Z=!0){let{input:$=P0,output:Q=N0,render:Y,signal:q,...U}=J;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Y.bind(this),this._track=Z,this._abortSignal=q,this.input=$,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber(J,Z){let $=this._subscribers.get(J)??[];$.push(Z),this._subscribers.set(J,$)}on(J,Z){return this.setSubscriber(J,{cb:Z}),this}once(J,Z){return this.setSubscriber(J,{cb:Z,once:!0}),this}emit(J,...Z){let $=this._subscribers.get(J)??[],Q=[];for(let Y of $)if(Y.cb(...Z),Y.once)Q.push(()=>$.splice($.indexOf(Y),1));for(let Y of Q)Y();return this}prompt(){return new Promise((J)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),J(NJ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=w0.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),zJ(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(C.show),this.output.off("resize",this.render),zJ(this.input,!1),J(this.value)}),this.once("cancel",()=>{this.output.write(C.show),this.output.off("resize",this.render),zJ(this.input,!1),J(NJ)})})}_isActionKey(J,Z){return J==="\t"}_setValue(J){this.value=J,this.emit("value",this.value)}_setUserInput(J,Z){if(this.userInput=J??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(J,Z){if(this._track&&Z.name!=="return"){if(Z.name&&this._isActionKey(J,Z))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let $=Z.name==="tab"||Z.name==="escape"||Z.name==="backspace"||Z.name==="delete"||Z.name==="enter"||Z.name==="return"||Z.name&&["up","down","left","right"].includes(Z.name);if(J&&!$&&J.length===1&&J>=" ")this._manualLine+=J;else if(Z.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Q=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Q)}if(this.state==="error")this.state="active",this.error="";if(Z?.name){if(!this._track&&v.aliases.has(Z.name))this.emit("cursor",v.aliases.get(Z.name));if(v.actions.has(Z.name))this.emit("cursor",Z.name)}if(J&&(J.toLowerCase()==="y"||J.toLowerCase()==="n"))this.emit("confirm",J.toLowerCase()==="y");if(this.emit("key",J?.toLowerCase(),Z),Z?.name==="return"){if(this.opts.validate){let $=this.opts.validate(this.value);if($)this.error=$ instanceof Error?$.message:$,this.state="error"}if(this.state!=="error")this.state="submit"}if(IJ([J,Z?.name,Z?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
`),zJ(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let J=_J(this._prevFrame,gJ.stdout.columns,{hard:!0,trim:!1}).split(`
`).length-1;this.output.write(C.move(-999,J*-1))}render(){let J=_J(this._render(this)??"",gJ.stdout.columns,{hard:!0,trim:!1});if(J===this._prevFrame)return;if(this.state==="initial")this.output.write(C.hide);else{let Z=V0(this._prevFrame,J);if(this.restoreCursor(),Z&&Z?.length===1){let $=Z[0];this.output.write(C.move(0,$)),this.output.write(JJ.lines(1));let Q=J.split(`
`);this.output.write(Q[$]),this._prevFrame=J,this.output.write(C.move(0,Q.length-$-1));return}if(Z&&Z?.length>1){let $=Z[0];this.output.write(C.move(0,$)),this.output.write(JJ.down());let Y=J.split(`
`).slice($);this.output.write(Y.join(`
`)),this._prevFrame=J;return}this.output.write(JJ.down())}if(this.output.write(J),this.state==="initial")this.state="active";this._prevFrame=J}}function B0(J,Z){if(J===void 0)return 0;if(Z.length===0)return 0;let Q=Z.findIndex((Y)=>Y.value===J);return Q!==-1?Q:0}function E0(J,Z){return(Z.label??String(Z.value)).toLowerCase().includes(J.toLowerCase())}function I0(J,Z){if(!Z)return;if(J)return Z;return Z[0]}class AJ extends _{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#J=0;#$="";#Q;#Z;get cursor(){return this.#J}get userInputWithCursor(){if(!this.userInput)return z.inverse(z.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let J=this.userInput.slice(0,this._cursor),[Z,...$]=this.userInput.slice(this._cursor);return`${J}${z.inverse(Z)}${$.join("")}`}get options(){if(typeof this.#Z==="function")return this.#Z();return this.#Z}constructor(J){super(J);this.#Z=J.options;let Z=this.options;this.filteredOptions=[...Z],this.multiple=J.multiple===!0,this.#Q=J.filter??E0;let $;if(J.initialValue&&Array.isArray(J.initialValue))if(this.multiple)$=J.initialValue;else $=J.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)$=[this.options[0].value];if($)for(let Q of $){let Y=Z.findIndex((q)=>q.value===Q);if(Y!==-1)this.toggleSelected(Q),this.#J=Y}this.focusedValue=this.options[this.#J]?.value,this.on("key",(Q,Y)=>this.#z(Q,Y)),this.on("userInput",(Q)=>this.#Y(Q))}_isActionKey(J,Z){return J==="\t"||this.multiple&&this.isNavigating&&Z.name==="space"&&J!==void 0&&J!==""}#z(J,Z){let $=Z.name==="up",Q=Z.name==="down",Y=Z.name==="return";if($||Q){if(this.#J=Math.max(0,Math.min(this.#J+($?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#J]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Y)this.value=I0(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(Z.name==="tab"||this.isNavigating&&Z.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(J){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(J))this.selectedValues=this.selectedValues.filter((Z)=>Z!==J);else this.selectedValues=[...this.selectedValues,J];else this.selectedValues=[J]}#Y(J){if(J!==this.#$){this.#$=J;let Z=this.options;if(J)this.filteredOptions=Z.filter(($)=>this.#Q(J,$));else this.filteredOptions=[...Z];if(this.#J=B0(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#J]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class YZ extends _{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(J){super(J,!1);this.value=!!J.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(Z)=>{this.output.write(C.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class qZ extends _{options;cursor=0;#J;getGroupItems(J){return this.options.filter((Z)=>Z.group===J)}isGroupSelected(J){let Z=this.getGroupItems(J),$=this.value;if($===void 0)return!1;return Z.every((Q)=>$.includes(Q.value))}toggleValue(){let J=this.options[this.cursor];if(this.value===void 0)this.value=[];if(J.group===!0){let Z=J.value,$=this.getGroupItems(Z);if(this.isGroupSelected(Z))this.value=this.value.filter((Q)=>$.findIndex((Y)=>Y.value===Q)===-1);else this.value=[...this.value,...$.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let Z=this.value.includes(J.value);this.value=Z?this.value.filter(($)=>$!==J.value):[...this.value,J.value]}}constructor(J){super(J,!1);let{options:Z}=J;this.#J=J.selectableGroups!==!1,this.options=Object.entries(Z).flatMap(([$,Q])=>[{value:$,group:!0,label:$},...Q.map((Y)=>({...Y,group:$}))]),this.value=[...J.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:$})=>$===J.cursorAt),this.#J?0:1),this.on("cursor",($)=>{switch($){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#J&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#J&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}class XZ extends _{options;cursor=0;get _value(){return this.options[this.cursor].value}toggleAll(){let J=this.value!==void 0&&this.value.length===this.options.length;this.value=J?[]:this.options.map((Z)=>Z.value)}toggleValue(){if(this.value===void 0)this.value=[];let J=this.value.includes(this._value);this.value=J?this.value.filter((Z)=>Z!==this._value):[...this.value,this._value]}constructor(J){super(J,!1);this.options=J.options,this.value=[...J.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Z})=>Z===J.cursorAt),0),this.on("key",(Z)=>{if(Z==="a")this.toggleAll()}),this.on("cursor",(Z)=>{switch(Z){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}}class UZ extends _{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let J=this.userInput;if(this.cursor>=J.length)return`${this.masked}${z.inverse(z.hidden("_"))}`;let Z=this.masked,$=Z.slice(0,this.cursor),Q=Z.slice(this.cursor);return`${$}${z.inverse(Q[0])}${Q.slice(1)}`}constructor({mask:J,...Z}){super(Z);this._mask=J??"\u2022",this.on("userInput",($)=>{this._setValue($)})}}class FZ extends _{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(J){super(J,!1);if(this.options=J.options,this.cursor=this.options.findIndex(({value:Z})=>Z===J.initialValue),this.cursor===-1)this.cursor=0;this.changeValue(),this.on("cursor",(Z)=>{switch(Z){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}}class jZ extends _{options;cursor=0;constructor(J){super(J,!1);this.options=J.options;let Z=this.options.map(({value:[$]})=>$?.toLowerCase());this.cursor=Math.max(Z.indexOf(J.initialValue),0),this.on("key",($)=>{if(!$||!Z.includes($))return;let Q=this.options.find(({value:[Y]})=>Y?.toLowerCase()===$);if(Q)this.value=Q.value,this.state="submit",this.emit("submit")})}}class GZ extends _{placeholder;get userInputWithCursor(){if(this.state==="submit")return this.userInput;let J=this.userInput;if(this.cursor>=J.length)return`${this.userInput}\u2588`;let Z=J.slice(0,this.cursor),[$,...Q]=J.slice(this.cursor);return`${Z}${z.inverse($)}${Q.join("")}`}get cursor(){return this._cursor}constructor(J){super({...J,initialUserInput:J.initialUserInput??J.initialValue});this.placeholder=J.placeholder,this.on("key",(Z)=>{if(Z==="\t"&&this.placeholder){if(!this.userInput||this.userInput==="\t")this._setValue(this.placeholder),this._setUserInput(this.placeholder,!0)}}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{if(!this.userInput&&this.placeholder)this.value=this.placeholder;if(!this.value)this.value=J.defaultValue;if(this.value===void 0)this.value=""})}}var wJ=vZ(),HZ=()=>A0.env.CI==="true";function R0(J){return J.isTTY===!0}var O=(J,Z)=>wJ?J:Z,x0=O("\u25C6","*"),KZ=O("\u25A0","x"),VZ=O("\u25B2","x"),t=O("\u25C7","o"),C0=O("\u250C","T"),H=O("\u2502","|"),x=O("\u2514","\u2014"),FJ=O("\u25CF",">"),jJ=O("\u25CB"," "),OJ=O("\u25FB","[\u2022]"),s=O("\u25FC","[+]"),RJ=O("\u25FB","[ ]"),k0=O("\u25AA","\u2022"),fJ=O("\u2500","-"),h0=O("\u256E","+"),b0=O("\u251C","+"),v0=O("\u256F","+"),WZ=O("\u25CF","\u2022"),DZ=O("\u25C6","*"),LZ=O("\u25B2","!"),MZ=O("\u25A0","x");function f(J){switch(J){case"initial":case"active":return z.cyan(x0);case"cancel":return z.red(KZ);case"error":return z.yellow(VZ);case"submit":return z.green(t)}}function n(J){return J.replace(/_([^_]+)_/g,(Z,$)=>i.italic($))}function ZJ(J){let{cursor:Z,options:$,style:Q}=J,Y=J.output??S0.stdout,q=Y instanceof y0&&Y.rows!==void 0?Y.rows:10,U=z.dim("..."),F=J.maxItems??Number.POSITIVE_INFINITY,X=Math.max(q-4,0),j=Math.min(X,Math.max(F,5)),G=0;if(Z>=G+j-3)G=Math.max(Math.min(Z-j+3,$.length-j),0);else if(Z<G+2)G=Math.max(Z-2,0);let V=j<$.length&&G>0,W=j<$.length&&G+j<$.length;return $.slice(G,G+j).map((K,L,P)=>{let D=L===0&&V,M=L===P.length-1&&W;return D||M?U:Q(K,L+G===Z)})}function mJ(J){return J.label??String(J.value??"")}function PZ(J,Z){if(!J)return!0;let $=(Z.label??String(Z.value??"")).toLowerCase(),Q=(Z.hint??"").toLowerCase(),Y=String(Z.value).toLowerCase(),q=J.toLowerCase();return $.includes(q)||Q.includes(q)||Y.includes(q)}function g0(J,Z){let $=[];for(let Q of Z)if(J.includes(Q.value))$.push(Q);return $}function _0(J){return new AJ({options:J.options,initialValue:J.initialValue?[J.initialValue]:void 0,initialUserInput:J.initialUserInput,filter:($,Q)=>{return PZ($,Q)},signal:J.signal,input:J.input,output:J.output,validate:J.validate,render(){let $=`${z.gray(H)}
${f(this.state)} ${J.message}
`,Q=this.userInput,Y=String(this.value??""),q=this.options,U=J.placeholder,F=Y===""&&U!==void 0;switch(this.state){case"submit":{let X=g0(this.selectedValues,q),j=X.length>0?` ${z.dim(X.map(mJ).join(", "))}`:"";return`${$}${z.gray(H)}${j}`}case"cancel":{let X=Q?` ${z.strikethrough(z.dim(Q))}`:"";return`${$}${z.gray(H)}${X}`}default:{let X="";if(this.isNavigating||F){let L=F?U:Q;X=L!==""?` ${z.dim(L)}`:""}else X=` ${this.userInputWithCursor}`;let j=this.filteredOptions.length!==q.length?z.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",G=this.filteredOptions.length===0?[]:ZJ({cursor:this.cursor,options:this.filteredOptions,style:(L,P)=>{let D=mJ(L),M=L.hint&&L.value===this.focusedValue?z.dim(` (${L.hint})`):"";return P?`${z.green(FJ)} ${D}${M}`:`${z.dim(jJ)} ${z.dim(D)}${M}`},maxItems:J.maxItems,output:J.output}),V=[`${z.dim("\u2191/\u2193")} to select`,`${z.dim("Enter:")} confirm`,`${z.dim("Type:")} to search`],W=this.filteredOptions.length===0&&Q?[`${z.cyan(H)} ${z.yellow("No matches found")}`]:[],K=this.state==="error"?[`${z.yellow(H)} ${z.yellow(this.error)}`]:[];return[`${$}${z.cyan(H)}`,`${z.cyan(H)} ${z.dim("Search:")}${X}${j}`,...W,...K,...G.map((L)=>`${z.cyan(H)} ${L}`),`${z.cyan(H)} ${z.dim(V.join(" \u2022 "))}`,`${z.cyan(x)}`].join(`
`)}}}}).prompt()}function v$(J){let Z=(Q,Y,q,U)=>{let F=q.includes(Q.value),X=Q.label??String(Q.value??""),j=Q.hint&&U!==void 0&&Q.value===U?z.dim(` (${Q.hint})`):"",G=F?z.green(s):z.dim(RJ);if(Y)return`${G} ${X}${j}`;return`${G} ${z.dim(X)}`},$=new AJ({options:J.options,multiple:!0,filter:(Q,Y)=>{return PZ(Q,Y)},validate:()=>{if(J.required&&$.selectedValues.length===0)return"Please select at least one item";return},initialValue:J.initialValues,signal:J.signal,input:J.input,output:J.output,render(){let Q=`${z.gray(H)}
${f(this.state)} ${J.message}
`,Y=this.userInput,q=J.placeholder,U=Y===""&&q!==void 0,F=this.isNavigating||U?z.dim(U?q:Y):this.userInputWithCursor,X=this.options,j=this.filteredOptions.length!==X.length?z.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${Q}${z.gray(H)} ${z.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${Q}${z.gray(H)} ${z.strikethrough(z.dim(Y))}`;default:{let G=[`${z.dim("\u2191/\u2193")} to navigate`,`${z.dim("Space:")} select`,`${z.dim("Enter:")} confirm`,`${z.dim("Type:")} to search`],V=this.filteredOptions.length===0&&Y?[`${z.cyan(H)} ${z.yellow("No matches found")}`]:[],W=this.state==="error"?[`${z.cyan(H)} ${z.yellow(this.error)}`]:[],K=ZJ({cursor:this.cursor,options:this.filteredOptions,style:(L,P)=>Z(L,P,this.selectedValues,this.focusedValue),maxItems:J.maxItems,output:J.output});return[Q,`${z.cyan(H)} ${z.dim("Search:")} ${F}${j}`,...V,...W,...K.map((L)=>`${z.cyan(H)} ${L}`),`${z.cyan(H)} ${z.dim(G.join(" \u2022 "))}`,`${z.cyan(x)}`].join(`
`)}}}});return $.prompt()}function S$(J){let Z=J.active??"Yes",$=J.inactive??"No",Q=n(J.message);return new YZ({active:Z,inactive:$,signal:J.signal,input:J.input,output:J.output,initialValue:J.initialValue??!0,render(){let Y=`${z.gray(H)}
${f(this.state)} ${Q}
`,q=this.value?Z:$;switch(this.state){case"submit":return`${Y}${z.gray(H)} ${z.dim(q)}`;case"cancel":return`${Y}${z.gray(H)} ${z.strikethrough(z.dim(q))}
${z.gray(H)}`;default:return`${Y}${z.cyan(H)} ${this.value?`${z.green(FJ)} ${Z}`:`${z.dim(jJ)} ${z.dim(Z)}`} ${z.dim("/")} ${!this.value?`${z.green(FJ)} ${$}`:`${z.dim(jJ)} ${z.dim($)}`}
${z.cyan(x)}
`}}}).prompt()}async function y$(J,Z){let $={},Q=Object.keys(J);for(let Y of Q){let q=J[Y],U=await q({results:$})?.catch((F)=>{throw F});if(typeof Z?.onCancel==="function"&&D0(U)){$[Y]="canceled",Z.onCancel({results:$});continue}$[Y]=U}return $}function g$(J){let{selectableGroups:Z=!0,groupSpacing:$=0}=J,Q=(q,U,F=[])=>{let X=q.label??String(q.value),j=typeof q.group==="string",G=j&&(F[F.indexOf(q)+1]??{group:!0}),V=j&&G.group===!0,W=j?Z?`${V?x:H} `:" ":"",K="";if($>0&&!j){let P=`
${z.cyan(H)}`;K=`${P.repeat($-1)}${P} `}if(U==="active")return`${K}${z.dim(W)}${z.cyan(OJ)} ${X}${q.hint?` ${z.dim(`(${q.hint})`)}`:""}`;if(U==="group-active")return`${K}${W}${z.cyan(OJ)} ${z.dim(X)}`;if(U==="group-active-selected")return`${K}${W}${z.green(s)} ${z.dim(X)}`;if(U==="selected"){let P=j||Z?z.green(s):"";return`${K}${z.dim(W)}${P} ${z.dim(X)}${q.hint?` ${z.dim(`(${q.hint})`)}`:""}`}if(U==="cancelled")return`${z.strikethrough(z.dim(X))}`;if(U==="active-selected")return`${K}${z.dim(W)}${z.green(s)} ${X}${q.hint?` ${z.dim(`(${q.hint})`)}`:""}`;if(U==="submitted")return`${z.dim(X)}`;let L=j||Z?z.dim(RJ):"";return`${K}${z.dim(W)}${L} ${z.dim(X)}`},Y=J.required??!0;return new qZ({options:J.options,signal:J.signal,input:J.input,output:J.output,initialValues:J.initialValues,required:Y,cursorAt:J.cursorAt,selectableGroups:Z,validate(q){if(Y&&(q===void 0||q.length===0))return`Please select at least one option.
${z.reset(z.dim(`Press ${z.gray(z.bgWhite(z.inverse(" space ")))} to select, ${z.gray(z.bgWhite(z.inverse(" enter ")))} to submit`))}`},render(){let q=`${z.gray(H)}
${f(this.state)} ${J.message}
`,U=this.value??[];switch(this.state){case"submit":{let F=this.options.filter(({value:j})=>U.includes(j)).map((j)=>Q(j,"submitted")),X=F.length===0?"":` ${F.join(z.dim(", "))}`;return`${q}${z.gray(H)}${X}`}case"cancel":{let F=this.options.filter(({value:X})=>U.includes(X)).map((X)=>Q(X,"cancelled")).join(z.dim(", "));return`${q}${z.gray(H)} ${F.trim()?`${F}
${z.gray(H)}`:""}`}case"error":{let F=this.error.split(`
`).map((X,j)=>j===0?`${z.yellow(x)} ${z.yellow(X)}`:` ${X}`).join(`
`);return`${q}${z.yellow(H)} ${this.options.map((X,j,G)=>{let V=U.includes(X.value)||X.group===!0&&this.isGroupSelected(`${X.value}`),W=j===this.cursor;if(!W&&typeof X.group==="string"&&this.options[this.cursor].value===X.group)return Q(X,V?"group-active-selected":"group-active",G);if(W&&V)return Q(X,"active-selected",G);if(V)return Q(X,"selected",G);return Q(X,W?"active":"inactive",G)}).join(`
${z.yellow(H)} `)}
${F}
`}default:{let F=this.options.map((j,G,V)=>{let W=U.includes(j.value)||j.group===!0&&this.isGroupSelected(`${j.value}`),K=G===this.cursor,L=!K&&typeof j.group==="string"&&this.options[this.cursor].value===j.group,P="";if(L)P=Q(j,W?"group-active-selected":"group-active",V);else if(K&&W)P=Q(j,"active-selected",V);else if(W)P=Q(j,"selected",V);else P=Q(j,K?"active":"inactive",V);return`${G!==0&&!P.startsWith(`
`)?" ":""}${P}`}).join(`
${z.cyan(H)}`),X=F.startsWith(`
`)?"":" ";return`${q}${z.cyan(H)}${X}${F}
${z.cyan(x)}
`}}}}).prompt()}function m0(J){if(Array.isArray(J))return J.map((Z)=>n(Z));return n(J)}var k={message:(J=[],{symbol:Z=z.gray(H),secondarySymbol:$=z.gray(H),output:Q=f0.stdout,spacing:Y=1}={})=>{let q=[];for(let X=0;X<Y;X++)q.push(`${$}`);let U=m0(J),F=Array.isArray(U)?U:U.split(`
`);if(F.length>0){let[X,...j]=F;if(X.length>0)q.push(`${Z} ${X}`);else q.push(Z);for(let G of j)if(G.length>0)q.push(`${$} ${G}`);else q.push($)}Q.write(`${q.join(`
`)}
`)},info:(J,Z)=>{k.message(J,{...Z,symbol:z.blue(WZ)})},success:(J,Z)=>{k.message(J,{...Z,symbol:z.green(DZ)})},step:(J,Z)=>{k.message(J,{...Z,symbol:z.green(t)})},warn:(J,Z)=>{k.message(J,{...Z,symbol:z.yellow(LZ)})},warning:(J,Z)=>{k.warn(J,Z)},error:(J,Z)=>{k.message(J,{...Z,symbol:z.red(MZ)})},custom:(J,Z,$,Q)=>{let Y=typeof $==="string"?(q)=>z[$]?.(q)||q:$;k.message(Z,{...Q,symbol:Y(J),secondarySymbol:Y(J)})}};function m$(J="",Z){(Z?.output??xJ.stdout).write(`${z.gray(x)} ${z.red(J)}
`)}function d$(J="",Z){(Z?.output??xJ.stdout).write(`${z.gray(C0)} ${J}
`)}function u$(J="",Z){(Z?.output??xJ.stdout).write(`${z.gray(H)}
${z.gray(x)} ${J}
`)}function c$(J){let Z=(Q,Y)=>{let q=Q.label??String(Q.value);if(Y==="active")return`${z.cyan(OJ)} ${q}${Q.hint?` ${z.dim(`(${Q.h