@dovenv/utils
Version:
Utilities for dovenv
42 lines (39 loc) • 58.7 kB
JavaScript
import{hexToRgb as co,hslToRgb as lo,xyzToCIELab as uo,rgbToXyz as po,rgbToHsl as mo,rgbToCIELab as ho,rgbToHex as fo}from"@vibrant/color";import go from"chalk";import wo from"chroma-js";import{highlight as yo}from"cli-highlight";import $o from"gradient-string";import bo from"figures";import ge from"terminal-link";import de from"cli-table3";export{default as Table}from"cli-table3";import Eo from"columnify";import{boxen as xo}from"@visulima/boxen";import g,{argv as tt}from"node:process";export{default as process}from"node:process";import ko from"terminal-size";export{default as terminalSize}from"terminal-size";import{globby as vo,globbyStream as Po}from"globby";import{createWriteStream as Ao}from"node:fs";export{createWriteStream}from"node:fs";import{readFile as Fo,rename as we,writeFile as ye,copyFile as To,mkdir as $e,access as jt,lstat as jo,symlink as Ct,constants as Co,stat as St,readdir as So,rm as Lo,unlink as be}from"node:fs/promises";import Ee,{homedir as Do,arch as No,platform as Ro,tmpdir as Oo}from"node:os";import{resolve as xe,basename as pt,dirname as Mo,extname as Uo,isAbsolute as Lt,normalize as Io,relative as zo,join as F}from"node:path";import{fileURLToPath as _o,pathToFileURL as ke}from"node:url";export{fileURLToPath}from"node:url";import{LocalStorage as Bo}from"node-localstorage";import*as ve from"open";import Wo from"supports-hyperlinks";export{default as supportsHyperlinks}from"supports-hyperlinks";import{createRequire as Go}from"module";import{exec as Pe,spawn as Dt,fork as Ae,execSync as Ho}from"node:child_process";import{npmRunPathEnv as Fe}from"npm-run-path";import{resolve as Vo}from"path";import{matcher as Zo}from"matcher";import*as Te from"node-emoji";export{Te as emoji};import Jo 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 qo from"@structium/svg";export{qo as svg};import*as Le from"@structium/toml";export{Le as toml};import*as De from"@structium/xml";export{De as xml};import*as Ne from"@structium/yaml";export{Ne as yaml};import{zip as Nt,tar as Rt,tgz as Ot,gzip as Re}from"compressing";export{gzip,tar,tgz,zip}from"compressing";import Xo from"yargs";import{hideBin as Yo}from"yargs/helpers";import Oe from"log-update";import*as R from"@clack/prompts";import{text as Ko}from"@clack/prompts";import Qo from"enquirer";import{consola as tn}from"consola";import en from"ora";import{performance as Me}from"node:perf_hooks";import rn from"pretty-ms";import{Tree as on}from"@ascii-kit/tree";import{Validator as nn}from"@cfworker/json-schema";import{compile as an}from"json-schema-to-typescript-lite";import{jsonSchemaToZod as sn}from"json-schema-to-zod";import{ZodError as cn,toJSONSchema as ln,z as mt}from"zod/v4";import{promisify as Ue}from"node:util";import{pipeline as un}from"node:stream";import{html as pn}from"@structium/html-markdown";export{html,markdown}from"@structium/html-markdown";export{qrcode}from"@ascii-kit/qr";import{PNG as mn}from"pngjs";import hn from"quantize";const fn=wo,gn={rgb2hex:fo,rgb2CIELab:ho,rgb2sl:mo,rgb2xyz:po,xyz2CIELab:uo,hslToRgb:lo,hex2rgb:co},Ie=(t,e)=>yo(t,e),b=go,dn=(t,e,r)=>$o(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 wn=new Mt({font:async()=>(await import("@ascii-kit/font")).Font}),yn=bo,ze=async(t,e,r)=>{const o=await wn.get("font");return await new o(e).text(t,{horizontalLayout:"default",verticalLayout:"default",whitespaceBreak:!0,...r||{}})},$n=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()},Be=(t,e)=>Eo(t,e),ht=(t,e)=>xo(t,e),ft=typeof window<"u"&&typeof window.document<"u",En=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,xn=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",kn=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")),vn=typeof Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno<"u",Pn=typeof process<"u"&&process.versions!=null&&process.versions.bun!=null,We=t=>{const e=t.process||g,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])}}},An=t=>We({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}}),Ge=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])}}},Fn=t=>Ge({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}}),Tn=()=>g.env.NODE_ENV!=="production",jn=()=>{g.noDeprecation=!0},Cn=()=>({show:()=>{g.noDeprecation=!1},hide:()=>{g.noDeprecation=!0}}),Sn=t=>{g.on("exit",t)},Ln=t=>{g.on("SIGINT",t)},Dn=()=>{g.exit(130)},et=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}=ko(),l=e(c,s);return ht("",{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+=et({lineChar:o,...l}),e+=`
`,e+=et({title:r,lineChar:" ",...l})):a.startsWith("top")?(e+=et({title:r,lineChar:" ",...l}),e+=`
`,e+=et({lineChar:o,...l})):e+=et({lineChar:o,title:r,...l}),e},C=xe,Rn=zo,rt=Uo,T=Mo,O=pt,He=Lt,On=Io,Mn=we,Ve=ye,S=vo,Un=Po,In=(t,e)=>{const r=C(t),o=C(e);return r===o},zn=t=>ke(C(t)).href,Ze=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 F(t)!==""}catch{return!1}}return!1},M=async t=>{await dt(t)||await Qe(t)},gt=async t=>(t=v(t),await So(t,{withFileTypes:!0}));async function _n({path:t,extensions:e=[]}){return(await gt(t)).filter(r=>{const o=rt(r.name);return e.includes(o)}).map(r=>O(r.name,rt(r.name)))}const Bn=(t=import.meta.url)=>T(_o(t));function f(...t){try{return F(...t)}catch(e){throw new Error(`Failed to join path (${t.join(", ")}):
- `+(e instanceof Error?e.message:e?.toString()),{cause:e})}}const Je=xe;function v(t){let e=t;return t.startsWith("~/")&&(e=t.replace(/^~(?=$|\/|\\)/,Do())),Je(e)}const U=Fo,Wn=async(t,e)=>{const r=await S(t,{dot:!0,...e?.inputOpts,onlyFiles:!0});return await Promise.all(r.map(async o=>{try{const n=await U(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()}`,{cause:n})}}))};async function qe(t){try{t=v(t),await Lo(t,{recursive:!0,force:!0})}catch(e){throw new Error(`Error removing ${t}: ${error.message}`,{cause:e})}}async function Xe(t){t=v(t),await dt(t)&&await qe(t)}async function Gn(t){t=v(t),await Ut(t)?await Xe(t):await Ye(t)}async function Ye(t){t=v(t),await L(t)&&await be(t)}async function Ke(t){await be(t)}async function Ut(t){return t=v(t),(await St(t)).isDirectory()}async function Qe(t){try{t=v(t),await $e(t,{recursive:!0})}catch(e){throw Error(`Error creating the directory: ${e}`,{cause:e})}}async function dt(t){try{return t=v(t),await jt(t,Co.F_OK),(await St(t)).isDirectory()}catch{return!1}}async function L(t){try{return t=v(t),await jt(t),(await St(t)).isFile()}catch{return!1}}async function Hn(t,e){t=v(t),await ye(t,e)}async function ot(t){return await L(t)?!0:await dt(t)}const tr=async({input:t,output:e})=>{try{await To(t,e)}catch(r){console.error(r)}},Vn=async({input:t,output:e})=>{try{const r=async({input:o,output:n})=>{const a=await gt(o);await M(n);for(const i of a){const s=F(o,i.name),c=F(n,i.name);i.isDirectory()?await r({input:s,output:c}):await tr({input:s,output:c})}};await r({input:t,output:e})}catch(r){console.error(`\u{1F4C1} Error copying directory: ${r.message}`)}},Zn=async({input:t,output:e})=>{try{await jt(e)}catch(n){if(n.code==="ENOENT")await $e(e,{recursive:!0});else throw`\u274C\u{1F517} ${n}`}const r=await jo(t),o=process.platform==="win32";r.isDirectory()?o?await Ct(t,F(e,pt(t)),"junction"):await Ct(t,F(e,pt(t)),"dir"):r.isFile()&&await Ct(t,F(e,pt(t))),console.log(`\u{1F517} symlink: "${t}" to "${e}".`)};function Jn(t){return new Bo(t)}const qn=ve.default,Xn=ve.openApp,P=async t=>t.then(e=>[void 0,e]).catch(e=>[e]);class er extends Error{data;constructor(e,r){super(e),this.data=r,Error.captureStackTrace(this,this.constructor)}}const Yn=t=>{try{return Go(Vo(g.cwd(),"./")).resolve(t)}catch{}try{const e=import.meta.resolve(t);return new URL(e).pathname}catch{return}};class rr extends Error{}const Kn=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=f(n,t);if(await ot(a))return a}},Qn=async({name:t,args:e,opts:r})=>new Promise((o,n)=>{const a=Fe(r),i=Dt(t,e||[],{env:a,cwd:r?.cwd||g.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 rr(`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)})}),ta=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)}})})},or=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)})}),ea=async t=>{const{name:e,on:r,onError:o,onExit:n,onSuccess:a}=t,i=g.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(`
${ht(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)}},ra=t=>P(new Promise((e,r)=>{Pe(t,(o,n,a)=>{if(o){r({error:o,stdout:n,stderr:a});return}e(n)})})),oa=async({module:t,args:e=[]})=>{const r=await _t(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()))})},na=async({module:t,args:e=[]})=>{const r=await _t(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)})})},nr=async t=>{const e=g.platform==="win32"?`where ${t}`:`which ${t}`;try{return await or(e),!0}catch{return!1}},aa=async t=>{const e={},r=t.map(async o=>{const n=await nr(o);e[o]=n});return await Promise.all(r),e},sa=(t,e)=>{const r=ar(t);if(r&&Object.values(e).includes(r))return r},ar=t=>{const e=t.length===1?"-":"--",r=tt;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]}},ia=t=>{const e=tt,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},ca=t=>{const e=t.length===1?"-":"--";return tt.includes(`${e}${t}`)},la=t=>tt.includes(t),ua=()=>tt.length>2,pa=Yo,ma=async({args:t=process.argv,fn:e})=>{const r=Xo(t);return await e(r),r.help(),r.parse(),r},ha=({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())}}},fa=async t=>{const e=await Ko({...t,validate:r=>{if(!r||r.trim()==="")return t.errorText||"The value must exist and must be a number";const o=!isNaN(Number(r)),n=t.errorText||"Value must be a number";if(!o||/\s/.test(r)||/\s/.test(r))return n;if(t.validate)return t.validate(r)}});return typeof e=="string"?Number(e):e},ga=()=>g.platform!=="win32"?g.env.TERM!=="linux":!!g.env.WT_SESSION||!!g.env.TERMINUS_SUBLIME||g.env.ConEmuTask==="{cmd::Cmder}"||g.env.TERM_PROGRAM==="Terminus-Sublime"||g.env.TERM_PROGRAM==="vscode"||g.env.TERM==="xterm-256color"||g.env.TERM==="alacritty"||g.env.TERMINAL_EMULATOR==="JetBrains-JediTerm",da=ga(),wt=(t,e)=>da?t:e,yt={STEP_ACTIVE:wt("\u25C6","*"),STEP_CANCEL:wt("\u25A0","x"),STEP_ERROR:wt("\u25B2","x"),STEP_SUBMIT:wt("\u25C7","o")},wa=t=>{if(t==="initial"||t==="active")return b.cyan(yt.STEP_ACTIVE);if(t==="cancel")return b.red(yt.STEP_CANCEL);if(t==="error")return b.yellow(yt.STEP_ERROR);if(t==="submit")return b.green(yt.STEP_SUBMIT)},It={message:"message"};async function sr(t){return Qo.prompt(t)}const ir=async(t,e)=>{R.log.message();const r="id",o=await sr({...t,name:r,prefix:n=>{let a="active";return n.cancelled&&(a="cancel"),n.submitted&&(a="submit"),n.error!==""&&(a="error"),wa(a)},onCancel:async()=>{R.log.message(),e&&await e()}});return R.log.message(),r in o?o[r]:void 0},ya={table:({value:t,opts:e,type:r=It.message})=>R.log[r](_e(t,e)),columns:({value:t,opts:e,type:r=It.message})=>R.log[r](Be(t,e)),box:({value:t,opts:e,type:r=It.message})=>R.log[r](ht(t,e))},$t={...R,number:fa},zt={...$t,log:{...$t.log,errorWithExit:t=>{$t.log.error(t),console.log(),g.exit(1)}},...ya},$a=ir;async function ba(t){t.onCancel||(t.onCancel=async n=>{n.cancel("canceled \u{1F494}"),g.exit(0)});const e={...zt,typePrompt:n=>ir(n,()=>t.onCancel?.(zt))};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 Ea=tn,xa=en,ka=()=>{const t=Me.now(),e=()=>Me.now()-t;return{stop:()=>e()/1e3,prettyStop:()=>rn(e())}},va=async t=>new Promise(e=>setTimeout(e,t)),cr=()=>{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=cr();return`${t.year}-${t.month}-${t.day}T${t.hours}:${t.minutes}:${t.seconds}Z`},_t=async({from:t=g.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 [${f(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=>f(l,a)).find(async l=>await ot(l));if(!c)throw new o(i+"Failed in lookupPaths");if(r&&(c=f(c,...r)),!await ot(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 ${f(e,...r||[])}.`+a,{cause:n})}},Aa=async t=>{const{content:e,params:r,transform:o,opts:n}=t,{prefix:a,suffix:i}=n?.mark||{prefix:"{{",suffix:"}}"},s=$=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`${s(a)}\\s*([^}]+?)\\s*${s(i)}`,"g"),l=($,y)=>{const h=y.split(".");let m=$;for(const x of h){if(m===void 0)return;if(x.includes("[")&&x.includes("]")){const[j,so]=x.split("["),io=parseInt(so.replace("]",""),10);m=m[j]?.[io]}else m=m[x]}return m},p=async($,y)=>{if(o){const m=await o(y);if(m!==y)return m}const h=l(r,y);if(h===void 0){if(n?.throw)throw new Error(`Placeholder ${y} not found`);return $}return String(h)};let u=e;const d=[...e.matchAll(c)];for(const $ of d){const[y,h]=$,m=await p(y,h);u=u.replace(y,m)}return u},bt=t=>{const e=t.length,r=t.split(/\s+/).filter(Boolean).length;return{chars:e,words:r}},lr=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase(),Bt=t=>t.charAt(0).toUpperCase()+t.slice(1),Fa=t=>t.replace(/([A-Z])/g,"_$1").toLowerCase(),ur=t=>t.replace(/-([a-z])/g,(e,r)=>r.toUpperCase()),Ta=t=>{const e=ur(t);return Bt(e)},ja=t=>t.replace(/-/g,"_"),pr=t=>t.charAt(0).toLowerCase()+t.slice(1),Ca=t=>{const e=pr(t);return lr(e)},Sa=t=>t.replace(/([A-Z])/g,"_$1").toLowerCase(),mr=t=>t.replace(/_([a-z])/g,(e,r)=>r.toUpperCase()),La=t=>t.replace(/_/g,"-"),Da=t=>{const e=mr(t);return Bt(e)},w="\x1B[",nt="\x1B]",G="\x07",at=";",hr=!ft&&g.env.TERM_PROGRAM==="Apple_Terminal",Na=!ft&&g.platform==="win32",Ra=ft?()=>{throw new Error("`process.cwd()` only works in Node.js, not the browser.")}:g.cwd,Oa=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");return typeof e=="number"?`${w}${e+1}${at}${t+1}H`:`${w}${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+=w+Math.abs(t)+(t<0?"D":"C")),e!==0&&(r+=w+Math.abs(e)+(e<0?"A":"B")),r},fr=(t=1)=>`${w}${t}A`,Ua=(t=1)=>`${w}${t}B`,Ia=(t=1)=>`${w}${t}C`,za=(t=1)=>`${w}${t}D`,gr=`${w}G`,_a=hr?"\x1B7":`${w}s`,Ba=hr?"\x1B8":`${w}u`,Wa=`${w}6n`,Ga=`${w}E`,Ha=`${w}F`,Va=`${w}?25l`,Za=`${w}?25h`,Ja=t=>{let e="";for(let r=0;r<t;r++)e+=dr+(r<t-1?fr():"");return e+gr},qa=`${w}K`,Xa=`${w}1K`,dr=`${w}2K`,Ya=`${w}J`,Ka=`${w}1J`,Wt=`${w}2J`,Qa=`${w}S`,ts=`${w}T`,es="\x1Bc",rs=Na?`${Wt}${w}0f`:`${Wt}${w}3J${w}H`,os=`${w}?1049h`,ns=`${w}?1049l`,as=G,wr=(t,e)=>[nt,"8",at,at,e,G,t,nt,"8",at,at,G].join(""),ss=(t,e={})=>{let r=`${nt}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")+G},is={setCwd(t=Ra()){return`${nt}50;CurrentDir=${t}${G}`},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=`${nt}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+G}},cs={__proto__:null,beep:as,clearScreen:es,clearTerminal:rs,cursorBackward:za,cursorDown:Ua,cursorForward:Ia,cursorGetPosition:Wa,cursorHide:Va,cursorLeft:gr,cursorMove:Ma,cursorNextLine:Ga,cursorPrevLine:Ha,cursorRestorePosition:Ba,cursorSavePosition:_a,cursorShow:Za,cursorTo:Oa,cursorUp:fr,enterAlternativeScreen:os,eraseDown:Ya,eraseEndLine:qa,eraseLine:dr,eraseLines:Ja,eraseScreen:Wt,eraseStartLine:Xa,eraseUp:Ka,exitAlternativeScreen:ns,iTerm:is,image:ss,link:wr,scrollDown:ts,scrollUp:Qa},yr=({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=Jo(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 ms={__proto__:null,align:ls},$r=t=>{return e.withOptions=r=>$r({...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 d=u[1].length;c?c=Math.min(c,d):c=d}}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}},hs=$r({}),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=Zo,I=t=>$s(t)?"url":Ze(t)?"path":"text",$s=t=>{try{return new URL(t),!0}catch{return!1}},Et=(...t)=>(t=t.map(e=>e.replace(/^\/+|\/+$/g,"")),t.join("/")),bs=t=>JSON.stringify(t,null," ")+`
`,Gt=()=>crypto.randomUUID(),xt=async t=>(t=v(t),(await U(t)).toString("utf8"));async function H(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 Es=async t=>{const e=I(t);return e==="path"?await xt(t):e==="url"?await H(t):t},xs=async(t,e)=>{const r=[];for(let o=0;o<t.length;o++){const n=t[o],a=I(n);if(a==="path"){const i=await S(n,e?.path);await Promise.all(i.map(async s=>r.push({type:a,path:s,id:O(T(s)),content:await xt(s)})))}else a==="url"?r.push({type:a,path:n,id:`${a}-${new URL(n).hostname}-${o}`,content:await H(n)}):r.push({type:a,id:`${a}-${o}`,content:n})}return r},D=Ee.homedir(),Ht=Ee.tmpdir(),{env:V}=g,ks=t=>{const e=f(D,"Library");return{data:f(e,"Application Support",t),config:f(e,"Preferences",t),cache:f(e,"Caches",t),log:f(e,"Logs",t),temp:f(Ht,t)}},vs=t=>{const e=V.APPDATA||f(D,"AppData","Roaming"),r=V.LOCALAPPDATA||f(D,"AppData","Local");return{data:f(r,t,"Data"),config:f(e,t,"Config"),cache:f(r,t,"Cache"),log:f(r,t,"Log"),temp:f(Ht,t)}},Ps=t=>{const e=O(D);return{data:f(V.XDG_DATA_HOME||f(D,".local","share"),t),config:f(V.XDG_CONFIG_HOME||f(D,".config"),t),cache:f(V.XDG_CACHE_HOME||f(D,".cache"),t),log:f(V.XDG_STATE_HOME||f(D,".local","state"),t),temp:f(Ht,e,t)}},br=({name:t,suffix:e="nodejs"})=>{if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),g.platform==="darwin"?ks(t):g.platform==="win32"?vs(t):Ps(t)},z=xt,Er=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),xr=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),kr=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)}`)}},vr=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 st(e)}catch(e){throw new Error(`Error reading JSON file ${t}: ${e.message}`)}},st=async t=>JSON.parse(t),As={deserialize:st,serialize:t=>JSON.stringify(t),parser:st,stringify:t=>JSON.stringify(t)},Pr=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),Ar=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 Ne.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)},A={json:"json",yml:"yml",yaml:"yaml",toml:"toml",js:"js",mjs:"mjs",ini:"ini",xml:"xml",csv:"csv"},Kt=async t=>{try{if(!await L(t))throw Error("File does not exists");let e;if(t.endsWith("."+A.json))e=await kt(t);else if(t.endsWith("."+A.yml)||t.endsWith("."+A.yaml))e=await Xt(t);else if(t.endsWith("."+A.toml))e=await Pr(t);else if(t.endsWith("."+A.js)||t.endsWith("."+A.mjs))e=await kr(t);else if(t.endsWith("."+A.ini))e=await xr(t);else if(t.endsWith("."+A.csv))e=await Er(t);else if(t.endsWith("."+A.xml))e=await Ar(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(A);for(let o=0;o<r.length;o++){const n=r[o],a=f(t,e+"."+n);if(await L(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 P(st(t));if(!e&&r)return r;const[o,n]=await P(Yt(t));if(!o&&n)return n;const[a,i]=await P(Jt(t));if(!a&&i)return i;const[s,c]=await P(vr(t));if(!s&&c)return c;const[l,p]=await P(Zt(t));if(!l&&p)return p;const[u,d]=await P(qt(t));if(!u&&d)return d;const[$,y]=await P(Vt(t));if(!$&&y&&Array.isArray(y))return y;throw new Error("Cannot parse object from content")},Qt=async t=>{try{const e=await H(t);return vt(e)}catch(e){throw new Error(`Error getting [${t}] data. ${e.message}`)}},te=async t=>{try{const e=I(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||br({name:o,suffix:a}).config,s=f(i,"config.json"),c={[e]:r},l=je({mergeArrays:!1}),p=async()=>{try{return await kt(s)}catch{return c}},u=async()=>{const m=await L(s);return m||await M(i),m?await p():c};let d=await u();const $=async m=>{const x=await u(),j=l(x,{[e]:m});await Ve(s,JSON.stringify(j,null,2)),d=j},y=async m=>typeof m=="string"?!d[e]||typeof d[e][m]>"u"?void 0:d[e][m]:d[e],h=async()=>await $(r);if(!await L(s))await $(r);else{const m=l({[e]:r},d);await $(m[e])}return{defaultValues:r,get:y,set:$,reset:h,path:s}},Ss=()=>Oo(),Ls=async()=>{switch(Ro()){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}};function Ds(){switch(No()){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,Fr="auto",Pt=()=>process.cwd(),Ns=t=>t.toLowerCase().replace(".",""),re=t=>`Unsupported compression format: ${t}. Supported formats: ${Object.values(k).join(", ")}`,Rs=async t=>{const{input:e,output:r=Pt(),newName:o,remove:n=!1,format:a=Fr,opts:i}=t,s=rt(e),c=a!==Fr?a:Ns(s),l=o||O(e,s),p=f(r,l);if(c===k.ZIP)await Nt.uncompress(e,p,i?.zip||{strip:1});else if(c===k.TAR)await Rt.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 Re.uncompress(e,p,i?.gzip||{strip:1});else throw new Error(re(a));return n&&await Ke(e),p},Os=async t=>{const{input:e,output:r=Pt(),hook:o,format:n=ee,inputOpts:a={}}=t;await M(r);const i=await S(e,{onlyFiles:!0,dot:!0,...a});await Promise.all(i.map(async s=>{await o?.beforeFile?.(s),await oe({input:s,output:r,name:O(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=f(r,i);if(await M(r),n===k.ZIP)await Nt.compressFile(e,s,a?.zip);else if(n===k.TAR)await Rt.compressFile(e,s,a?.tar);else if(n===k.TGZ)await Ot.compressFile(e,s,a?.tgz);else if(n===k.GZ)await Re.compressFile(e,s,a?.gzip);else throw new Error(re(n));return s},Tr=async t=>{const{input:e,output:r=Pt(),name:o=Gt(),format:n=ee,opts:a}=t,i=`${o}.${n}`,s=f(r,i);if(await M(r),n===k.ZIP)await Nt.compressDir(e,s,a?.zip);else if(n===k.TAR)await Rt.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 Tr(t):await oe(t),jr=async({input:t,opts:e})=>{let r=0,o=0;const n=await S(t,{onlyFiles:!0,...e||{}});for(const a of n){const i=await U(a,"utf-8"),s=bt(i);r+=s.chars,o+=s.words}return{files:n.length,chars:r,words:o}},Cr=async({input:t,opts:e})=>{const{chars:r,words:o}=await jr({input:t,opts:e});return{chars:r,words:o}},Sr=async({input:t})=>{let e=0,r=0;for(const o of t){const n=await H(o),a=bt(n);e+=a.chars,r+=a.words}return{chars:e,words:r}},Lr=async({input:t})=>{let e=0,r=0;for(const o of t){const n=bt(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 Cr({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 Sr({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 Lr({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 on(t.structure,{hook:{onData:e=>(e.name=b[e.isFile?"green":"blue"](e.name),e.pattern={indent:b.gray.dim(e.pattern.indent),line:b.gray.dim(e.pattern.line),lastLine:b.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 gt(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=f(n,l.name);l.isDirectory()?s[l.name]=await o(p,a-1):s[l.name]=null})),s};return await o(t.input,e)},zs=async t=>{const{input:e,...r}=t,o=await Is(t);return ne({structure:o,...r})},Dr=async t=>{const e=await S(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,d)=>(p[u]||(p[u]=d===l.length-1?null:{}),p[u]),s)}return s})(n,r)},_s=async t=>{const{input:e,...r}=t,o=await Dr(t);return ne({structure:o,...r})},Bs=t=>t,Ws=t=>t(it),Nr=t=>t instanceof At?it.prettifyError(t):t instanceof Error?t.message:"Unexpected error",At=cn,it=mt,ae=ln,se=t=>{const e=sn(t);return new Function("z","return "+e)(mt)};class Gs{Error=At;schema=it;formatError=Nr;serialize=ae;deserialize=se;createLiteralUnion(e){return mt.union(e.map(r=>mt.literal(r)))}}const Hs=async t=>await ae(t.schema,t.opts),Vs=se,Zs=t=>JSON.parse(t),Rr=async t=>an(t.schema,t.name,{...t?.opts}),Js=async t=>{const e="PKGSchema",r=(await Rr({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},ct={INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_DATA:"INVALID_DATA",UNEXPECTED:"UNEXPECTED"};class lt extends er{}const qs=async(t,e)=>{const r=async()=>e.parse(t),[o,n]=await P(r());if(!o)return n;throw o instanceof At?new lt(ct.INVALID_DATA,{data:o}):new lt(ct.UNEXPECTED,{data:o.message})},Xs=async(t,e)=>{try{if(typeof t=="string"&&(t=await te(t)),e instanceof it.ZodType)return await qs(t,e);if(typeof e=="string"&&(e=await te(e),typeof e!="object"))throw new lt(ct.INVALID_SCHEMA,{data:e});const r="2020-12",o=!0,n=new nn(e,r,o).validate(t);if(!n.valid)throw new lt(ct.INVALID_DATA,{data:n.errors});return t}catch(r){throw new lt(r?.message||ct.UNEXPECTED)}},Ys=Ue(un),Or=/^[/]([^/]+)[/]([^/]+)[/]tree[/]([^/]+)[/](.*)/,Mr=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 Mr(`${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},Ur=async(t,e,r,o,n)=>{const a=(await Mr(`${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]=Or.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: ",Or),a.error="Invalid url",a;e||(e=C(process.cwd(),l)),He(e)||(e=C(process.cwd(),e));try{o=await Ur(i,s,c,l,r)}catch(h){r?.muteLog||console.error("Failed to fetch repo meta info: ",h),await new Promise(m=>setTimeout(m,3e3));try{o=await Ur(i,s,c,l,r)}catch(m){return r?.muteLog||console.error("Failed to fetch repo meta info after second attempt: ",m),a.error=m,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 h=>{const m=await fetch(`https://raw.githubusercontent.com/${i}/${s}/${c}/${h.path}`,r?.token?{headers:{Authorization:`Bearer ${r?.token}`}}:void 0);if(!m.ok)throw new Error(`HTTP ${m.statusText} for ${h.path}`);return m};n=0;const d=async h=>{let m;try{m=await u(h)}catch(x){r?.muteLog||console.log("\u26A0 Failed to download file: "+h.path,x),await new Promise(j=>setTimeout(j,2e3));try{m=await u(h)}catch(j){r?.muteLog||console.log("\u26A0 Failed to download file after second attempt: "+h.path,j);return}}try{n++;const x=C(e,h.path.replace(l+"/",""));await M(T(x)),await Ys(m.body,Ao(x)),a.files[h.path]=x}catch(x){r?.muteLog||console.error("Failed to write file: "+h.path,x)}},$=r?.requests??10,y=[];for(let h=0;h<p.length;h++){const m=h%$;y[m]&&await y[m],y[m]=d(p[h])}return await Promise.all(y),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})},Ir=()=>{try{return Ho("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=F(r,o),c=F(r,n||o),l=`gh release download ${a||""} --repo ${t}/${e} --pattern ${o} --dir ${r}`;try{if(!Ir())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}),zr="^*||*^",ce="*|*|*|*",oi=new RegExp(Xr(ce),"g"),_r="*#COLON|*",ni=new RegExp(Xr(_r),"g"),ai=[" "],si=yr(),Ft="\r",ii=new RegExp(Ft),ci=new RegExp(Ft+"|<br />"),Br={code:b.yellow,blockquote:b.gray.italic,html:b.gray,heading:b.green.bold,firstHeading:b.magenta.underline.bold,hr:b.reset,listitem:b.reset,list:yi,table:b.reset,paragraph:b.reset,strong:b.bold,em:b.italic,codespan:b.yellow,del:b.dim.gray.strikethrough,link:b.blue,href:b.blue.underline,text:Z,unescape:!0,emoji:!0,width:80,showSectionPrefix:!0,reflowText:!1,tab:4,tableOptions:{}};function E(t,e){this.o=Object.assign({},Br,t),this.tab=Pi(this.o.tab,Br.tab),this.tableSettings=this.o.tableOptions,this.emoji=this.o.emoji?bi:Z,this.unescape=this.o.unescape?ki:Z,this.highlightOptions=e||{},this.transform=me(xi,this.unescape,this.emoji)}function le(t){return t.replace(si,"").length}E.prototype.textLength=le;function ue(t,e){return e?t.replace(Ft,/\n/g):t}E.prototype.space=function(){return""},E.prototype.text=function(t){return typeof t=="object"&&(t=t.text),this.o.text(t)},E.prototype.code=function(t,e,r){return typeof t=="object"&&(e=t.lang,t.escaped,t=t.text),_(Gr(this.tab,$i(t,e,this.o,this.highlightOptions)))},E.prototype.blockquote=function(t){return typeof t=="object"&&(t=this.parser.parse(t.tokens)),_(this.o.blockquote(Gr(this.tab,t.trim())))},E.prototype.html=function(t){return typeof t=="object"&&(t=t.text),this.o.html(t)},E.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=Wr(t,this.o.width,this.options.gfm)),_(e===1?this.o.firstHeading(t):this.o.heading(t))},E.prototype.hr=function(){return _(this.o.hr(Ei("-",this.o.reflowText&&this.o.width)))},E.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),_(hi(ui(this.tab,t),this.tab))},E.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=me(this.o.listitem,this.transform);return t.indexOf(`
`)!==-1&&(t=t.trim()),`
`+pe+e(t)},E.prototype.checkbox=function(t){return typeof t=="object"&&(t=t.checked),"["+(t?"X":" ")+"] "},E.prototype.paragraph=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t=me(this.o.paragraph,this.transform)(t),this.o.reflowText&&(t=Wr(t,this.o.width,this.options.gfm)),_(t)},E.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:qr(t)[0]},this.tableSettings));return qr(e,this.transform).forEach(o=>{r.push(o)}),_(this.o.table(r.toString()))},E.prototype.tablerow=function(t){return typeof t=="object"&&(t=t.text),ce+t+ce+`
`},E.prototype.tablecell=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t+zr},E.prototype.strong=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),this.o.strong(t)},E.prototype.em=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),t=ue(t,this.o.reflowText),this.o.em(t)},E.prototype.codespan=function(t){return typeof t=="object"&&(t=t.text),t=ue(t,this.o.reflowText),this.o.codespan(t.replace(/:/g,_r))},E.prototype.br=function(){return this.o.reflowText?Ft:`
`},E.prototype.del=function(t){return typeof t=="object"&&(t=this.parser.parseInline(t.tokens)),this.o.del(t)},E.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(Wo.stdout){const i=r?this.o.href(this.emoji(r)):this.o.href(t);a=wr(i,t.replace(/\+/g,"%20"))}else n&&(a+=this.emoji(r)+" ("),a+=this.o.href(t),n&&(a+=")");return this.o.link(a)},E.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="
`};function li(t,e){const r=new E(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 Wr(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 d=s[0];if(d===""){s.splice(0,1),p=!1;continue}if(!le(d)){l+=d,s.splice(0,1),p=!0;continue}const $=d.split(/[ \t\n]+/);for(let y=0;y<$.length;y++){let h=$[y],m=c!=0;if(p&&(m=!1),c+h.length+m>e)if(h.length<=e)a.push(l),l=h,c=h.length;else{var u=h.substr(0,e-c-m);for(m&&(l+=" "),l+=u,a.push(l),l="",c=0,h=h.substr(u.length);h.length;){var u=h.substr(0,e);if(!u.length)break;if(u.length<e){l=u,c=u.length;break}else a.push(u),h=h.substr(e)}}else m&&(l+=" ",c++),l+=h,c+=h.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 Gr(t,e){return e&&t+e.split(`
`).join(`
`+t)}const pi="\\*",mi="\\d+\\.",Hr="(?:"+[pi,mi].join("|")+")";function hi(t,e){const r=new RegExp("(\\S(?: | )?)((?:"+e+")+)("+Hr+"(?:.*)+)$","gm");return t.replace(r,`$1
`+e+"$2$3")}const Vr=(t,e)=>t.match("^(?:"+e+")*"+Hr);function Zr(t){return" ".repeat(t.length)}var pe="* ";function fi(t,e){return Vr(e,t)?e:Zr(pe)+e}function gi(t,e){const r=fi.bind(null,e);return t.split(`
`).filter(Z).map(r).join(`
`)}const Jr=t=>t+". ";function di(t,e,r){return Vr(e,t)?{num:r+1,line:e.replace(pe,Jr(r+1))}:{num:r,line:Zr(Jr(r))+e}}function wi(t,e){const r=di.bind(null,e);let o=0;return t.split(`
`).filter(Z).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(b.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 bi(t){return t.replace(/:([A-Za-z0-9_\-\+]+?):/g,e=>{const r=Te.get(e);return r?r+" ":e})}function Ei(t,e){return e=e||process.stdout.columns,new Array(e).join(t)}function xi(t){return t.replace(ni,":")}function qr(t,e){if(!t)return[];e=e||Z;const r=e(t).split(`
`),o=[];return r.forEach(n=>{if(!n)return;const a=n.replace(oi,"").split(zr);o.push(a.splice(0,a.length-1))}),o}function Xr(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function ki(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function Z(t){return t}function me(){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 Yr=({name:t,URL:e,imgURL:r})=>r?`[](${e})`:`[${t}](${e})`,Ai=t=>{let e="";for(let r=0;r<t.length;r++)e+=Yr(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=Et(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()}`},B=async t=>{const e=I(t);return e==="path"?await U(t,"utf-8"):e==="url"?await H(t):t},Ti=async t=>await B(t),ji=async t=>await B(t),Ci=async t=>{t=await B(t);const e=await ie.get("marked");return await new e({gfm:!1}).parse(t)},Kr=async(t,e)=>{t=await B(t);const r=await ie.get("marked"),o=new r;return o.use(li(e?.renderer,e?.highlight)),await o.parse(t)},Qr=async t=>(t=await B(t),pn.toMarkdown(t)),Si=async t=>{t=await B(t);const e=await Qr(t);return await Kr(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(`
`)},to=async t=>{t=await B(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 to(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,d)=>{const $=d>0&&u.level>e?" ".repeat(u.level-e):"";r+=`${$}- [${u.title}](#${u.anchor})
`}),r},N={BUN:"bun",NPM:"npm",PNPM:"pnpm",YARN:"yarn"},W={NODE:"node",BUN:"bun",DENO:"deno"},J=(t,e)=>{try{const r=o=>o.replace(/^git\+/,"").replace(/\.git$/,"");return typeof t?.repository=="object"&&"url"in t.repository&&t.repository.url?Et(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")}},Ni=async(t,e)=>{const r=await q(t);return J(r,e)},Ri=async(t,e)=>{const r=await X(t,e?.pkg);return J(r,e)},Oi=async(t,e)=>{const r=await Y(t);return J(r,e)},Mi=async(t,e)=>{const r=await ut(t,e?.pkg);return J(r,e)},q=async(t,e)=>{const r=e?.registry||"https://registry.npmjs.org",o=await Qt(Et(r,t.toLowerCase()));return o.versions[e?.version?e.version:o["dist-tags"].latest]},X=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 q(o,e)},he=t=>f(T(t),"package.json"),Y=async t=>await kt(he(t)),ut=async(t,e)=>{if(typeof t=="object")return t;if(typeof t!="string")return await X(t,e?.remote);const r=I(t);return r==="url"?await X(t,e?.remote):r==="path"?await Y(t):await q(t,e?.remote)},eo=async t=>{const e=await Y(t);return{id:e.name||O(t),packagePath:he(t),dir:T(t),repoUrl:J(e),content:e}},ro=async(t="./")=>{let e=C(t);for(;;){const r=f(e,"package.json");if(await L(r))return r;const o=T(e);if(o===e)throw new Error("No package.json found in any parent directory.");e=o}},Ui=async(t="./")=>{const e=await ro(t);return T(e)};class Ii{#t;default=N.NPM;#e(e){if(e?.includes(N.PNPM))return N.PNPM;if(e?.includes(N.YARN))return N.YARN;if(e?.includes(N.BUN))return N.BUN}constructor({pkg:e}){this.#t=e}get value(){return this.dev||this.prod||this.default}get prod(){return this.#e(this.#t.packageManager)}get dev(){return this.#e(this.#t.devEngines?.packageManager?.name)}get prodCmds(){return this.prod?Tt(this.prod,!!this.#t.works