UNPKG

@dovenv/utils

Version:
50 lines (47 loc) 59.3 kB
import{hexToRgb as uo,hslToRgb as po,xyzToCIELab as ho,rgbToXyz as mo,rgbToHsl as fo,rgbToCIELab as go,rgbToHex as wo}from"@vibrant/color";import yo from"chalk";import $o from"chroma-js";import{highlight as Eo}from"cli-highlight";import bo from"gradient-string";import xo from"figures";import ge from"terminal-link";import de from"cli-table3";export{default as Table}from"cli-table3";import ko from"columnify";import{boxen as vo}from"@visulima/boxen";import d,{argv as rt}from"node:process";export{default as process}from"node:process";import Po from"terminal-size";export{default as terminalSize}from"terminal-size";import{globby as Ao,globbyStream as Fo}from"globby";import{createWriteStream as To}from"node:fs";export{createWriteStream}from"node:fs";import{rename as we,writeFile as ye,readdir as jo,readFile as Co,rm as So,unlink as $e,stat as jt,mkdir as Ee,access as Ct,constants as Lo,copyFile as Do,lstat as Ro,symlink as St}from"node:fs/promises";import be,{homedir as No,tmpdir as Oo,platform as Mo,arch as Uo}from"node:os";import{resolve as xe,relative as Io,extname as Bo,dirname as zo,basename as mt,isAbsolute as Lt,normalize as _o,join as T}from"node:path";import{pathToFileURL as ke,fileURLToPath as Wo}from"node:url";export{fileURLToPath}from"node:url";import{LocalStorage as Go}from"node-localstorage";import*as ve from"open";import Ho from"supports-hyperlinks";export{default as supportsHyperlinks}from"supports-hyperlinks";import{createRequire as Vo}from"module";import{spawn as Dt,exec as Pe,fork as Ae,execSync as Zo}from"node:child_process";import{npmRunPathEnv as Fe}from"npm-run-path";import{resolve as Jo}from"path";import{matcher as qo}from"matcher";import*as Te from"node-emoji";export{Te as emoji};import Xo from"string-width";export{default as stringWidth}from"string-width";import{deepmergeCustom as je}from"deepmerge-ts";export{deepmerge,deepmergeCustom}from"deepmerge-ts";import*as Ce from"@structium/csv";export{Ce as csv};import*as Se from"@structium/ini";export{Se as ini};import*as Yo from"@structium/svg";export{Yo as svg};import*as Le from"@structium/toml";export{Le as toml};import*as De from"@structium/xml";export{De as xml};import*as Re from"@structium/yaml";export{Re as yaml};import{zip as Rt,tar as Nt,tgz as Ot,gzip as Ne}from"compressing";export{gzip,tar,tgz,zip}from"compressing";import Ko from"yargs";import{hideBin as Qo}from"yargs/helpers";import Oe from"log-update";import*as O from"@clack/prompts";import{TextPrompt as tn}from"@clack/core";import en from"enquirer";import{consola as rn}from"consola";import on from"ora";import{performance as Me}from"node:perf_hooks";import nn from"pretty-ms";import{Tree as an}from"@ascii-kit/tree";import{Validator as sn}from"@cfworker/json-schema";import{compile as cn}from"json-schema-to-typescript-lite";import{jsonSchemaToZod as ln}from"json-schema-to-zod";import{toJSONSchema as un,z as ft,ZodError as pn}from"zod/v4";import{promisify as Ue}from"node:util";import{pipeline as hn}from"node:stream";import{html as mn}from"@structium/html-markdown";export{html,markdown}from"@structium/html-markdown";export{qrcode}from"@ascii-kit/qr";import{PNG as fn}from"pngjs";import gn from"quantize";const dn=$o,wn={rgb2hex:wo,rgb2CIELab:go,rgb2sl:fo,rgb2xyz:mo,xyz2CIELab:ho,hslToRgb:po,hex2rgb:uo},Ie=(t,e)=>Eo(t,e),m=yo,yn=(t,e,r)=>bo(e,r).multiline(t);class Mt{constructor(e,r={}){this.resources=e,this.options=r}#t=new Map;options;#e(e){if(!this.options.debug)return{stop:()=>{}};const r=performance.now();return{stop:()=>{const o=performance.now();console.log(`Resource ${String(e)} loaded in ${(o-r).toFixed(2)}ms`)}}}async get(e){const r=this.#e(e);if(this.#t.has(e)){const n=this.#t.get(e);return r.stop(),n}const o=this.resources[e];if(!o)throw new Error(`No load function found for ${e.toString()}`);try{const n=await o();return this.#t.set(e,n),r.stop(),n}catch(n){throw console.error(`Error loading resource ${e.toString()}:`,n),n}}}const Be=new Mt({font:async()=>(await import("@ascii-kit/font")).Font}),$n=xo,ze=async(t,e,r)=>{const o=await Be.get("font");return await new o(e).text(t,{horizontalLayout:"default",verticalLayout:"default",whitespaceBreak:!0,...r||{}})},En=async(t,e,r)=>{const o=await fetch(`https://unpkg.com/@ascii-kit/fonts-flf/dist/${e}.flf`);if(!o.ok)throw new Error(`Error getting file: ${o.statusText}`);const n=await o.text();return await ze(t,n,r)},bn=(t,e)=>ge.isSupported?ge(t,e):e,_e=(t,e)=>{const r=new de(e);return r.push(...t),r.toString()},We=(t,e)=>ko(t,e),gt=(t,e)=>vo(t,e),dt=typeof window<"u"&&typeof window.document<"u",xn=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,kn=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",vn=typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&"userAgent"in navigator&&typeof navigator.userAgent=="string"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),Pn=typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u",An=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,Ge=t=>{const e=t.process||d,r=Array.isArray(t.type)?t.type:[t.type||"stdout"],o={},n=a=>{o[a]=e[a].write,e[a].write=(i,...s)=>{const c=typeof i=="string"?i:i.toString(),l=t.fn({data:c,type:a});return o[a]?.call(e[a],l,...s)}};return{start:()=>{for(const a of r)n(a)},stop:()=>{for(const a of r)o[a]&&(e[a].write=o[a])}}},Fn=t=>Ge({process:t.process,type:t.type,fn:({data:e,type:r})=>{let o=t.transform?t.transform({data:e,type:r}):e;for(const[n,a]of Object.entries(t.params))o=o.replace(new RegExp(n,"g"),a);return o}}),He=t=>{const e=Array.isArray(t.type)?t.type:[t.type||"log"],r={},o=n=>{r[n]=console[n],console[n]=(...a)=>{const i=a.map(s=>{const c=typeof s=="string"?s:JSON.stringify(s);return t.fn({data:c,type:n})});r[n]?.call(console,...i)}};return{start:()=>{for(const n of e)o(n)},stop:()=>{for(const n of e)r[n]&&(console[n]=r[n])}}},Tn=t=>He({type:t.type,fn:({data:e,type:r})=>{let o=t.transform?t.transform({data:e,type:r}):e;for(const[n,a]of Object.entries(t.params))o=o.replace(new RegExp(n,"g"),a);return o}}),jn=()=>d.env.NODE_ENV!=="production",Cn=()=>{d.noDeprecation=!0},Sn=()=>({show:()=>{d.noDeprecation=!1},hide:()=>{d.noDeprecation=!0}}),Ln=t=>{d.on("exit",t)},Dn=t=>{d.on("SIGINT",t)},Rn=()=>{d.exit(130)},ot=t=>{const e=(p,u)=>p*u/100,{lineChar:r,title:o,titleAlign:n,align:a,lineColor:i}=t;let{width:s}=t;(s<1||s>100)&&(s=100);const{columns:c}=Po(),l=e(c,s);return gt("",{headerText:o===""?void 0:o,borderStyle:{top:r,topLeft:"",topRight:"",left:"",right:"",bottomRight:"",bottomLeft:"",bottom:""},borderColor:i,headerAlignment:n,float:a,padding:0,margin:0,width:l}).trimEnd()},Nn=t=>{let e="";const{title:r="",lineChar:o="\u23AF",align:n="center",titleAlign:a="center",width:i=100,lineColor:s,lineDim:c=!1}=t||{},l={align:n,width:i,lineColor:s,lineDim:c,titleAlign:a.replace("top-","").replace("bottom-","")};return a.startsWith("bottom")?(e+=ot({lineChar:o,...l}),e+=` `,e+=ot({title:r,lineChar:" ",...l})):a.startsWith("top")?(e+=ot({title:r,lineChar:" ",...l}),e+=` `,e+=ot({lineChar:o,...l})):e+=ot({lineChar:o,title:r,...l}),e},S=xe,On=Io,nt=Bo,j=zo,M=mt,Ve=Lt,Mn=_o,Un=we,Ze=ye,L=Ao,In=Fo,Bn=(t,e)=>{const r=S(t),o=S(e);return r===o},zn=t=>ke(S(t)).href,Je=t=>{if((Lt(t)||/^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(t))&&(Lt(t)||/^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(t))){if(/\s(?!\\)/.test(t)&&!/\\\s/.test(t))return!1;try{return T(t)!==""}catch{return!1}}return!1},U=async t=>{await yt(t)||await tr(t)},wt=async t=>(t=v(t),await jo(t,{withFileTypes:!0}));async function _n({path:t,extensions:e=[]}){return(await wt(t)).filter(r=>{const o=nt(r.name);return e.includes(o)}).map(r=>M(r.name,nt(r.name)))}const Wn=(t=import.meta.url)=>j(Wo(t));function g(...t){try{return T(...t)}catch(e){throw new Error(`Failed to join path (${t.join(", ")}): - `+(e instanceof Error?e.message:e?.toString()))}}const qe=xe;function v(t){let e=t;return t.startsWith("~/")&&(e=t.replace(/^~(?=$|\/|\\)/,No())),qe(e)}const I=Co,Gn=async(t,e)=>{const r=await L(t,{dot:!0,...e?.inputOpts,onlyFiles:!0});return await Promise.all(r.map(async o=>{try{const n=await I(o,"utf8"),a={path:o,content:n};return await e?.hook?.onFile?.(a),a}catch(n){throw new Error(`Error reading file ${o}: ${n instanceof Error?n.message:n?.toString()}`)}}))};async function Xe(t){try{t=v(t),await So(t,{recursive:!0,force:!0})}catch(e){throw new Error(`Error removing ${t}: ${e.message}`)}}async function Ye(t){t=v(t),await yt(t)&&await Xe(t)}async function Hn(t){t=v(t),await Ut(t)?await Ye(t):await Ke(t)}async function Ke(t){t=v(t),await D(t)&&await $e(t)}async function Qe(t){await $e(t)}async function Ut(t){return t=v(t),(await jt(t)).isDirectory()}async function tr(t){try{t=v(t),await Ee(t,{recursive:!0})}catch(e){throw Error(`Error creating the directory: ${e}`)}}async function yt(t){try{return t=v(t),await Ct(t,Lo.F_OK),(await jt(t)).isDirectory()}catch{return!1}}async function D(t){try{return t=v(t),await Ct(t),(await jt(t)).isFile()}catch{return!1}}async function Vn(t,e){t=v(t),await ye(t,e)}async function at(t){return await D(t)?!0:await yt(t)}const er=async({input:t,output:e})=>{try{await Do(t,e)}catch(r){console.error(r)}},Zn=async({input:t,output:e})=>{try{const r=async({input:o,output:n})=>{const a=await wt(o);await U(n);for(const i of a){const s=T(o,i.name),c=T(n,i.name);i.isDirectory()?await r({input:s,output:c}):await er({input:s,output:c})}};await r({input:t,output:e})}catch(r){console.error(`\u{1F4C1} Error copying directory: ${r.message}`)}},Jn=async({input:t,output:e})=>{try{await Ct(e)}catch(n){if(n.code==="ENOENT")await Ee(e,{recursive:!0});else throw`\u274C\u{1F517} ${n}`}const r=await Ro(t),o=process.platform==="win32";r.isDirectory()?o?await St(t,T(e,mt(t)),"junction"):await St(t,T(e,mt(t)),"dir"):r.isFile()&&await St(t,T(e,mt(t))),console.log(`\u{1F517} symlink: "${t}" to "${e}".`)};function qn(t){return new Go(t)}const Xn=ve.default,Yn=ve.openApp,A=async t=>t.then(e=>[void 0,e]).catch(e=>[e]);class rr extends Error{data;constructor(e,r){super(e),this.data=r,Error.captureStackTrace(this,this.constructor)}}const Kn=t=>{try{return Vo(Jo(d.cwd(),"./")).resolve(t)}catch{}try{const e=import.meta.resolve(t);return new URL(e).pathname}catch{return}};class or extends Error{}const Qn=async({name:t,opts:e})=>{const r=Fe(e);if(!r.PATH)return;const o=r.PATH.split(":").filter(n=>n.endsWith("node_modules/.bin"));for(const n of o){const a=g(n,t);if(await at(a))return a}},ta=async({name:t,args:e,opts:r})=>new Promise((o,n)=>{const a=Fe(r),i=Dt(t,e||[],{env:a,cwd:r?.cwd||d.cwd(),shell:!0,stdio:"inherit"});i.on("error",s=>{"code"in s&&s.code==="ENOENT"||"code"in s&&s.code==="MODULE_NOT_FOUND"?n(new or(`Command '${t}' not found.`)):n(new Error(`Failed to execute '${t}': ${s.message}`))}),i.on("close",s=>{s!==0?n(new Error(`Process '${t}' exited with code ${s}`)):o(s)})}),ea=async t=>{await new Promise((e,r)=>{Dt(t,{shell:!0,stdio:"inherit"}).on("close",o=>{if(o===0)e();else{const n=new Error(`Command failed with code ${o}`);console.error(n),r(n)}})})},nr=async t=>new Promise((e,r)=>{const o=Dt(t,{shell:!0,stdio:"pipe"});let n="",a="";o.stdout?.on("data",i=>{n+=i.toString()}),o.stderr?.on("data",i=>{a+=i.toString()}),o.on("close",i=>{i===0?e({stdout:n,stderr:a}):r({code:i,stdout:n,stderr:a})}),o.on("error",i=>{r(i)})}),ra=async t=>{const{name:e,on:r,onError:o,onExit:n,onSuccess:a}=t,i=d.argv.includes("--debug"),s=l=>` \u{1F426}${l} [${e}]`,c={debug:l=>{i&&console.debug(s("\u2B1B\uFE0F"),l)},info:l=>console.log(s("\u{1F7E6}"),l),success:l=>console.log(s("\u{1F7E2}"),l),warn:l=>console.warn(s("\u{1F7E1}"),l),error:l=>console.error(s("\u{1F534}")+" Error: ",l),box:l=>console.log(` ${gt(l,{padding:1,headerText:s("\u{1F7E6}").trimStart()})}`)};try{c.info(`Init process `),console.group(),await r({log:c}),console.groupEnd(),a?await a({log:c}):c.success(`Process executed successfully `)}catch(l){console.groupEnd(),l.name==="ExitPromptError"?n?await n({log:c}):c.warn("Exit from process"):o?await o({log:c,error:l}):c.error(l)}},oa=t=>A(new Promise((e,r)=>{Pe(t,(o,n,a)=>{if(o){r({error:o,stdout:n,stderr:a});return}e(n)})})),na=async({module:t,args:e=[]})=>{const r=await zt(t);await new Promise((o,n)=>{Ae(r,e,{stdio:"inherit"}).on("close",a=>a===0?o():(console.warn(`[${t.id}] exited with code ${a}`),n()))})},aa=async({module:t,args:e=[]})=>{const r=await zt(t);return new Promise((o,n)=>{const a=Ae(r,e,{stdio:["pipe","pipe","pipe","ipc"]});let i="",s="";a.stdout&&a.stdout.on("data",c=>i+=c.toString()),a.stderr&&a.stderr.on("data",c=>s+=c.toString()),a.on("close",c=>c===0?o({stdout:i,stderr:s}):(console.warn(`[${t.id}] exited with code ${c}`),n(new Error(`Process exited with code ${c}`)))),a.on("error",c=>{n(c)})})},ar=async t=>{const e=d.platform==="win32"?`where ${t}`:`which ${t}`;try{return await nr(e),!0}catch{return!1}},sa=async t=>{const e={},r=t.map(async o=>{const n=await ar(o);e[o]=n});return await Promise.all(r),e},ia=(t,e)=>{const r=sr(t);if(r&&Object.values(e).includes(r))return r},sr=t=>{const e=t.length===1?"-":"--",r=rt;for(let o=0;o<r.length;o++){const n=r[o];if(n.startsWith(`${e}${t}=`))return n.split("=")[1];if(n===`${e}${t}`&&r[o+1]&&!r[o+1].startsWith(e))return r[o+1]}},ca=t=>{const e=rt,r=t.length===1?"-":"--";let o=[];for(let n=0;n<e.length;n++){const a=e[n];if(a.startsWith(`${r}${t}=`)){o=a.split("=")[1].split(",");break}if(a===`${r}${t}`){for(let i=n+1;i<e.length&&!e[i].startsWith(r);i++)o.push(e[i]);break}}return o.length>0?o:void 0},la=t=>{const e=t.length===1?"-":"--";return rt.includes(`${e}${t}`)},ua=t=>rt.includes(t),pa=()=>rt.length>2,ha=Qo,ma=async({args:t=process.argv,fn:e})=>{const r=Ko(t);return await e(r),r.help(),r.parse(),r},fa=({frames:t,interval:e=100,clear:r=!1})=>{let o=!1,n=0,a=null;return{start:()=>{o||(o=!0,a=setInterval(()=>{Oe(t[n]),n=(n+1)%t.length},e))},stop:()=>{o&&(o=!1,a&&(clearInterval(a),a=null),r&&Oe.clear())}}},ga=()=>d.platform!=="win32"?d.env.TERM!=="linux":!!d.env.WT_SESSION||!!d.env.TERMINUS_SUBLIME||d.env.ConEmuTask==="{cmd::Cmder}"||d.env.TERM_PROGRAM==="Terminus-Sublime"||d.env.TERM_PROGRAM==="vscode"||d.env.TERM==="xterm-256color"||d.env.TERM==="alacritty"||d.env.TERMINAL_EMULATOR==="JetBrains-JediTerm",da=ga(),H=(t,e)=>da?t:e,P={STEP_ACTIVE:H("\u25C6","*"),STEP_CANCEL:H("\u25A0","x"),STEP_ERROR:H("\u25B2","x"),STEP_SUBMIT:H("\u25C7","o"),BAR:H("\u2502","|"),BAR_END:H("\u2514","\u2014")},ir=t=>{if(t==="initial"||t==="active")return m.cyan(P.STEP_ACTIVE);if(t==="cancel")return m.red(P.STEP_CANCEL);if(t==="error")return m.yellow(P.STEP_ERROR);if(t==="submit")return m.green(P.STEP_SUBMIT)};async function wa(t){return new tn({validate:e=>{const r="Value must be a number without",o=/\s/.test(e),n=typeof Number(e)=="number"&&!isNaN(Number(e));if(!e||!n||o)return t.errorText?t.errorText:r;if(t.validate)return t.validate(e)},placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,render(){const e=`${m.gray(P.BAR)} ${ir(this.state)} ${t.message} `,r=t.placeholder?m.inverse(t.placeholder[0])+m.dim(t.placeholder.slice(1)):m.inverse(m.hidden("_")),o=this.value?this.valueWithCursor:r;switch(this.state){case"error":return`${e.trim()} ${m.yellow(P.BAR)} ${o} ${m.yellow(P.BAR_END)} ${m.yellow(this.error)} `;case"submit":return`${e}${m.gray(P.BAR)} ${m.dim(this.value||t.placeholder)}`;case"cancel":return`${e}${m.gray(P.BAR)} ${m.strikethrough(m.dim(this.value??""))}${this.value?.trim()?` `+m.gray(P.BAR):""}`;default:return`${e}${m.cyan(P.BAR)} ${o} ${m.cyan(P.BAR_END)} `}}}).prompt()}const It={message:"message"};async function cr(t){return en.prompt(t)}const lr=async(t,e)=>{O.log.message();const r="id",o=await cr({...t,name:r,prefix:n=>{let a="active";return n.cancelled&&(a="cancel"),n.submitted&&(a="submit"),n.error!==""&&(a="error"),ir(a)},onCancel:async()=>{O.log.message(),e&&await e()}});return O.log.message(),r in o?o[r]:void 0},ya={table:({value:t,opts:e,type:r=It.message})=>O.log[r](_e(t,e)),columns:({value:t,opts:e,type:r=It.message})=>O.log[r](We(t,e)),box:({value:t,opts:e,type:r=It.message})=>O.log[r](gt(t,e))},$t=O,$a=lr,Bt={...$t,log:{...$t.log,errorWithExit:t=>{$t.log.error(t),console.log(),d.exit(1)}},number:wa,...ya};async function Ea(t){t.onCancel||(t.onCancel=async n=>{n.cancel("canceled \u{1F494}"),d.exit(0)});const e={...Bt,typePrompt:n=>lr(n,()=>t.onCancel?.(Bt))};t.intro&&e.intro(t.intro);const r=await t.list(e),o=await e.group(r,{onCancel:()=>t.onCancel?.(e)});return t.outro&&(e.log.step(""),e.outro(t.outro)),o}const ba=rn,xa=on,ka=()=>{const t=Me.now(),e=()=>Me.now()-t;return{stop:()=>e()/1e3,prettyStop:()=>nn(e())}},va=async t=>new Promise(e=>setTimeout(e,t)),ur=()=>{const t=new Date,e=t.getUTCFullYear().toString(),r=("0"+(t.getUTCMonth()+1)).slice(-2),o=("0"+t.getUTCDate()).slice(-2),n=("0"+t.getUTCHours()).slice(-2),a=("0"+t.getUTCMinutes()).slice(-2),i=("0"+t.getUTCSeconds()).slice(-2);return{year:e,month:r,day:o,hours:n,minutes:a,seconds:i}},Pa=()=>{const t=ur();return`${t.year}-${t.month}-${t.day}T${t.hours}:${t.minutes}:${t.seconds}Z`},zt=async({from:t=d.cwd(),id:e,path:r})=>{const o=class extends Error{};try{const n=e,a=n.includes("/")?n.startsWith("@")?n.split("/").slice(0,2).join("/"):n.split("/")[0]:n,i=`Module [${g(n,...r||[])}] not found. `,s=(await import("node:module")).default.createRequire(t).resolve.paths(n);if(!s)throw new o(i+"Failed in resolve.paths");let c=s.map(l=>g(l,a)).find(async l=>await at(l));if(!c)throw new o(i+"Failed in lookupPaths");if(r&&(c=g(c,...r)),!await at(c))throw new o(i+"Path does not exist");return c}catch(n){const a=` Error information: - Make sure the package [${e}] is installed correctly.`;throw n instanceof o?(n.message+=a,n):new Error(`It could not be located ${g(e,...r||[])}.`+a)}},Aa=async t=>{const{content:e,params:r,transform:o,opts:n}=t,{prefix:a,suffix:i}=n?.mark||{prefix:"{{",suffix:"}}"},s=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`${s(a)}\\s*([^}]+?)\\s*${s(i)}`,"g"),l=(E,$)=>{const f=$.split(".");let h=E;for(const x of f){if(h===void 0)return;if(x.includes("[")&&x.includes("]")){const[C,co]=x.split("["),lo=parseInt(co.replace("]",""),10);h=h[C]?.[lo]}else h=h[x]}return h},p=async(E,$)=>{if(o){const h=await o($);if(h!==$)return h}const f=l(r,$);if(f===void 0){if(n?.throw)throw new Error(`Placeholder ${$} not found`);return E}return String(f)};let u=e;const w=[...e.matchAll(c)];for(const E of w){const[$,f]=E,h=await p($,f);u=u.replace($,h)}return u},Et=t=>{const e=t.length,r=t.split(/\s+/).filter(Boolean).length;return{chars:e,words:r}},pr=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase(),_t=t=>t.charAt(0).toUpperCase()+t.slice(1),Fa=t=>t.replace(/([A-Z])/g,"_$1").toLowerCase(),hr=t=>t.replace(/-([a-z])/g,(e,r)=>r.toUpperCase()),Ta=t=>{const e=hr(t);return _t(e)},ja=t=>t.replace(/-/g,"_"),mr=t=>t.charAt(0).toLowerCase()+t.slice(1),Ca=t=>{const e=mr(t);return pr(e)},Sa=t=>t.replace(/([A-Z])/g,"_$1").toLowerCase(),fr=t=>t.replace(/_([a-z])/g,(e,r)=>r.toUpperCase()),La=t=>t.replace(/_/g,"-"),Da=t=>{const e=fr(t);return _t(e)},y="\x1B[",st="\x1B]",V="\x07",it=";",gr=!dt&&d.env.TERM_PROGRAM==="Apple_Terminal",Ra=!dt&&d.platform==="win32",Na=dt?()=>{throw new Error("`process.cwd()` only works in Node.js, not the browser.")}:d.cwd,Oa=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");return typeof e=="number"?`${y}${e+1}${it}${t+1}H`:`${y}${t+1}G`},Ma=(t,e=0)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");let r="";return t!==0&&(r+=y+Math.abs(t)+(t<0?"D":"C")),e!==0&&(r+=y+Math.abs(e)+(e<0?"A":"B")),r},dr=(t=1)=>`${y}${t}A`,Ua=(t=1)=>`${y}${t}B`,Ia=(t=1)=>`${y}${t}C`,Ba=(t=1)=>`${y}${t}D`,wr=`${y}G`,za=gr?"\x1B7":`${y}s`,_a=gr?"\x1B8":`${y}u`,Wa=`${y}6n`,Ga=`${y}E`,Ha=`${y}F`,Va=`${y}?25l`,Za=`${y}?25h`,Ja=t=>{let e="";for(let r=0;r<t;r++)e+=yr+(r<t-1?dr():"");return e+wr},qa=`${y}K`,Xa=`${y}1K`,yr=`${y}2K`,Ya=`${y}J`,Ka=`${y}1J`,Wt=`${y}2J`,Qa=`${y}S`,ts=`${y}T`,es="\x1Bc",rs=Ra?`${Wt}${y}0f`:`${Wt}${y}3J${y}H`,os=`${y}?1049h`,ns=`${y}?1049l`,as=V,$r=(t,e)=>[st,"8",it,it,e,V,t,st,"8",it,it,V].join(""),ss=(t,e={})=>{let r=`${st}1337;File=inline=1`;return e.width&&(r+=`;width=${e.width}`),e.height&&(r+=`;height=${e.height}`),e.preserveAspectRatio===!1&&(r+=";preserveAspectRatio=0"),r+":"+Buffer.from(t).toString("base64")+V},is={setCwd(t=Na()){return`${st}50;CurrentDir=${t}${V}`},annotation(t,e={}){if((e.x!==void 0||e.y!==void 0)&&(e.x===void 0||e.y===void 0||e.length===void 0))throw new Error("`x`, `y`, and `length` must all be provided when using coordinates");const r=t.replace(/\|/g,""),o=`${st}1337;${e.isHidden?"AddHiddenAnnotation=":"AddAnnotation="}`,n=e.length?e.x!==void 0?[r,e.length,e.x,e.y].join("|"):[e.length,r].join("|"):r;return o+n+V}},cs={__proto__:null,beep:as,clearScreen:es,clearTerminal:rs,cursorBackward:Ba,cursorDown:Ua,cursorForward:Ia,cursorGetPosition:Wa,cursorHide:Va,cursorLeft:wr,cursorMove:Ma,cursorNextLine:Ga,cursorPrevLine:Ha,cursorRestorePosition:_a,cursorSavePosition:za,cursorShow:Za,cursorTo:Oa,cursorUp:dr,enterAlternativeScreen:os,eraseDown:Ya,eraseEndLine:qa,eraseLine:yr,eraseLines:Ja,eraseScreen:Wt,eraseStartLine:Xa,eraseUp:Ka,exitAlternativeScreen:ns,iTerm:is,image:ss,link:$r,scrollDown:ts,scrollUp:Qa},Er=({onlyFirst:t=!1}={})=>{const e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(e,t?void 0:"g")},ls=(t,e={})=>{if(!t)return t;const r=e.align||"center";let o,n=0,a=!1;if(r==="left")return t;const i=e.split||` `,s=e.pad||" ",c=r!=="right"?us:ps;return Array.isArray(t)||(a=!0,t=String(t).split(i)),t=t.map(l=>(l=String(l),o=Xo(l),n=Math.max(o,n),{str:l,width:o})).map(l=>new Array(c(n,l.width)+1).join(s)+l.str),a?t.join(i):t};function us(t,e){return Math.floor((t-e)/2)}function ps(t,e){return t-e}const hs={__proto__:null,align:ls},br=t=>{return e.withOptions=r=>br({...t,...r}),e;function e(r,...o){const n=typeof r=="string"?[r]:r.raw,{escapeSpecialCharacters:a=Array.isArray(r),trimWhitespace:i=!0}=t;let s="",c=null;for(let p=0;p<n.length;p++){let u=n[p];a&&(u=u.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=u,p<o.length&&(s+=o[p])}const l=s.split(` `);for(const p of l){const u=p.match(/^(\s+)\S+/);if(u){const w=u[1].length;c?c=Math.min(c,w):c=w}}if(c!==null){const p=c;s=l.map(u=>u[0]===" "||u[0]===" "?u.slice(p):u).join(` `)}return i&&(s=s.trim()),a&&(s=s.replace(/\\n/g,` `)),s}},ms=br({}),fs=(t,e)=>{const r={maxConsecutive:e?.maxConsecutive??0,trimStart:e?.trimStart??!1,trimEnd:e?.trimEnd??!1},o=t.split(` `);let n=0;const a=o.filter(i=>i.trim()===""?(n++,n<=r.maxConsecutive):(n=0,!0));if(r.trimStart)for(;a[0]?.trim()==="";)a.shift();if(r.trimEnd)for(;a[a.length-1]?.trim()==="";)a.pop();return[...a].join(` `)},gs=(t,e=" ")=>t.split(` `).map(r=>`${e}${r}`).join(` `),ds=t=>t.charAt(0).toUpperCase()+t.slice(1),ws=(t,e,r="\u2026")=>t.length<=e?t:t.slice(0,e).trimEnd()+r,ys=qo,B=t=>$s(t)?"url":Je(t)?"path":"text",$s=t=>{try{return new URL(t),!0}catch{return!1}},bt=(...t)=>(t=t.map(e=>e.replace(/^\/+|\/+$/g,"")),t.join("/")),Es=t=>JSON.stringify(t,null," ")+` `,Gt=()=>crypto.randomUUID(),xt=async t=>(t=v(t),(await I(t)).toString("utf8"));async function Z(t){try{const e=await fetch(t);return e.headers.get("content-type")?.includes("image")?`data:image/jpeg;base64,${Buffer.from(await e.arrayBuffer()).toString("base64")}`:await e.text()}catch(e){throw new Error(`Fetching URL Error: ${e.message}`)}}const bs=async t=>{const e=B(t);return e==="path"?await xt(t):e==="url"?await Z(t):t},xs=async(t,e)=>{const r=[];for(let o=0;o<t.length;o++){const n=t[o],a=B(n);if(a==="path"){const i=await L(n,e?.path);await Promise.all(i.map(async s=>r.push({type:a,path:s,id:M(j(s)),content:await xt(s)})))}else a==="url"?r.push({type:a,path:n,id:`${a}-${new URL(n).hostname}-${o}`,content:await Z(n)}):r.push({type:a,id:`${a}-${o}`,content:n})}return r},R=be.homedir(),Ht=be.tmpdir(),{env:J}=d,ks=t=>{const e=g(R,"Library");return{data:g(e,"Application Support",t),config:g(e,"Preferences",t),cache:g(e,"Caches",t),log:g(e,"Logs",t),temp:g(Ht,t)}},vs=t=>{const e=J.APPDATA||g(R,"AppData","Roaming"),r=J.LOCALAPPDATA||g(R,"AppData","Local");return{data:g(r,t,"Data"),config:g(e,t,"Config"),cache:g(r,t,"Cache"),log:g(r,t,"Log"),temp:g(Ht,t)}},Ps=t=>{const e=M(R);return{data:g(J.XDG_DATA_HOME||g(R,".local","share"),t),config:g(J.XDG_CONFIG_HOME||g(R,".config"),t),cache:g(J.XDG_CACHE_HOME||g(R,".cache"),t),log:g(J.XDG_STATE_HOME||g(R,".local","state"),t),temp:g(Ht,e,t)}},xr=({name:t,suffix:e="nodejs"})=>{if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),d.platform==="darwin"?ks(t):d.platform==="win32"?vs(t):Ps(t)},z=xt,kr=async t=>{try{const e=await z(t);return await Vt(e)}catch(e){throw new Error(`Error reading CSV file ${t}: ${e.message}`)}},Vt=async(t,e={})=>await Ce.deserialize(t,e),vr=async t=>{try{const e=await z(t);return await Zt(e)}catch(e){throw new Error(`Error reading INI file ${t}: ${e.message}`)}},Zt=async t=>await Se.deserialize(t),Pr=async(t,e="default")=>{try{t=v(t);const r=(await import(ke(t).href))[e];if(!r)throw new Error(`No [${e}] export found`);if(typeof r!="object")throw new Error("Export is not an object");return r}catch(r){throw r instanceof SyntaxError?new Error(`Syntax error in JS file ${t}: ${r.message}`):r instanceof Error&&r.code==="MODULE_NOT_FOUND"?new Error(`Module not found at ${t}: ${r.message}`):r instanceof TypeError?new Error(`Error accessing export [${e}] in ${t}: ${r.message}`):new Error(`Error reading JS file ${t}: ${r instanceof Error?r.message:String(r)}`)}},Ar=async(t,e="default")=>{const r=/export\s+default\s+({[^]*?});/,o=new RegExp(`export\\s+(const|let|var|function)\\s+${e}\\s*=\\s*({[^]*?});`);let n;const a=t.match(r);if(a&&a.length>1)n=a[1];else{const i=t.match(o);i&&i.length>2&&(n=i[2])}if(!n)throw new Error(`No export object found for "${e}".`);try{const i=new Function(`return ${n}`)();if(typeof i!="object"||i===null)throw new Error("The export is not a valid object.");return i}catch(i){throw new Error(`Error when loading the object from the Javascript content: ${i.message}`)}},kt=async t=>{try{const e=await z(t);return await ct(e)}catch(e){throw new Error(`Error reading JSON file ${t}: ${e.message}`)}},ct=async t=>JSON.parse(t),As={deserialize:ct,serialize:t=>JSON.stringify(t),parser:ct,stringify:t=>JSON.stringify(t)},Fr=async t=>{try{const e=await z(t);return await Jt(e)}catch(e){throw new Error(`Error reading TOML file ${t}: ${e.message}`)}},Jt=async t=>await Le.deserialize(t),Tr=async t=>{try{const e=await z(t);return await qt(e)}catch(e){throw new Error(`Error reading XML file ${t}: ${e.message}`)}},qt=async t=>{try{return De.deserialize(t)}catch(e){throw new Error(`Error parsing XML content: ${e.message}`)}},Xt=async t=>{try{const e=await z(t);return await Yt(e)}catch(e){throw new Error(`Error reading YAML file ${t}: ${e.message}`)}},Yt=async t=>await Re.deserialize(t),Fs=t=>(...e)=>{const r=(...o)=>je(t||{})(...o);if(e.length===1){const[o]=e;return Array.isArray(o)?r(...o):o}return r(...e)},F={json:"json",yml:"yml",yaml:"yaml",toml:"toml",js:"js",mjs:"mjs",ini:"ini",xml:"xml",csv:"csv"},Kt=async t=>{try{if(!await D(t))throw Error("File does not exists");let e;if(t.endsWith("."+F.json))e=await kt(t);else if(t.endsWith("."+F.yml)||t.endsWith("."+F.yaml))e=await Xt(t);else if(t.endsWith("."+F.toml))e=await Fr(t);else if(t.endsWith("."+F.js)||t.endsWith("."+F.mjs))e=await Pr(t);else if(t.endsWith("."+F.ini))e=await vr(t);else if(t.endsWith("."+F.csv))e=await kr(t);else if(t.endsWith("."+F.xml))e=await Tr(t);else throw new Error("Unsupported file format. Expected JSON, YAML or TOML.");if(typeof e!="object"||e===null)throw new Error("Data is not an object.");return e}catch(e){throw new Error(`Error reading file ${t}: ${e.message}`)}},Ts=async t=>{try{const e=await z(t),r=await vt(e);if(typeof r!="object"||r===null)throw new Error("Data is not an object.");return r}catch(e){throw new Error(`Error reading file ${t}: ${e.message}`)}},js=async(t,e)=>{try{const r=Object.values(F);for(let o=0;o<r.length;o++){const n=r[o],a=g(t,e+"."+n);if(await D(a))return await Kt(a)}throw Error("Path not exist")}catch(r){throw new Error(`Error reading file ${t} with filename ${e}: ${r.message}`)}},vt=async t=>{const[e,r]=await A(ct(t));if(!e&&r)return r;const[o,n]=await A(Yt(t));if(!o&&n)return n;const[a,i]=await A(Jt(t));if(!a&&i)return i;const[s,c]=await A(Ar(t));if(!s&&c)return c;const[l,p]=await A(Zt(t));if(!l&&p)return p;const[u,w]=await A(qt(t));if(!u&&w)return w;const[E,$]=await A(Vt(t));if(!E&&$&&Array.isArray($))return $;throw new Error("Cannot parse object from content")},Qt=async t=>{try{const e=await Z(t);return vt(e)}catch(e){throw new Error(`Error getting [${t}] data. ${e.message}`)}},te=async t=>{try{const e=B(t);return e==="url"?await Qt(t):e==="path"?await Kt(t):await vt(t)}catch(e){throw new Error(e.message)}},Cs=async t=>{const{id:e,values:r,projectName:o,cwd:n,suffix:a}=t,i=n||xr({name:o,suffix:a}).config,s=g(i,"config.json"),c={[e]:r},l=je({mergeArrays:!1}),p=async()=>{try{return await kt(s)}catch{return c}},u=async()=>{const h=await D(s);return h||await U(i),h?await p():c};let w=await u();const E=async h=>{const x=await u(),C=l(x,{[e]:h});await Ze(s,JSON.stringify(C,null,2)),w=C},$=async h=>typeof h=="string"?!w[e]||typeof w[e][h]>"u"?void 0:w[e][h]:w[e],f=async()=>await E(r);if(!await D(s))await E(r);else{const h=l({[e]:r},w);await E(h[e])}return{defaultValues:r,get:$,set:E,reset:f,path:s}},Ss=()=>Oo(),Ls=async()=>{switch(Mo()){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}};function Ds(){switch(Uo()){case"arm64":return"arm64";case"arm":return"arm64";case"x64":return"x64";default:return"unknown"}}const k={ZIP:"zip",TAR:"tar",TGZ:"tgz",GZ:"gz"},ee=k.ZIP,jr="auto",Pt=()=>process.cwd(),Rs=t=>t.toLowerCase().replace(".",""),re=t=>`Unsupported compression format: ${t}. Supported formats: ${Object.values(k).join(", ")}`,Ns=async t=>{const{input:e,output:r=Pt(),newName:o,remove:n=!1,format:a=jr,opts:i}=t,s=nt(e),c=a!==jr?a:Rs(s),l=o||M(e,s),p=g(r,l);if(c===k.ZIP)await Rt.uncompress(e,p,i?.zip||{strip:1});else if(c===k.TAR)await Nt.uncompress(e,p,i?.tar||{strip:1});else if(c===k.TGZ)await Ot.uncompress(e,p,i?.tgz||{strip:1});else if(c===k.GZ)await Ne.uncompress(e,p,i?.gzip||{strip:1});else throw new Error(re(a));return n&&await Qe(e),p},Os=async t=>{const{input:e,output:r=Pt(),hook:o,format:n=ee,inputOpts:a={}}=t;await U(r);const i=await L(e,{onlyFiles:!0,dot:!0,...a});await Promise.all(i.map(async s=>{await o?.beforeFile?.(s),await oe({input:s,output:r,name:M(s),format:n}),await o?.afterFile?.(s)}))},oe=async t=>{const{input:e,output:r=Pt(),name:o=Gt(),format:n=ee,opts:a}=t,i=`${o}.${n}`,s=g(r,i);if(await U(r),n===k.ZIP)await Rt.compressFile(e,s,a?.zip);else if(n===k.TAR)await Nt.compressFile(e,s,a?.tar);else if(n===k.TGZ)await Ot.compressFile(e,s,a?.tgz);else if(n===k.GZ)await Ne.compressFile(e,s,a?.gzip);else throw new Error(re(n));return s},Cr=async t=>{const{input:e,output:r=Pt(),name:o=Gt(),format:n=ee,opts:a}=t,i=`${o}.${n}`,s=g(r,i);if(await U(r),n===k.ZIP)await Rt.compressDir(e,s,a?.zip);else if(n===k.TAR)await Nt.compressDir(e,s,a?.tar);else if(n===k.TGZ)await Ot.compressDir(e,s,a?.tgz);else throw n===k.GZ?new Error("Gzip compression of directories is not supported."):new Error(re(n));return s},Ms=async t=>await Ut(t.input)?await Cr(t):await oe(t),Sr=async({input:t,opts:e})=>{let r=0,o=0;const n=await L(t,{onlyFiles:!0,...e||{}});for(const a of n){const i=await I(a,"utf-8"),s=Et(i);r+=s.chars,o+=s.words}return{files:n.length,chars:r,words:o}},Lr=async({input:t,opts:e})=>{const{chars:r,words:o}=await Sr({input:t,opts:e});return{chars:r,words:o}},Dr=async({input:t})=>{let e=0,r=0;for(const o of t){const n=await Z(o),a=Et(n);e+=a.chars,r+=a.words}return{chars:e,words:r}},Rr=async({input:t})=>{let e=0,r=0;for(const o of t){const n=Et(o);e+=n.chars,r+=n.words}return{chars:e,words:r}},Us=async({paths:t,url:e,content:r,opts:o})=>{try{const n={chars:0,words:0,paths:{chars:0,words:0},url:{chars:0,words:0},content:{chars:0,words:0}};if(t){const a=await Lr({input:t,opts:o?.paths});n.chars+=a.chars,n.words+=a.words,n.paths.chars+=a.chars,n.paths.words+=a.words}if(e){const a=await Dr({input:e});n.chars+=a.chars,n.words+=a.words,n.url.chars+=a.chars,n.url.words+=a.words}if(r){const a=await Rr({input:r});n.chars+=a.chars,n.words+=a.words,n.content.chars+=a.chars,n.content.words+=a.words}return n}catch(n){throw console.error("Error reading files:",n),n}},ne=t=>new an(t.structure,{hook:{onData:e=>(e.name=m[e.isFile?"green":"blue"](e.name),e.pattern={indent:m.gray.dim(e.pattern.indent),line:m.gray.dim(e.pattern.line),lastLine:m.gray.dim(e.pattern.lastLine)},e)},...t||{}}).generate(),Is=async t=>{if(!t.input)throw new Error("The 'input' path is required.");const e=t.max??1/0,r=t?.sort||"atoz",o=async(n,a)=>{if(a<=0)return{};const i=await wt(n),s={},c=i.sort((l,p)=>{const u=l.name.localeCompare(p.name);return r==="atoz"?u:-u});return await Promise.all(c.map(async l=>{const p=g(n,l.name);l.isDirectory()?s[l.name]=await o(p,a-1):s[l.name]=null})),s};return await o(t.input,e)},Bs=async t=>{const{input:e,...r}=t,o=await Is(t);return ne({structure:o,...r})},Nr=async t=>{const e=await L(t.input,t.patternOpts),r=t.max??1/0,o=t?.sort||"atoz";if(!e||e.length===0)throw new Error("No files found");const n=e.sort((a,i)=>{const s=a.localeCompare(i);return o==="atoz"?s:-s});return((a,i)=>{if(i<=0)return{};const s={};for(const c of a){const l=c.split("/");l.length>i&&(l.length=i),l.reduce((p,u,w)=>(p[u]||(p[u]=w===l.length-1?null:{}),p[u]),s)}return s})(n,r)},zs=async t=>{const{input:e,...r}=t,o=await Nr(t);return ne({structure:o,...r})},_s=t=>t,Ws=t=>t(lt),Or=t=>t instanceof At?lt.prettifyError(t):t instanceof Error?t.message:"Unexpected error",At=pn,lt=ft,ae=un,se=t=>{const e=ln(t);return new Function("z","return "+e)(ft)};class Gs{Error=At;schema=lt;formatError=Or;serialize=ae;deserialize=se;createLiteralUnion(e){return ft.union(e.map(r=>ft.literal(r)))}}const Hs=async t=>await ae(t.schema,t.opts),Vs=se,Zs=t=>JSON.parse(t),Mr=async t=>cn(t.schema,t.name,{...t?.opts}),Js=async t=>{const e="PKGSchema",r=(await Mr({name:e,schema:t.schema})).replace(new RegExp(`^[\\s\\S]*?${e}\\s`),"");return t.required&&r.replaceAll("?",""),t.noUnknownObject&&r.replaceAll(/^\s*\[k: string\]: unknown;\s*$/gm,"").replaceAll(/^\s*[\r\n]+/gm,""),r},ut={INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_DATA:"INVALID_DATA",UNEXPECTED:"UNEXPECTED"};class pt extends rr{}const qs=async(t,e)=>{const r=async()=>e.parse(t),[o,n]=await A(r());if(!o)return n;throw o instanceof At?new pt(ut.INVALID_DATA,{data:o}):new pt(ut.UNEXPECTED,{data:o.message})},Xs=async(t,e)=>{try{if(typeof t=="string"&&(t=await te(t)),e instanceof lt.ZodType)return await qs(t,e);if(typeof e=="string"&&(e=await te(e),typeof e!="object"))throw new pt(ut.INVALID_SCHEMA,{data:e});const r="2020-12",o=!0,n=new sn(e,r,o).validate(t);if(!n.valid)throw new pt(ut.INVALID_DATA,{data:n.errors});return t}catch(r){throw new pt(r?.message||ut.UNEXPECTED)}},Ys=Ue(hn),Ur=/^[/]([^/]+)[/]([^/]+)[/]tree[/]([^/]+)[/](.*)/,Ir=async(t,e,r)=>{const o=await fetch(`https://api.github.com/repos/${t}`,e?{headers:{Authorization:`Bearer ${e}`}}:{});if(o.status===401)throw r||console.log("\u26A0 The token provided is invalid or has been revoked.",{token:e}),new Error("Invalid token");if(o.status===403){if(o.headers.get("X-RateLimit-Remaining")==="0")throw r||console.log("\u26A0 Your token rate limit has been exceeded.",{token:e}),new Error("Rate limit exceeded")}else if(o.status===404)throw r||console.log("\u26A0 Repository was not found.",{repo:t}),new Error("Repository not found");if(!o.ok)throw r||console.log("\u26A0 Could not obtain repository data from the GitHub API.",{repo:t,response:o}),new Error("Fetch error");return o.json()},Ks=async({user:t,repository:e,ref:r="HEAD",directory:o,token:n,muteLog:a})=>{o.endsWith("/")||(o+="/");const i=[],s=await Ir(`${t}/${e}/git/trees/${r}?recursive=1`,n,a);if(s.message)throw new Error(s.message);for(const c of s.tree)c.type==="blob"&&c.path.startsWith(o)&&i.push(c);return i},Br=async(t,e,r,o,n)=>{const a=(await Ir(`${t}/${e}`,n?.token,n?.muteLog)).private;return{files:await Ks({user:t,repository:e,ref:r,directory:decodeURIComponent(o),token:n?.token,muteLog:n?.muteLog}),repoIsPrivate:a}},Qs=(t,e)=>{try{const[,r,o,n,a]=Ur.exec(new URL(t).pathname)??[];return[r,o,n,a]}catch{}return[]},ti=async(t,e,r)=>{let o,n;const a={files:{},downloaded:0,success:!1},[i,s,c,l]=Qs(t);if(!i||!s)return r?.muteLog||console.error("Invalid url. It must match: ",Ur),a.error="Invalid url",a;e||(e=S(process.cwd(),l)),Ve(e)||(e=S(process.cwd(),e));try{o=await Br(i,s,c,l,r)}catch(f){r?.muteLog||console.error("Failed to fetch repo meta info: ",f),await new Promise(h=>setTimeout(h,3e3));try{o=await Br(i,s,c,l,r)}catch(h){return r?.muteLog||console.error("Failed to fetch repo meta info after second attempt: ",h),a.error=h,a}}const{files:p}=o;if(p.length===0)return r?.muteLog||console.log("No files to download"),a.success=!0,a;r?.muteLog||console.log(`Downloading ${p.length} files\u2026`);const u=async f=>{const h=await fetch(`https://raw.githubusercontent.com/${i}/${s}/${c}/${f.path}`,r?.token?{headers:{Authorization:`Bearer ${r?.token}`}}:void 0);if(!h.ok)throw new Error(`HTTP ${h.statusText} for ${f.path}`);return h};n=0;const w=async f=>{let h;try{h=await u(f)}catch(x){r?.muteLog||console.log("\u26A0 Failed to download file: "+f.path,x),await new Promise(C=>setTimeout(C,2e3));try{h=await u(f)}catch(C){r?.muteLog||console.log("\u26A0 Failed to download file after second attempt: "+f.path,C);return}}try{n++;const x=S(e,f.path.replace(l+"/",""));await U(j(x)),await Ys(h.body,To(x)),a.files[f.path]=x}catch(x){r?.muteLog||console.error("Failed to write file: "+f.path,x)}},E=r?.requests??10,$=[];for(let f=0;f<p.length;f++){const h=f%E;$[h]&&await $[h],$[h]=w(p[f])}return await Promise.all($),r?.muteLog||console.log(`Downloaded ${n}/${p.length} files`),a.downloaded=n,p.length===n&&(a.success=!0),a},ei=async t=>{await ti(t.input,t.output,{token:t.token})},zr=()=>{try{return Zo("gh auth status",{encoding:"utf-8"}).includes("Logged in to github.com")}catch{return!1}},ri=async({user:t,repo:e,outputPath:r,filename:o,newFilename:n,version:a=""})=>{const i=Ue(Pe),s=T(r,o),c=T(r,n||o),l=`gh release download ${a||""} --repo ${t}/${e} --pattern ${o} --dir ${r}`;try{if(!zr())throw new Error('You need to authenticate in GitHub via CLI with "gh auth login"');const{stderr:p}=await i(l);if(p){console.error(`stderr: ${p}`);return}console.log(`File downloaded successfully to ${s}`),n&&(await we(s,c),console.log(`File renamed successfully to ${c}`))}catch(p){console.error(`Error: ${p.message}`)}},ie=new Mt({marked:async()=>(await import("marked")).Marked}),_r="^*||*^",ce="*|*|*|*",oi=new RegExp(Kr(ce),"g"),Wr="*#COLON|*",ni=new RegExp(Kr(Wr),"g"),ai=[" "],si=Er(),Ft="\r",ii=new RegExp(Ft),ci=new RegExp(Ft+"|<br />"),Gr={code:m.yellow,blockquote:m.gray.italic,html:m.gray,heading:m.green.bold,firstHeading:m.magenta.underline.bold,hr:m.reset,listitem:m.reset,list:yi,table:m.reset,paragraph:m.reset,strong:m.bold,em:m.italic,codespan:m.yellow,del:m.dim.gray.strikethrough,link:m.blue,href:m.blue.underline,text:q,unescape:!0,emoji:!0,width:80,showSectionPrefix:!0,reflowText:!1,tab:4,tableOptions:{}};function b(t,e){this.o=Object.assign({},Gr,t),this.tab=Pi(this.o.tab,Gr.tab),this.tableSettings=this.o.tableOptions,this.emoji=this.o.emoji?Ei:q,this.unescape=this.o.unescape?ki:q,this.highlightOptions=e||{},this.transform=he(xi,this.unescape,this.emoji)}function le(t){return t.replace(si,"").length}b.prototype.textLength=le;function ue(t,e){return e?t.replace(Ft,/\n/g):t}b.prototype.space=function(){return""},b.prototype.text=function(t){return typeof t=="object"&&(t=t.text),this.o.text(t)},b.prototype.code=function(t,e,r){return typeof t=="object"&&(e=t.lang,t.escaped,t=t.text),_(Vr(this.tab,$i(t,e,this.o,this.highlightOptions)))},b.prototype.blockquote=function(t){return typeof t=="object"&&(t=this.parser.parse(t.tokens)),_(this.o.blockquote(Vr(this.tab,t.trim())))},b.prototype.html=function(t){return typeof t=="object"&&(t=t.text),this.o.html(t)},b.prototype.heading=function(t,e){return typeof t=="object"&&(e=t.depth,t=this.parser.parseInline(t.tokens)),t=this.transform(t),t=(this.o.showSectionPrefix?new Array(e+1).join("#")+" ":"")+t,this.o.reflowText&&(t=Hr(t,this.o.width,this.options.gfm)),_(e===1?this.o.firstHeading(t):this.o.heading(t))},b.prototype.hr=function(){return _(this.o.hr(bi("-",this.o.reflowText&&this.o.width)))},b.prototype.list=function(t,e){if(typeof t=="object"){const r=t;r.start,r.loose,e=r.ordered,t="";for(let o=0;o<r.items.length;o++)t+=this.listitem(r.items[o])}return t=this.o.list(t,e,this.tab),_(mi(ui(this.tab,t),this.tab))},b.prototype.listitem=function(t){if(typeof t=="object"){const r=t;if(t="",r.task){const o=this.checkbox({checked:!!r.checked});r.loose?r.tokens.length>0&&r.tokens[0].type==="paragraph"?(r.tokens[0].text=o+" "+r.tokens[0].text,r.tokens[0].tokens&&r.tokens[0].tokens.length>0&&r.tokens[0].tokens[0].type==="text"&&(r.tokens[0].tokens[0].text=o+" "+r.tokens[0].tokens[0].text)):r.tokens.unshift({type:"text",raw:o+" ",text:o+" "}):t+=o+" "}t+=this.parser.parse(r.tokens,!!r.loose)}const e=he(this.o.listitem,this.transform);return t.indexOf(` `)!==-1&&(t=t.trim()),` `+pe+e(t)},b.prototype.checkbox=function(t){return typeof t=="object"&&(t=t.checked),"["+(t?"X":" ")+"] "},b.prototype.paragraph=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t=he(this.o.paragraph,this.transform)(t),this.o.reflowText&&(t=Hr(t,this.o.width,this.options.gfm)),_(t)},b.prototype.table=function(t,e){if(typeof t=="object"){const o=t;t="";let n="";for(let a=0;a<o.header.length;a++)n+=this.tablecell(o.header[a]);t+=this.tablerow({text:n}),e="";for(let a=0;a<o.rows.length;a++){const i=o.rows[a];n="";for(let s=0;s<i.length;s++)n+=this.tablecell(i[s]);e+=this.tablerow({text:n})}}var r=new de(Object.assign({},{head:Yr(t)[0]},this.tableSettings));return Yr(e,this.transform).forEach(o=>{r.push(o)}),_(this.o.table(r.toString()))},b.prototype.tablerow=function(t){return typeof t=="object"&&(t=t.text),ce+t+ce+` `},b.prototype.tablecell=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t+_r},b.prototype.strong=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),this.o.strong(t)},b.prototype.em=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t=ue(t,this.o.reflowText),this.o.em(t)},b.prototype.codespan=function(t){return typeof t=="object"&&(t=t.text),t=ue(t,this.o.reflowText),this.o.codespan(t.replace(/:/g,Wr))},b.prototype.br=function(){return this.o.reflowText?Ft:` `},b.prototype.del=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),this.o.del(t)},b.prototype.link=function(t,e,r){if(typeof t=="object"&&(t.title,r=this.parser.parseInline(t.tokens),t=t.href),this.options.sanitize){try{var o=decodeURIComponent(unescape(t)).replace(/[^\w:]/g,"").toLowerCase()}catch{return""}if(o.indexOf("javascript:")===0)return""}let n=r&&r!==t,a="";if(Ho.stdout){let i="";r?i=this.o.href(this.emoji(r)):i=this.o.href(t),a=$r(i,t.replace(/\+/g,"%20"))}else n&&(a+=this.emoji(r)+" ("),a+=this.o.href(t),n&&(a+=")");return this.o.link(a)},b.prototype.image=function(t,e,r){if(typeof t=="object"&&(e=t.title,r=t.text,t=t.href),typeof this.o.image=="function")return this.o.image(t,e,r);let o="!["+r;return e&&(o+=" - "+e),o+"]("+t+`) `};function li(t,e){const r=new b(t,e);return["text","code","blockquote","html","heading","hr","list","listitem","checkbox","paragraph","table","tablerow","tablecell","strong","em","codespan","br","del","link","image"].reduce((o,n)=>(o.renderer[n]=function(...a){return r.options=this.options,r.parser=this.parser,r[n](...a)},o),{renderer:{},useNewRenderer:!0})}function Hr(t,e,r){const o=r?ci:ii,n=t.split(o),a=[];return n.forEach(i=>{let s=i.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g),c=0,l="",p=!1;for(;s.length;){const w=s[0];if(w===""){s.splice(0,1),p=!1;continue}if(!le(w)){l+=w,s.splice(0,1),p=!0;continue}const E=w.split(/[ \t\n]+/);for(let $=0;$<E.length;$++){let f=E[$],h=c!=0;if(p&&(h=!1),c+f.length+h>e)if(f.length<=e)a.push(l),l=f,c=f.length;else{var u=f.substr(0,e-c-h);for(h&&(l+=" "),l+=u,a.push(l),l="",c=0,f=f.substr(u.length);f.length;){var u=f.substr(0,e);if(!u.length)break;if(u.length<e){l=u,c=u.length;break}else a.push(u),f=f.substr(e)}}else h&&(l+=" ",c++),l+=f,c+=f.length;p=!1}s.splice(0,1)}le(l)&&a.push(l)}),a.join(` `)}function ui(t,e){return e.replace(/(^|\n)(.+)/g,"$1"+t+"$2")}function Vr(t,e){return e&&t+e.split(` `).join(` `+t)}const pi="\\*",hi="\\d+\\.",Zr="(?:"+[pi,hi].join("|")+")";function mi(t,e){const r=new RegExp("(\\S(?: | )?)((?:"+e+")+)("+Zr+"(?:.*)+)$","gm");return t.replace(r,`$1 `+e+"$2$3")}const Jr=(t,e)=>t.match("^(?:"+e+")*"+Zr);function qr(t){return" ".repeat(t.length)}var pe="* ";function fi(t,e){return Jr(e,t)?e:qr(pe)+e}function gi(t,e){const r=fi.bind(null,e);return t.split(` `).filter(q).map(r).join(` `)}const Xr=t=>t+". ";function di(t,e,r){return Jr(e,t)?{num:r+1,line:e.replace(pe,Xr(r+1))}:{num:r,line:qr(Xr(r))+e}}function wi(t,e){const r=di.bind(null,e);let o=0;return t.split(` `).filter(q).map(n=>{const a=r(n,o);return o=a.num,a.line}).join(` `)}function yi(t,e,r){return t=t.trim(),t=e?wi(t,r):gi(t,r),t}function _(t){return t+` `}function $i(t,e,r,o){if(m.level===0)return t;const n=r.code;t=ue(t,r.reflowText);try{return Ie(t,Object.assign({},{language:e},o))}catch{return n(t)}}function Ei(t){return t.replace(/:([A-Za-z0-9_\-\+]+?):/g,e=>{const r=Te.get(e);return r?r+" ":e})}function bi(t,e){return e=e||process.stdout.columns,new Array(e).join(t)}function xi(t){return t.replace(ni,":")}function Yr(t,e){if(!t)return[];e=e||q;const r=e(t).split(` `),o=[];return r.forEach(n=>{if(!n)return;const a=n.replace(oi,"").split(_r);o.push(a.splice(0,a.length-1))}),o}function Kr(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function ki(t){return t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function q(t){return t}function he(){const t=arguments;return function(){let e=arguments;for(let r=t.length;r-- >0;)e=[t[r].apply(this,e)];return e[0]}}function vi(t){return ai.some(e=>t.match("^("+e+")+$"))}function Pi(t,e){return typeof t=="number"?new Array(t+1).join(" "):typeof t=="string"&&vi(t)?t:new Array(e+1).join(" ")}const Qr=({name:t,URL:e,imgURL:r})=>r?`[![${t}](${r})](${e})`:`[${t}](${e})`,Ai=t=>{let e="";for(let r=0;r<t.length;r++)e+=Qr(t[r]),r!==t.length-1&&(e+=` `);return e},Fi=t=>{const{path:e,style:r="flat",host:o="https://img.shields.io",...n}=t;if(!e)throw new Error('The "path" parameter is required to create a badge URL.');const a=bt(o,e),i=new URLSearchParams({style:r});for(const[s,c]of Object.entries(n))c&&i.append(s,c.toString());return`${a}?${i.toString()}`},W=async t=>{const e=B(t);return e==="path"?await I(t,"utf-8"):e==="url"?await Z(t):t},Ti=async t=>await W(t),ji=async t=>await W(t),Ci=async t=>{t=await W(t);const e=await ie.get("marked");return await new e({gfm:!1}).parse(t)},to=async(t,e)=>{t=await W(t);const r=await ie.get("marked"),o=new r;return o.use(li(e?.renderer,e?.highlight)),await o.parse(t)},eo=async t=>(t=await W(t),mn.toMarkdown(t)),Si=async t=>{t=await W(t);const e=await eo(t);return await to(e)},Li=t=>{const e=t.split(` `);let r=!1;return e.map(o=>{if(o.startsWith("```"))return r=!r,o;if(r)return o;if(/^(#{1,6})\s/.test(o)){const n=o.match(/^(#{1,6})\s/);if(n){const a=n[1];if(a.length<6){const i="#".repeat(a.length+1);return o.replace(a,i)}}}return o}).join(` `)},ro=async t=>{t=await W(t);const e=await ie.get("marked"),r=new e().lexer(t),o=[];for(const n of r)if(n.type==="heading"){const a=n.depth,i=n.text,s=i.toLowerCase().replace(/\s+/g,"-").replace(/[^\w-]+/g,"");o.push({level:a,title:i,anchor:s})}return o},Di=async t=>{let e,r;const{title:o,input:n,removeH1:a,maxHeadingLevel:i}=t;r=o?`## ${o} `:"";const s=await ro(n),c=a?s.filter(u=>u.level!==1):s,l=i??6,p=c.filter(u=>u.level<=l);return e=1,p.length&&p[0].level>1&&(e=p[0].level),p.forEach((u,w)=>{const E=w>0&&u.level>e?" ".repeat(u.level-e):"";r+=`${E}- [${u.title}](#${u.anchor}) `}),r},N={BUN:"bun",NPM:"npm",PNPM:"pnpm",YARN:"yarn"},G={NODE:"node",BUN:"bun",DENO:"deno"},X=(t,e)=>{try{const r=o=>o.replace(/^git\+/,"").replace(/\.git$/,"");return typeof t?.repository=="object"&&"url"in t.repository&&t.repository.url?bt(r(t.repository.url),e?.dir===!1?"":t.repository.directory||""):typeof t?.repository=="string"&&t.repository?r(t.repository):void 0}catch{throw new Error("Unexpected error getting repository URL")}},Ri=async(t,e)=>{const r=await Y(t);return X(r,e)},Ni=async(t,e)=>{const r=await K(t,e?.pkg);return X(r,e)},Oi=async(t,e)=>{const r=await Q(t);return X(r,e)},Mi=async(t,e)=>{const r=await ht(t,e?.pkg);return X(r,e)},Y=async(t,e)=>{const r=e?.registry||"https://registry.npmjs.org",o=await Qt(bt(r,t.toLowerCase()));return o.versions[e?.version?e.version:o["dist-tags"].latest]},K=async(t,e)=>{typeof t=="string"&&(t=new URL(t));const r=t.pathname.split("/").filter(Boolean),o=(r[0]==="package"&&r[1]?r.slice(1):r).join("/");return await Y(o,e)},me=t=>g(j(t),"package.json"),Q=async t=>await kt(me(t)),ht=async(t,e)=>{if(typeof t=="object")return t;if(typeof t!="string")return await K(t,e?.remote);const r=B(t);return r==="url"?await K(t,e?.remote):r==="path"?await Q(t):await Y(t,e?.remote)},oo=async t=>{const e=await Q(t);return{id:e.name||M(t),packagePath:me(t),dir:j(t),repoUrl:X(e),content:e}},no=async(t="./")=>{let e=S(t);for