@ngm-dev/cli
Version:
A CLI for ui.angular-material.dev
80 lines (77 loc) • 100 kB
JavaScript
#!/usr/bin/env node
import {b,a,w,v,u,H,r,p,F,f,j,d,A,c,n,i,G,q,J,I,m,h,z}from'./chunk-SNPGRLIR.js';import {Command,Argument,program,Option}from'commander';import pe,{readFileSync,existsSync}from'node:fs';import {outro,confirm,isCancel,cancel,text,select,log,password,multiselect,spinner,intro,group}from'@clack/prompts';import $ from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Q from'pathe';import*as x from'valibot';import us from'is-unicode-supported';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import jo from'validate-npm-package-name';import gs from'node:os';import {promisify,stripVTControlCharacters}from'node:util';import Qs from'escape-string-regexp';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import Gn from'boxen';import {diffLines,diffChars}from'diff';import Fn from'semver';import {cursor,erase}from'sisteransi';import bs from'@anthropic-ai/sdk';import Rs from'ollama';import Ss from'openai';import $s from'conf';import Wr from'node-fetch';import*as Zn from'css-dependency';import*as eo from'prettier';import*as ro from'parse5';import ti from'oxc-parser';import {walk}from'estree-walker';import*as vo from'svelte/compiler';import*as ko from'vue/compiler-sfc';import nt from'fs';import kr,{relative}from'path';import {glob}from'glob';import zi from'ignore';import {exec}from'node:child_process';import*as he from'node:fs/promises';import je from'node:path';var ht={name:"@ngm-dev/cli",description:"A CLI for ui.angular-material.dev",version:"1.5.0"};var ms=us(),ae=(e,t)=>ms?e:t,bn=ae("\u25C6","*"),kn=ae("\u25C6","*"),xn=ae("\u25A0","x"),L=$.gray(ae("\u2502","|")),Lt=$.gray(ae("\u2500","-")),Cn=$.gray(ae("\u2510","+")),Rn=$.gray(ae("\u2518","+")),Ft=$.gray(ae("\u251C","+")),Sn=$.gray(ae("\u252C","+"));$.gray(ae("\u250C","T"));var jn=$.gray(ae("\u2514","-")),ve=$.bgRgb(245,149,66).black(" WARN "),we=$.bgBlueBright.white(" INFO "),Mt=$.bgRedBright.white(" ERROR "),Bt=$.hex("#6750A4")(b),Rr=$.hex("#6750A4")(a),Te={SPACE:$.bgBlackBright.white(" SPACE "),ENTER:$.bgBlackBright.white(" ENTER "),A:$.bgBlackBright.white(" A ")};var Pn=(e,t)=>{let r=[];for(let[n,o]of e)r.push(t(n,o));return r},En=(e,t)=>{let r=0;for(let n of e)r=r+t(n);return r};var Vt=(e,t,r=" ")=>{if(stripVTControlCharacters(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-stripVTControlCharacters(e).length)+e};var ys=/\n|\r\n/g,W=e=>e.split(ys),U=(e,{lineNumbers:t=false,prefix:r}={})=>{let n=e;if(t){let o=e.length.toString().length+1;n=n.map((s,i)=>`${Vt(`${i+1}`,o)} ${s}`);}return r!==void 0&&(n=n.map((o,s)=>`${r(s,e.length)}${o}`)),n.join(gs.EOL)};var hs={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},vs={"install-as-dev-dependency":"-D"},ws={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},An={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},On={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Sr={bun:hs,npm:ws,pnpm:An,deno:vs,yarn:On,"yarn@berry":On,"pnpm@6":An};var Ve=()=>new $s({projectName:b});var jr="http-registries-w-tokens",Pe=class{#e;constructor(t){this.#e=t??Ve();}getKey(t){return `${t}-token`.toLowerCase()}get(t){let r=this.getKey(t);return this.#e.get(r,void 0)}set(t,r){if(t.startsWith("http")&&!(t.startsWith("http-username")||t.startsWith("http-machine-id"))){let o=this.getHttpRegistriesWithTokens(),s=t.slice(5);o||(o=[]),o.includes(s)||o.push(s),this.#e.set(jr,o);}let n=this.getKey(t);this.#e.set(n,r);}delete(t){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),o=t.slice(5),s=n.indexOf(o);s!==-1&&(n=[...n.slice(0,s),...n.slice(s+1)]),this.#e.set(jr,n);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(jr);return t||[]}getHttpUsernameToken(t){return `http-username-${t}`}getHttpMachineIdToken(t){return `http-machine-id-${t}`}};var Ir={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:n,additionalInstructions:o,messages:s})=>{let i=await Tn("Anthropic");n||r.start("Asking Claude 3.7 Sonnet");let a=Pr({originalFile:e,newFile:t,additionalInstructions:o,rePrompt:s!==void 0&&s.length>0});n?.(`Prompting Claude 3.7 Sonnet with:
${JSON.stringify(a,null," ")}`);let c=await Ps({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return n||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:Er(c),prompt:a.message}:{content:t.content,prompt:a.message}}},"OpenAI o3-mini":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:n,additionalInstructions:o,messages:s})=>{let i=await Tn("OpenAI");n||r.start("Asking OpenAI o3-mini");let a=Pr({originalFile:e,newFile:t,additionalInstructions:o,rePrompt:s!==void 0&&s.length>0});n?.(`Prompting OpenAI o3-mini with:
${JSON.stringify(a,null," ")}`);let c=await js({model:"o3-mini",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return n||r.stop("OpenAI o3-mini updated the file"),c?{content:Er(c),prompt:a.message}:{content:t.content,prompt:a.message}}},Phi4:{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:n,additionalInstructions:o,messages:s})=>{n||r.start("Asking Phi4");let i=Pr({originalFile:e,newFile:t,additionalInstructions:o,rePrompt:s!==void 0&&s.length>0});n?.(`Prompting Phi4 with:
${JSON.stringify(i,null," ")}`);let a=await Es({model:"phi4",prompt:i,messages:s});return n||r.stop("Phi4 updated the file"),a?{content:Er(a),prompt:i.message}:{content:t.content,prompt:i.message}}}},js=async({prompt:e,maxTokens:t,model:r,apiKey:n,messages:o})=>{let a=(await new Ss({apiKey:n}).chat.completions.create({model:r,max_completion_tokens:t,messages:[{role:"system",content:e.system},...o??[],{role:"user",content:e.message}]})).choices[0];return a.message.content===null?null:a.message.content},Ps=async({prompt:e,messages:t,maxTokens:r,model:n,apiKey:o})=>{let s=new bs({apiKey:o}),i=[];if(t)for(let l of t)i.push({role:l.role,content:[{type:"text",text:l.content}]});i.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await s.messages.create({model:n,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:i})).content[0];return c.type!=="text"?null:c.text},Es=async({prompt:e,messages:t,model:r})=>(await Rs.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content,Pr=({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:n})=>({system:"You will merge two files provided by the user. You will respond only with the resulting code. DO NOT format the code with markdown, DO NOT put the code inside of triple quotes, only return the code as a raw string. DO NOT make unnecessary changes.",message:n?r??"":`
This is my current file ${e.path}:
<code>
${e.content}
</code>
This is the file that has changes I want to update with ${t.path}:
<code>
${t.content}
</code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
`}),Er=e=>{let t=e.trim();if(t.startsWith("```")&&(t=W(t).slice(1).join(`
`).trim()),t.endsWith("```")){let r=W(t);t=r.slice(0,r.length-1).join(`
`).trim();}return t},Tn=async e=>{let t=new Pe,r=t.get(e);if(!r){let n=await password({message:`Paste your ${e} API key:`,validate(o){if(o.trim()==="")return "Please provide an API key"}});(isCancel(n)||!n)&&(cancel("Canceled!"),process.exit(0)),r=n;}return t.set(e,r),r};var vt=ht;var Dn=e=>/^\s+$/g.test(e),wt=e=>{let t=e.length-1;for(;Dn(e[t])&&t>=0;){if(e[t]===`
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},_n=({from:e,to:t,changes:r,expand:n=false,maxUnchanged:o=5,colorRemoved:s=$.redBright,colorAdded:i=$.greenBright,colorCharsRemoved:a=$.bgRedBright,colorCharsAdded:c=$.bgGreenBright,prefix:l,onUnchanged:d,intro:m})=>{let v="",u=En(r,p=>p.count??0).toString().length+1,g=0;if(r.length===1&&!r[0].added&&!r[0].removed)return d({from:e,to:t,changes:r,expand:n,maxUnchanged:o,colorAdded:i,colorRemoved:s,prefix:l,onUnchanged:d,intro:m});v+=m({from:e,to:t,changes:r,expand:n,maxUnchanged:o,colorAdded:i,colorRemoved:s,prefix:l,onUnchanged:d,intro:m});let h=p=>$.gray(`${l?.()??""}${Vt(`${p+1+g} `,u)} `);for(let p=0;p<r.length;p++){let f=r[p],k=r[p-1]?.added||r[p-1]?.removed,y=r[p+1]?.added||r[p+1]?.removed;if(!f.added&&!f.removed){if(!n&&f.count!==void 0&&f.count>o){let A=g,I=W(wt(f.value)),_=0;if(y&&(_+=o),k&&(_+=o),_>=I.length){v+=`${U(I,{prefix:h})}
`,g+=I.length;continue}if(k&&(v+=`${U(I.slice(0,o),{prefix:h})}
`),I.length>_){let ee=I.length-_;v+=`${U(W($.gray(`+ ${ee} more unchanged (${$.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Vt(" ",u)} `})}
`;}y&&(g=g+I.length-o,v+=`${U(I.slice(I.length-o),{prefix:h})}
`),g=A+f.count;continue}v+=`${U(W(wt(f.value)),{prefix:h})}
`,g+=f.count??0;continue}let w=A=>A.added?i(wt(A.value)):A.removed?s(wt(A.value)):A.value,j=A=>A.added?c(wt(A.value)):A.removed?a(wt(A.value)):A.value;if(f.removed&&f.count===1&&r[p+1]?.added&&r[p+1]?.count===1){let I=diffChars(f.value,r[p+1].value).map(_=>j(_)).join("");v+=`${h(0)}${I}`,g+=1,p++;}else Dn(f.value)?(v+=`${U(W(j(f)),{prefix:A=>`${h(A)}${j({removed:true,value:" ",added:false})}`})}
`,f.removed||(g+=f.count??0)):(v+=`${U(W(w(f)),{prefix:h})}
`,f.removed||(g+=f.count??0));}return v.endsWith(`
`)||(v=v+=`
`),v};var Nr="latest-version",As=60*60*1e3,Ln=async({noCache:e=false}={})=>{try{let t=Ve(),r;if(!e){let a=t.get(Nr);if(a){if(a.expiration>Date.now())return r=a.version,p(r);t.delete(Nr);}}let n=new AbortController,o=setTimeout(()=>{n.abort();},1e3),s=await Wr("https://raw.githubusercontent.com/Angular-Material-Dev/ngm-dev-cli/refs/heads/main/packages/cli/package.json",{signal:n.signal});if(clearTimeout(o),!s.ok)return q("Error getting version");let{version:i}=await s.json();return r=i,t.set(Nr,{expiration:Date.now()+As,version:r}),p(r)}catch(t){return q(`Error getting version: ${t}`)}};var Os=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Ts=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,He=e=>{let t=Os.exec(e)||Ts.exec(e);return t?p({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):q(`invalid package name: ${e}`)};var Or=(e,t)=>{let r=Q.join(e,"package.json");if(pe.existsSync(r))return r;if(e===t)return;let n=e.split(/[\/\\]/);return Or(n.slice(0,n.length-1).join("/"),t)},Tr=e=>{if(!pe.existsSync(e))return q(`${e} doesn't exist`);let t=pe.readFileSync(e).toString();try{return p(JSON.parse(t))}catch(r){return q(`Error reading package.json: ${r}`)}},cr=e=>e[0]==="^"?e.slice(1):e,Bn=(e,t,{cwd:r})=>{let n=e,o=t,s=Tr(Q.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of n){let{name:c,version:l}=He(a).unwrap(),d=i.dependencies[c];if(l===void 0&&d){n.delete(a);continue}d&&Fn.satisfies(cr(d),l)&&n.delete(a);}if(i.devDependencies)for(let a of o){let{name:c,version:l}=He(a).unwrap(),d=i.devDependencies[c];if(l===void 0&&d){o.delete(a);continue}d&&Fn.satisfies(cr(d),l)&&o.delete(a);}}return {dependencies:n,devDependencies:o}};var Jn=async(e,{loading:t})=>{for(let r of e){t.start(r.loadingMessage);try{await r.run();}catch(n){t.stop(`Error while ${r.loadingMessage}`),console.error(n);}t.stop(r.completedMessage);}},Kn=async({tasks:e,startMessage:t,stopMessage:r,loading:n})=>{n.start(t),await Promise.all([...e.map(o=>o.run({message:n.message}))]),n.stop(r);},be=({verbose:e}={})=>{let t=spinner();return {message:r=>{e?e(r??""):t.message(r);},stop:r=>{e?e(r??""):t.stop(r);},start:r=>{e?e(r??""):t.start(r);}}},at=(e,t="Next Steps")=>{let r=Gn(e.join(`
`),{title:t,textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Ft),bottomLeft:stripVTControlCharacters(Ft),topRight:stripVTControlCharacters(Cn),top:stripVTControlCharacters(Lt),bottom:stripVTControlCharacters(Lt),bottomRight:stripVTControlCharacters(Rn),left:stripVTControlCharacters(L),right:stripVTControlCharacters(L)}});return `${L}
${r}
`},Hn=(e,t=3)=>{let r=e.slice(0,t),n=e.length-r.length;return `${r.join(", ")}${n>0?` and ${n} other(s)`:""}`},Js=async(e,t,r)=>{let n=(await detect$1({cwd:process.cwd()}))?.agent??"npm",o=resolveCommand$1(n,"global",["@ngm-dev/cli@latest"]),s=[`Update available! ${$.redBright(t)} -> ${$.greenBright(r)}`,`Run ${$.cyan(`${o?.command} ${o?.args.join(" ")}`)} to update!`,""];return Gn(s.join(`
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})},fe=async()=>{console.clear();let e=await Ln();e.isOk()&&Fn.lt(vt.version,e.unwrap())&&console.info(await Js(vt.name,vt.version,e.unwrap())),intro(`${$.bgHex("#6750A4").black(` ${vt.name} `)}${$.gray(` v${vt.version} `)}`);},Wn="model-preference",$t=async({incoming:e,current:t,config:r,options:n})=>{let o=Ve();process.stdout.write(`${L}
`);let s=false,i=e.content,a=o.get(Wn,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,i),d=_n({from:e.path,to:t.path,changes:l,expand:n.expand,maxUnchanged:n.maxUnchanged,prefix:()=>`${L} `,onUnchanged:({from:m,to:v,prefix:u})=>`${u?.()??""}${$.cyan(m)} \u2192 ${$.gray(v)} ${$.gray("(unchanged)")}
`,intro:({from:m,to:v,changes:u,prefix:g})=>{let h=u.filter(p=>p.added||p.removed).length;return `${g?.()??""}${$.cyan(m)} \u2192 ${$.gray(v)} (${h} change${h===1?"":"s"})
${g?.()??""}
`}});if(process.stdout.write(d),(l.length>1||t.content==="")&&(s=n.yes,!n.yes&&!n.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${$.yellow("Update with AI")} \u2728 ${$.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${$.yellow("Update with AI")} \u2728 ${$.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${$.yellow("Update with AI")} \u2728`,value:"update"});let v=await select({message:"Accept changes?",options:m});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v==="update"||v==="update-iterate"){v==="update"&&(c=[]);let u=await select({message:"Select a model",options:Object.keys(Ir).map(h=>({label:h,value:h})),initialValue:a});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!==a&&o.set(Wn,u),a=u;let g=await text({message:"Additional instructions:",defaultValue:"None",validate:h=>{if(c.length!==0&&h.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(g)&&(cancel("Canceled!"),process.exit(0));try{let{content:h,prompt:p}=await Ir[a].updateFile({originalFile:t,newFile:{content:v==="update-iterate"?i:e.content,path:e.path},additionalInstructions:g!=="None"?g:void 0,loading:n.loading,verbose:n.verbose,messages:c});i=h,c.push({role:"user",content:p}),c.push({role:"assistant",content:h});}catch(h){n.loading.stop(),log.error($.red(`Error getting completions: ${h}`)),process.stdout.write(`${L}
`);continue}i=await lr({file:{content:i,destPath:t.path},prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${L}
`);continue}s=v==="accept";break}break}return s?{applyChanges:true,updatedContent:i}:{applyChanges:false}},Ye=async(e,t,{yes:r,no:n=false,cwd:o,pm:s,ignoreWorkspace:i=false})=>{let{dependencies:a,devDependencies:c}=Bn(e,t,{cwd:o});if(a.size>0||c.size>0){let d=r;if(!r&&!n){let m=await confirm({message:`Would you like to install dependencies?
${a.size>0?`${$.gray("Dependencies:")} ${Array.from(a).join(", ")}`:""}
${c.size>0?`${$.gray("Dev Dependencies:")} ${Array.from(c).join(", ")}`:""}`,initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),d=m;}if(d)return a.size>0&&await Dr({pm:s,deps:Array.from(a),dev:false,cwd:o,ignoreWorkspace:i}),c.size>0&&await Dr({pm:s,deps:Array.from(c),dev:true,cwd:o,ignoreWorkspace:i}),{installed:true,dependencies:a,devDependencies:c}}return {installed:false,dependencies:a,devDependencies:c}},Yn=e=>{let t=$.dim(L),r=$.green(bn),n=$.green(kn),o=$.red(xn);process.stdout.write(`${t}
`),process.stdout.write(`${r} ${e}
`);let s="",i="",a=(l=false)=>{if(!i)return;let d=process.stdout.columns,v=i.split(`
`).reduce((u,g)=>u+Math.ceil(g.length/d),0)+(l?1:0);process.stdout.write(cursor.up(v)),process.stdout.write(erase.down());},c=(l=0)=>{let d=s.split(`
`).slice(-l);i="";for(let m of d)i+=`${t} ${m}
`;process.stdout.write($.dim(i));};return {set text(l){a(),s+=l;let d=Math.ceil(process.stdout.rows/2);c(d);},fail(l){a(true),process.stdout.write(`${o} ${l}
`),c();},success(l){a(true),process.stdout.write(`${n} ${l}
`);}}};var _r=async(e,t)=>{let r=await confirm({message:e,initialValue:t});return isCancel(r)&&(cancel("Canceled!"),process.exit(0)),r};var Dr=async({pm:e,deps:t,dev:r,cwd:n,ignoreWorkspace:o=false})=>{let s=[...t];r&&s.push(Sr[e]["install-as-dev-dependency"]);let i=Sr[e]["no-workspace"];o&&i&&s.push(i);let a=resolveCommand$1(e,"add",s);a==null&&program.error($.red(`Could not resolve add command for '${e}'.`));let c=Yn(`Installing dependencies with ${e}...`);try{let l=execa(a.command,[...a.args],{cwd:n});l.stdout.on("data",d=>{c.text=d;}),l.stderr.on("data",d=>{c.text=d;}),await l,c.success(`Installed ${$.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}},zs=/\{\{([^\/]+)\/([^\}]+)\}\}/g,qn=({template:e,config:t,destPath:r,cwd:n})=>{let o=Q.join(r,"../");return e.replace(zs,(s,i,a)=>{if(t.paths[i]===void 0){if(t.paths["*"].startsWith(".")){let c=Q.relative(o,Q.join(n,t.paths["*"],i,a));return c.startsWith(".")?c:`./${c}`}return Q.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let c=Q.relative(o,Q.join(n,t.paths[i],a));return c.startsWith(".")?c:`./${c}`}return Q.join(t.paths[i],a)})};var Jt=async({file:e,config:t,imports:r,watermark:n,prettierOptions:o,cwd:s,verbose:i})=>{let a=Ee.find(l=>l.matches(e.destPath)),c=e.content;if(a){t.watermark&&(c=`${a.comment(n)}
${c}`),i?.(`Formatting ${$.bold(e.destPath)}`);try{c=await a.format(c,{filePath:e.destPath,formatter:t.formatter,prettierOptions:o});}catch(l){return q(`Error formatting ${$.bold(e.destPath)} ${l}`)}}for(let[l,d]of Object.entries(r)){let m=qn({template:d,config:t,destPath:e.destPath,cwd:s}),v=new RegExp(`(['"])${Qs(l)}\\1`,"g");c=c.replaceAll(v,`$1${m}$1`);}return p(c)},lr=async({file:e,formatter:t,prettierOptions:r})=>{let n=Ee.find(s=>s.matches(e.destPath)),o=e.content;if(n)try{o=await n.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r});}catch{return o}return o},Xn=e=>{let t=[".js",".ts",".cjs",".mjs"];if(!z(e,t))return;let r=Q.dirname(e),n=pe.readdirSync(r),o=Q.parse(e);for(let s of n)if(z(s,t)&&Q.parse(s).name===o.name)return Q.join(r,s)},bt=e=>{let t;try{if(t=getTsconfig(e,"tsconfig.json"),!t&&(t=getTsconfig(e,"jsconfig.json"),!t))return p(null)}catch(r){return q(`Error while trying to get ${$.bold("tsconfig.json")}: ${r}`)}return p(t)};var to={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=Zn.parse(i,{allowTailwindDirectives:true});if(a.isErr())return q(a.unwrapErr().message);let c=a.unwrap(),l=Ne({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:r});return l.isErr()?q(l.unwrapErr().map(d=>Ie(d)).join(`
`)):p(l.unwrap())},comment:e=>`/*
${U(W(e),{prefix:()=>" "})}
*/`,format:async(e,{formatter:t,prettierOptions:r,filePath:n})=>t&&t==="prettier"?await eo.format(e,{filepath:n,...r}):e};var oo={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=ro.parse(i),c=[],l=(m,v)=>{if(m&&(v(m),m.childNodes&&m.childNodes.length>0))for(let u of m.childNodes)l(u,v);};for(let m of a.childNodes)l(m,v=>{if(v.tagName==="script")for(let u of v.attrs)u.name==="src"&&c.push(u.value);if(v.tagName==="link"&&v.attrs.find(u=>u.name==="rel"&&u.value==="stylesheet"))for(let u of v.attrs)u.name==="href"&&!u.value.startsWith("http")&&c.push(u.value);});let d=Ne({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?q(d.unwrapErr().map(m=>Ie(m)).join(`
`)):p(d.unwrap())},comment:e=>`<!--
${U(W(e),{prefix:()=>" "})}
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await eo.format(e,{parser:"html",...r}):e};var dr=(e,t)=>{let r=ti.parseSync(e,t),n=[];for(let o of r.module.staticImports)n.push(o.moduleRequest.value);for(let o of r.module.dynamicImports){let s=t.slice(o.moduleRequest.start+1,o.moduleRequest.end-1);n.push(s);}for(let o of r.module.staticExports)for(let s of o.entries)s.moduleRequest&&n.push(s.moduleRequest.value);return n},io={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=dr(e,i),c=Ne({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:r});return c.isErr()?q(c.unwrapErr().map(l=>Ie(l)).join(`
`)):p(c.unwrap())},comment:e=>`/*
${U(W(e),{prefix:()=>" "})}
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:n})=>t&&t==="prettier"?await eo.format(e,{filepath:r,...n}):e};var co=async(e,{formatter:t,prettierOptions:r,filePath:n})=>t&&t==="prettier"?await eo.format(e,{parser:"json",filepath:n,...r}):e,fr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>p({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:co},lo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>p({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
${U(W(e),{prefix:()=>" "})}
*/`,format:co};var ri=async(e,{formatter:t,prettierOptions:r,filePath:n})=>t&&t==="prettier"?await eo.format(e,{parser:"markdown",filepath:n,...r}):e,fo={matches:e=>e.endsWith(".md"),resolveDependencies:()=>p({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
${U(W(e),{prefix:()=>" "})}
-->`,format:ri};var go={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=Zn.parse(i);if(a.isErr())return q(a.unwrapErr().message);let c=a.unwrap(),l=Ne({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:r});return l.isErr()?q(l.unwrapErr().map(d=>Ie(d)).join(`
`)):p(l.unwrap())},comment:e=>`/*
${U(W(e),{prefix:()=>" "})}
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await eo.format(e,{parser:"scss",...r}):e};var wo={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=vo.parse(i,{modern:true,filename:e});if(!a.instance&&!a.module)return p({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=m=>{(m.type==="ImportDeclaration"||m.type==="ExportAllDeclaration"||m.type==="ExportNamedDeclaration")&&typeof m.source?.value=="string"&&c.push(m.source.value),m.type==="ImportExpression"&&m.source.type==="Literal"&&typeof m.source.value=="string"&&c.push(m.source.value);};a.instance&&walk(a.instance,{enter:l}),a.module&&walk(a.module,{enter:l});let d=Ne({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?q(d.unwrapErr().map(m=>Ie(m)).join(`
`)):p(d.unwrap())},comment:e=>`<!--
${U(W(e),{prefix:()=>" "})}
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:n})=>t&&t==="prettier"&&n&&n.plugins?.find(o=>o==="prettier-plugin-svelte")?await eo.format(e,{filepath:r,...n}):e};var $o={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>p({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
${U(W(e),{prefix:()=>" "})}
-->`,format:async e=>e};var xo={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:n,cwd:o,containingDir:s})=>{let i=pe.readFileSync(e).toString(),a=ko.parse(i,{filename:e}),c=[];if(a.descriptor.script?.content){let d=dr("noop.ts",a.descriptor.script.content);c.push(...d);}if(a.descriptor.scriptSetup?.content){let d=dr("noop.ts",a.descriptor.scriptSetup.content);c.push(...d);}if(c.length===0)return p({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Ne({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:n,cwd:o,containingDir:s,doNotInstall:["vue","nuxt",...r]});return l.isErr()?q(l.unwrapErr().map(d=>Ie(d)).join(`
`)):p(l.unwrap())},comment:e=>`<!--
${U(W(e),{prefix:()=>" "})}
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await eo.format(e,{parser:"vue",...r}):e};var Ro={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>p({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>U(W(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await eo.format(e,{parser:"yaml",...r}):e};var Ie=e=>`${U(W(e),{prefix:t=>t===0?`${L} ${Mt} `:`${L} `})}`,Ne=({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:n,doNotInstall:o,dirs:s,cwd:i})=>{let a=[],c=new Set,l=new Set,d={};for(let u of e){if(builtinModules.includes(u)||u.startsWith("node:"))continue;if(u.startsWith(".")){let f=Po(u,t,{filePath:r,containingDir:n,dirs:s,cwd:i});if(f.isErr()){a.push(f.unwrapErr());continue}let k=f.unwrap();k&&(l.add(k.dependency),d[u]=k.template);continue}let g=He(u);if(!g.isErr()){let f=g.unwrap();if(jo(f.name).validForNewPackages){c.add(u);continue}}let h=ci(u,t,{filePath:r,containingDir:n,dirs:s,cwd:i});if(h.isErr()){a.push(h.unwrapErr());continue}let p=h.unwrap();p?(l.add(p.dependency),d[u]=p.template):console.warn(`${L} ${ve} Skipped adding import \`${$.cyan(u)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a.length>0)return q(a);let{devDependencies:m,dependencies:v}=di(Array.from(c),r,{doNotInstall:o||[]});return p({dependencies:v,devDependencies:m,local:Array.from(l),imports:d})},Po=(e,t,{filePath:r,containingDir:n,dropExtension:o=true,alias:s,dirs:i,cwd:a})=>{if(t&&(e.startsWith("./")||e==="."))return p(void 0);let c=t?Q.join(n,"../"):Q.join(r,"../"),l=Q.join(Q.join(r,"../"),e),d=Q.join(c,"../");if(n&&l.startsWith(n))return p(void 0);if(l.startsWith(d))return p(So(l.slice(d.length),o));for(let m of i){let v=Q.resolve(Q.join(a,m)),u=Q.resolve(l);if(u.startsWith(v))return p(So(u.slice(v.length+1),o))}return q(`${r}:
${s||e} references code not contained in ${$.bold(i.join(", "))} and cannot be resolved.`)},So=(e,t=true)=>{let[r,n,...o]=e.split("/"),s=n;s===void 0&&(s="index");let i=s;t&&i.includes(".")&&(i=i.slice(0,i.length-Q.parse(i).ext.length));let a=`${r}/${i}`,c=`{{${a}}}`;return o.length===0?i.length!==s.length&&(c+=Q.parse(s).ext):c+=`/${o.join("/")}`,{dependency:a,template:c}},ci=(e,t,{filePath:r,dirs:n,cwd:o,containingDir:s})=>{let i=bt(r);if(i.isErr())return q(i.unwrapErr());let a=i.unwrap();if(a===null)return p(void 0);let c=createPathsMatcher(a);if(c){let l=c(e);for(let d of l){let m=pi(d);if(!m)continue;let v=Q.relative(Q.resolve(Q.join(r,"../")),m.prettyPath),u=li(m.prettyPath,m.path,[".js",".ts"]),g=Po(v,t,{filePath:r,containingDir:s,alias:e,dropExtension:u,dirs:n,cwd:o,modIsFile:m.type==="file"});if(g.isErr())return q(g.unwrapErr());if(g.unwrap())return p(g.unwrap());break}}return p(void 0)},li=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let n=Q.parse(e),o=Q.parse(t),s=Q.join(n.dir,n.name),i=Q.join(o.dir,o.name);return s!==i?false:!!(r.includes(n.ext)&&r.includes(o.ext))},pi=e=>{if(pe.existsSync(e))return {path:e,prettyPath:e,type:pe.statSync(e).isDirectory()?"directory":"file"};let t=Q.join(e,"../");if(!pe.existsSync(t))return;let r=Q.parse(e);if(r.ext===".js"){let o=`${e.slice(0,e.length-3)}.ts`;if(pe.existsSync(o))return {path:o,prettyPath:e,type:"file"}}let n=pe.readdirSync(t);for(let o of n){let s=Q.parse(o);if(s.name===r.base){let i=Q.join(t,o),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:pe.statSync(i).isDirectory()?"directory":"file"}}}},di=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let n=new Set(r),o=Or(Q.dirname(t),""),s=new Set,i=new Set;if(o){let{devDependencies:a,dependencies:c}=JSON.parse(pe.readFileSync(o,"utf-8"));for(let l of e){let d=He(l);if(d.isErr()){console.warn(`${L} ${ve} Skipped adding import \`${$.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let m=d.unwrap();if(!jo(m.name).validForNewPackages){console.warn(`${L} ${ve} Skipped adding import \`${$.cyan(l)}\`. Reason: Not a valid package name`);continue}if(n.has(m.name))continue;let v;if(c!==void 0&&(v=c[m.name]),v!==void 0){s.add(`${m.name}@${v}`);continue}if(a!==void 0&&(v=a[m.name]),v!==void 0){i.add(`${m.name}@${v}`);continue}s.add(m.name);}}return {dependencies:Array.from(s),devDependencies:Array.from(i)}},Ee=[to,oo,fr,lo,fo,go,wo,$o,io,xo,Ro];var Io=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),No=x.union([x.literal("off"),x.literal("warn"),x.literal("error")]),ui=x.union([x.literal("no-category-index-file-dependency"),x.literal("no-unpinned-dependency"),x.literal("require-local-dependency-exists"),x.literal("max-local-dependencies"),x.literal("no-circular-dependency"),x.literal("no-unused-block"),x.literal("no-framework-dependency"),x.literal("require-config-file-exists"),x.literal("no-config-file-framework-dependency"),x.literal("no-config-file-unpinned-dependency")]),Ao={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${$.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let n of e.localDependencies){let[o,s]=n.split("/"),i=t.categories.find(c=>c.name.trim()===o.trim()),a=`${$.bold(`${e.category}/${e.name}`)} depends on local dependency ${$.bold(n)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(c=>c.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let n of e.localDependencies){let[o,s]=n.split("/");if(s!=="index")continue;let i=t.categories.find(c=>c.name===o);!i||!i.blocks.find(c=>c.name===s)||r.push(`${$.bold(`${e.category}/${e.name}`)} depends on ${$.bold(`${o}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],n;return typeof t[0]!="number"?n=5:n=t[0],e.localDependencies.length>n&&r.push(`${$.bold(`${e.category}/${e.name}`)} has too many local dependencies (${$.bold(e.localDependencies.length)}) limit (${$.bold(n)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],n=`${e.category}/${e.name}`,o=mr(n,e,t.categories);return o&&r.push(`There is a circular dependency in ${$.bold(n)}: ${$.bold(o.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,n=t.categories.flatMap(o=>o.blocks).filter(o=>o.list);for(let o of n)if(mr(r,o,t.categories))return;return [`${$.bold(r)} is unused and will be ${$.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(n=>He(n).unwrap().name).filter(n=>Io.has(n));if(r.length>0)for(let n of r)t.push(`${$.bold(`${e.category}/${e.name}`)} depends on ${$.bold(n)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let n of e.configFiles)pe.existsSync(Q.join(t,n.path))||r.push(`The ${$.bold(n.name)} config file doesn't exist at ${$.bold(Q.join(t,n.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let n=[...r.devDependencies??[],...r.dependencies??[]].map(o=>He(o).unwrap().name).filter(o=>Io.has(o));if(n.length>0)for(let o of n)t.push(`${$.bold(r.name)} depends on ${$.bold(o)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let n of [...r.dependencies??[],...r.devDependencies??[]])n.includes("@")||t.push(`Couldn't find a version to use for ${$.bold(n)}`);return t.length>0?t:void 0}}}},Oo=x.record(ui,x.union([No,x.tupleWithRest([No,x.union([x.string(),x.number()])],x.union([x.string(),x.number()]))])),Fr={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"},To=(e,t,r,n=Fr)=>{let o=[],s=[];for(let[i,a]of Object.entries(Ao)){if(a.scope==="block")continue;let c=n[i],l,d=[];if(Array.isArray(c)?(l=c[0],d.push(...c.slice(1))):l=c,l==="off")continue;let m=a.check({manifest:e,options:d,cwd:r,config:t});if(m){if(l==="error"){s.push(...m.map(v=>`${L} ${Mt} ${$.red(v)} ${$.gray(i)}`));continue}o.push(...m.map(v=>`${L} ${ve} ${v} ${$.gray(i)}`));}}for(let i of e.categories)for(let a of i.blocks)for(let[c,l]of Object.entries(Ao)){if(l.scope==="global")continue;let d=n[c],m,v=[];if(Array.isArray(d)?(m=d[0],v.push(...d.slice(1))):m=d,m==="off")continue;let u=l.check(a,{manifest:e,options:v,cwd:r,config:t});if(u){if(m==="error"){s.push(...u.map(g=>`${L} ${Mt} ${$.red(g)} ${$.gray(c)}`));continue}o.push(...u.map(g=>`${L} ${ve} ${g} ${$.gray(c)}`));}}return {warnings:o,errors:s}},mr=(e,t,r,n=[])=>{let o=[...n,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return o;if(n.includes(s))return;let[i,a]=s.split("/"),c=r.find(d=>d.name===i)?.blocks.find(d=>d.name===a);if(!c)continue;let l=mr(e,c,r,o);if(l)return [...l,e]}},Do=(e,t)=>{for(let r of t)for(let n of r.blocks){if(!n.list)continue;if(mr(e,n,t))return true}return false};var Mo=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],kt=e=>Mo.find(t=>e.endsWith(t))!==void 0,Bo=(e,{cwd:t,ignore:r,config:n})=>{let o;try{o=pe.readdirSync(e);}catch{program.error($.red(`Couldn't read the ${$.bold(e)} directory.`));}let s=[];for(let i of o){let a=Q.join(e,i);if(pe.statSync(a).isFile())continue;let c=`${Q.relative(t,a)}/`;if(r.ignores(c))continue;let l=Q.basename(i);if(!gi(l,n))continue;let d=mi(l,n),m={name:l,blocks:[]},v=pe.readdirSync(a);for(let u of v){let g=Q.join(a,u);if(pe.statSync(g).isFile()){if(kt(u))continue;let h=yi(u),p=_o(h,n);if(!Lo(h,n))continue;let f=Ee.find(_=>_.matches(u));if(!f){console.warn(`${L} ${ve} Skipped \`${$.bold(g)}\` \`*${$.bold(Q.parse(u).ext)}\` files are not currently supported!`);continue}let k=v.find(_=>Mo.find(ee=>_===`${h}${ee}`)),{dependencies:y,devDependencies:w,local:j,imports:A}=f.resolveDependencies({filePath:g,isSubDir:false,excludeDeps:n.excludeDeps,dirs:n.dirs,cwd:t}).match(_=>_,_=>{program.error($.red(_));}),I={name:h,directory:Q.relative(t,a),category:l,tests:k!==void 0,subdirectory:false,list:d?p:false,files:[u],localDependencies:j,_imports_:A,dependencies:y,devDependencies:w};k!==void 0&&I.files.push(k),m.blocks.push(I);}else {let h=u,p=_o(h,n);if(!Lo(h,n))continue;let f=new Set,k=new Set,y=new Set,w={},j=false,A=[],I=(ee,te)=>{for(let se of te){let C=Q.join(ee,se),M=C.slice(g.length+1);if(kt(se)){j=true,A.push(M);continue}if(pe.statSync(C).isDirectory()){if(!n.allowSubdirectories){console.warn(`${L} ${ve} Skipped \`${$.bold(Q.join(g,se))}\` subdirectories are not allowed! Allow them with ${$.bold("--allow-subdirectories")}!`);continue}let T=pe.readdirSync(C);I(C,T);continue}let b=Ee.find(T=>T.matches(se));if(!b){console.warn(`${L} ${ve} Skipped \`${C}\` \`*${$.bold(Q.parse(se).ext)}\` files are not currently supported!`);continue}let{local:B,dependencies:F,devDependencies:K,imports:O}=b.resolveDependencies({isSubDir:true,excludeDeps:n.excludeDeps,dirs:n.dirs,containingDir:g,filePath:C,cwd:t}).match(T=>T,T=>{program.error($.red(T));});for(let T of B)T!==`${l}/${h}`&&f.add(T);for(let T of F)k.add(T);for(let T of K)y.add(T);for(let[T,ne]of Object.entries(O))w[T]=ne;A.push(M);}};I(g,pe.readdirSync(g));let _={name:h,directory:Q.relative(t,g),category:l,tests:j,subdirectory:true,list:d?p:false,files:A,localDependencies:Array.from(f.keys()),dependencies:Array.from(k.keys()),devDependencies:Array.from(y.keys()),_imports_:w};m.blocks.push(_);}}s.push(m);}return s},Vo=(e,{cwd:t})=>{if(!e.configFiles)return;let r=[];for(let n of e.configFiles){let o=Ee.find(c=>c.matches(n.path));if(!o){r.push(n);continue}let{dependencies:s,devDependencies:i,local:a}=o.resolveDependencies({filePath:Q.join(t,n.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error($.red(c));});a.length>0&&program.error($.red(`${$.bold(n.name)} ${$.bold(n.path)} Config files cannot have local dependencies!`)),r.push({...n,dependencies:s,devDependencies:i});}return r},_o=(e,t)=>t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true,Lo=(e,t)=>t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true,mi=(e,t)=>t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true,gi=(e,t)=>t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true,yi=e=>Q.parse(Q.basename(e)).name,Wo=e=>{let t=[];for(let n of e){let o=[];for(let s of n.blocks){let i=`${s.category}/${s.name}`;!s.list&&!Do(i,e)||o.push(s);}o.length>0&&t.push({name:n.name,blocks:o});}return [t,0]};var dt=`${c}.json`,tt=`${c}-build-config.json`,Mr=x.union([x.literal("prettier")]),vi=x.objectWithRest({"*":x.string()},x.string()),Br=x.object({$schema:x.string(),repos:x.optional(x.array(x.string()),[]),includeTests:x.boolean(),paths:vi,configFiles:x.optional(x.record(x.string(),x.string())),watermark:x.optional(x.boolean(),true),formatter:x.optional(Mr)}),Ce=e=>{if(!pe.existsSync(Q.join(e,dt)))return q("Could not find your configuration file! Please run `init`.");let t=x.safeParse(Br,JSON.parse(pe.readFileSync(Q.join(e,dt)).toString()));return t.success?p(t.output):q(`There was an error reading your \`${dt}\` file!`)},wi=x.object({$schema:x.string(),meta:x.optional(u),peerDependencies:x.optional(v),configFiles:x.optional(x.array(w)),dirs:x.array(x.string()),outputDir:x.optional(x.string()),includeBlocks:x.optional(x.array(x.string()),[]),includeCategories:x.optional(x.array(x.string()),[]),excludeBlocks:x.optional(x.array(x.string()),[]),excludeCategories:x.optional(x.array(x.string()),[]),doNotListBlocks:x.optional(x.array(x.string()),[]),doNotListCategories:x.optional(x.array(x.string()),[]),listBlocks:x.optional(x.array(x.string()),[]),listCategories:x.optional(x.array(x.string()),[]),excludeDeps:x.optional(x.array(x.string()),[]),allowSubdirectories:x.optional(x.boolean()),preview:x.optional(x.boolean()),rules:x.optional(Oo)}),hr=e=>{if(!pe.existsSync(Q.join(e,tt)))return p(null);let t=x.safeParse(wi,JSON.parse(pe.readFileSync(Q.join(e,tt)).toString()));return t.success?p(t.output):q(`There was an error reading your \`${tt}\` file!`)},Ue=(e,t)=>{let r=bt(t).unwrapOr(null),n=r?createPathsMatcher(r):null,o={"*":""};for(let[s,i]of Object.entries(e)){if(i.startsWith("./")){o[s]=Q.relative(t,Q.join(Q.resolve(t),i));continue}if(n===null)return q(`Cannot resolve ${$.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${$.bold("`./`")}.`);let a=$i(i,n,t);if(!a)return q(`Cannot resolve ${$.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${$.bold("`./`")}.`);o[s]=a;}return p(o)},$i=(e,t,r)=>{let n=t(e);return n.length>0?Q.relative(r,n[0]):void 0},Vr=(e,t,r)=>{let n;return t[e.category]!==void 0?n=Q.join(r,t[e.category]):n=Q.join(r,t["*"],e.category),n};var xt=async(e,t,{verbose:r}={})=>await I(e,t,{verbose:r,fetch:Wr,token:Ur(e.provider,e.url),userName:Gr(e.provider,e.url),machineId:Jr(e.provider,e.url)}),vr=async(e,{verbose:t}={})=>await J(e,{verbose:t,fetch:Wr,token:Ur(e.provider,e.url),userName:Gr(e.provider,e.url),machineId:Jr(e.provider,e.url)}),Ur=(e,t)=>{let r=new Pe;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)},Gr=(e,t)=>{let r=new Pe;return e.name==="http"?r.get(r.getHttpUsernameToken(new URL(t).origin)):r.get(e.name)},Jr=(e,t)=>{let r=new Pe;return e.name==="http"?r.get(r.getHttpMachineIdToken(new URL(t).origin)):r.get(e.name)},Kr=async(e,{noCache:t=false}={})=>{let r=H(e);if(r){let n=Ve();if(r.name!==F.name&&!t){let i=n.get(`${e}-state`);if(i)return p({...i,provider:r})}let o=r.parse(e,{fullyQualified:false}),s=await r.state(e,{token:Ur(r,o.url),userName:Gr(r,o.url),machineId:Jr(r,o.url),fetch:Wr});return r.name!==F.name&&!t&&n.set(`${e}-state`,s),p(s)}return q(`Only ${G.map((n,o)=>`${o===G.length-1?"and ":""}${$.bold(n.name)}`).join(", ")} registries are supported at this time!`)},rt=async(e,{noCache:t=false}={})=>{let r=[],o=(await Promise.all(e.map(async s=>{let i=await Kr(s,{noCache:t});if(i.isErr())return q({message:i.unwrapErr(),repo:s});let a=i.unwrap();r.push(a);}))).find(s=>s!==void 0);return o||p(r)},Uo=async(...e)=>{let t=new Map,n=(await Promise.all(e.map(async o=>{let s=await vr(o);if(s.isErr())return q({message:s.unwrapErr(),repo:o.url});let i=s.unwrap();for(let a of i.categories)for(let c of a.blocks)t.set(r(o.url,`${c.category}/${c.name}`),{...c,sourceRepo:o});}))).find(o=>o!==void 0);return n||p(t)},Ct=e=>{let t=new Map;for(let r$1 of e)for(let n of r$1.manifest.categories)for(let o of n.blocks)t.set(r(r$1.state.url,`${o.category}/${o.name}`),{...o,sourceRepo:r$1.state});return t},Rt=async(...e)=>{let t=[],n=(await Promise.all(e.map(async o=>{let s=await vr(o);if(s.isErr())return q({message:s.unwrapErr(),repo:o.url});let i=s.unwrap();t.push({state:o,manifest:i});}))).find(o=>o!==void 0);return n||p(t)};var ze=async(e,t,r$1,n=new Map)=>{let o=new Map;for(let s of e){let i,a=H(s);if(a){let{url:l,specifier:d}=a.parse(s,{fullyQualified:true});i=t.get(r(l,d));}else {if(r$1.length===0)return q($.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${$.bold(`github/ieedan/std/${s}`)}\`!`));for(let l of r$1){let{url:d,specifier:m}=l.provider.parse(r(l.url,s),{fullyQualified:true}),v=t.get(r(d,m));if(v!==void 0){i=v;break}}}if(!i)return q(`Invalid block! ${$.bold(s)} does not exist!`);let c=`${i.category}/${i.name}`;if(o.set(c,i),i.localDependencies&&i.localDependencies.length>0){let l=await ze(i.localDependencies.filter(d=>!o.has(d)&&!n.has(d)),t,r$1,o);if(l.isErr())return q(l.unwrapErr());for(let d of l.unwrap())o.set(`${d.category}/${d.name}`,d);}}return p(Pn(o,(s,i)=>i))},zt=(e,t,r)=>{let n=[],o=Ue(t.paths,r).match(s=>s,s=>program.error($.red(s)));for(let[s,i]of e){let a=Vr(i,o,r),c=Q.join(a,i.files[0]);i.subdirectory&&(c=Q.join(a,i.name)),pe.existsSync(c)&&n.push({specifier:`${i.category}/${i.name}`,path:c,block:i});}return n},jt=(e,t)=>{let r=[];for(let n of e){let o=n.files.filter(i=>kt(i)?t.includeTests:true),s=Promise.all(o.map(async i=>{let a=await xt(n.sourceRepo,Q.join(n.directory,i));return {name:i,content:a}}));r.push({block:n,files:s});}return r},ft=(e,t,r,n)=>{let o=Vr(t,r,n);return t.subdirectory?Q.join(o,t.name,e):Q.join(o,e)};var Go=e=>new Promise(t=>t(e));var qe=async({formatter:e,cwd:t})=>{let r={singleQuote:true};return e==="prettier"&&(r=await eo.resolveConfig(Q.join(t,".prettierrc"))),{prettierOptions:r}};var qt=(e,t)=>`Installed from ${e}${t?`
Update this file using \`${b} update ${t}\``:""}`;var Pt=(e,t,r)=>{if(!t.peerDependencies)return;let n=Tr(Q.join(r,"package.json")).match(i=>i,i=>{i.endsWith("doesn't exist")&&program.error(`Couldn't find your ${$.bold("package.json")}. Please create one.`),program.error($.red(i));}),o={...n.dependencies,...n.devDependencies},s=[];for(let[i,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let d=o[i];if(!d){s.push({name:i,expected:c,message:l,version:d,exists:false});continue}Fn.satisfies(cr(d),c)||s.push({name:i,expected:c,message:l,version:d,exists:true});}if(s.length>0){process.stdout.write(`${L}
${$.yellow("\u25B2")} ${Sn} Issues with ${$.bold(e.url)} peer dependencies
`);let i=s.map((a,c)=>{let l=s.length-1===c,d;a.exists?d=`${$.yellowBright("x unmet peer")} need ${$.bold(`${a.name}@`)}${$.greenBright.bold(a.expected)} >> found ${$.yellowBright.bold(a.version)}`:d=`${$.red("x missing peer")} need ${$.bold(`${a.name}@`)}${$.greenBright.bold(a.expected)}`;let m=`${L} ${l?jn:Ft}${Lt} ${d}`;return a.message?`${m}
${L} ${l?"":L} ${$.gray(a.message)}`:m}).join(`
`);process.stdout.write(`${i}
`);}};var Et=e=>{let t=kr.join(e,"app.config.ts");if(nt.existsSync(t)&&nt.statSync(t).isFile())return t;let r=nt.readdirSync(e);for(let n of r){let o=kr.join(e,n);if(nt.statSync(o).isDirectory()){let s=Et(o);if(s)return s}}};function Qt(e,t){let r=/providers:\s*\[\s*([^\]]*)\s*\]/s,n=e.match(r);if(n&&!t.some(o=>n[0].includes(o))){let o=n[1].trim(),s=o?`${o}${o.endsWith(",")?" ":", "}${t.join(", ")}`:t.join(", ");e=e.replace(n[0],`providers: [${s}]`);}return e}async function br(e){return await glob("**/project.json",{cwd:e})}var Yo=async e=>{let t=kr.join(e,"angular.json");if(nt.existsSync(t)&&nt.statSync(t).isFile()){let o=[],i=JSON.parse(nt.readFileSync(t,"utf8")).projects||{};for(let[a,c]of Object.entries(i))c.projectType==="application"&&o.push(c.sourceRoot);return o}let r=kr.join(e,"nx.json");if(nt.existsSync(r)&&nt.statSync(r).isFile()){let o=await br(e),s=[];for(let i of o){let a=JSON.parse(nt.readFileSync(i,"utf8"));a.projectType==="application"&&(a.targets?.build?.executor).includes("angular")&&s.push(kr.join(e,a.sourceRoot));}return s}let n=kr.join(e,"src");if(nt.existsSync(n)&&nt.statSync(n).isDirectory())return [n];throw new Error("Could not find src root")};var _i=x.object({expand:x.boolean(),maxUnchanged:x.number(),allow:x.boolean(),yes:x.boolean(),verbose:x.boolean(),cwd:x.string(),skipPreconditions:x.optional(x.boolean()),silent:x.optional(x.boolean())}),Hr=new Command("add").description("Add blocks to your project.").addArgument(new Argument("<blocks...>","Names of the blocks you want to add to your project. ex: (free-authentication/login-with-email-password)").argRequired()).option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged [number]","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-A, --allow",`Allow ${b} to download code from the provided repo.`,false).option("-y, --yes","Skip confirmation prompt.",false).option("--verbose","Include debug logs.",false).option("--cwd [path]","The current working directory.",process.cwd()).action(async(e,t)=>{let r=x.parse(_i,t);await fe(),await Yr(e,r),outro($.green("All done!"));}),Yr=async(e,t)=>{let r$1=C=>{t.verbose&&console.info(`${we} ${C}`);};r$1(`Attempting to add ${JSON.stringify(e)}`);let n=be({verbose:t.verbose?r$1:void 0}),o=Ce(t.cwd),s=o.isErr(),i;o.isErr()?program.error($.red(`There was an error loading your config. Please run \`${$.cyan.bold(`${b} init`)}\` to initialize your project.`)):i=o.unwrap();let a=i.repos,c=new Set,l=false;for(let C of e){let M=H(C);if(!M){l=true;continue}let{url:b}=M.parse(C,{fullyQualified:true});if(!(!i.repos.find(F=>F===b)&&!c.has(b))){if(!t.allow){let F=await confirm({message:`Allow ${Bt} to download and run code from ${$.cyan(b)}?`,initialValue:true});(isCancel(F)||!F)&&(cancel("Canceled!"),process.exit(0));}a.push(b);}c.add(b);}!l&&e.length>0&&(a=Array.from(c)),a.length===0&&program.error($.red(`There were no repos present in your config. Please run \`${$.bold(`${b} init`)}\` to initialize your project.`)),r$1(`Resolving ${$.cyan(a.join(", "))}`),!t.verbose&&!t.silent&&n.start(`Fetching blocks from ${$.cyan(a.join(", "))}`);let d=(await rt(a,{noCache:true})).match(C=>C,({repo:C,message:M})=>{n.stop(`Failed to get info for ${$.cyan(C)}`),program.error($.red(M));});r$1(`Resolved ${$.cyan(a.join(", "))}`),r$1(`Fetching blocks from ${$.cyan(a.join(", "))}`);let m=(await Rt(...d)).match(C=>C,({repo:C,message:M})=>{n.stop(`Failed fetching blocks from ${$.cyan(C)}`),program.error($.red(M));}),v=Ct(m);if(!t.verbose&&!t.silent&&n.stop(`Retrieved blocks from ${$.cyan(a.join(", "))}`),r$1(`Retrieved blocks from ${$.cyan(a.join(", "))}`),!t.skipPreconditions)for(let C of m)Pt(C.state,C.manifest,t.cwd);let u=zt(v,i,t.cwd).map(C=>C.specifier),g=e;r$1(`Installing blocks ${$.cyan(g.join(", "))}`);let h=(await ze(g,v