jsrepo 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import {h,g,f,j,z as z$1,c,w,m,o,p,x as x$1,y,a,v,u,b,l,B,A as A$1}from'./chunk-UBBLYFUD.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import fe from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import A from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import te from'pathe';import*as k from'valibot';import gi from'is-unicode-supported';import {stripVTControlCharacters}from'util';import {builtinModules}from'module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import En from'validate-npm-package-name';import wi from'os';import os from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import Ho from'boxen';import {diffLines,diffChars}from'diff';import Jo from'semver';import {cursor,erase}from'sisteransi';import Ri from'@anthropic-ai/sdk';import Ei from'ollama';import Ii from'openai';import Ci from'conf';import Ai from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as on from'css-dependency';import*as nn from'prettier';import*as an from'parse5';import ps from'oxc-parser';import {walk}from'estree-walker';import*as bn from'svelte/compiler';import*as Cn from'vue/compiler-sfc';import Xs from'node-machine-id';import oa from'ignore';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {CallToolRequestSchema,ListToolsRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ii from'tar';var Dt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.4.2"};var hi=gi(),de=(e,t)=>hi?e:t,So=de("\u25C6","*"),jo=de("\u25C6","*"),Po=de("\u25A0","x"),T=A.gray(de("\u2502","|")),Ht=A.gray(de("\u2500","-")),Eo=A.gray(de("\u2510","+")),Io=A.gray(de("\u2518","+")),Kt=A.gray(de("\u251C","+")),Oo=A.gray(de("\u252C","+"));A.gray(de("\u250C","T"));var Do=A.gray(de("\u2514","-")),ce=A.bgRgb(245,149,66).black(" WARN "),Ee=A.bgBlueBright.white(" INFO "),Yt=A.bgRedBright.white(" ERROR "),Xe=A.hex("#f7df1e")("jsrepo"),We=A.hex("#f7df1e").bold("jsrepo.com");function mr(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function To(e,t){let r=0;for(let o of e)r=r+t(o);return r}function No(e){let t=0;for(let r of e){let o=stripVTControlCharacters(r);o.length>t&&(t=o.length);}return t}function Qt(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-o)+e}function Fo(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-o)}var bi=/\n|\r\n/g;function q(e){return e.split(bi)}function z(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Qt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(wi.EOL)}var ki={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},$i={"install-as-dev-dependency":"-D"},xi={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Lo={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Bo={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Lr={bun:ki,npm:xi,pnpm:Lo,deno:$i,yarn:Bo,"yarn@berry":Bo,"pnpm@6":Lo};function Ve(){return new Ci({projectName:"jsrepo"})}var Br="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),o=this.#e.get(r,void 0);return t==="jsrepo"?o??process.env.JSREPO_TOKEN:o}set(t,r){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),i=t.slice(5);n||(n=[]),n.includes(i)||n.push(i),this.#e.set(Br,n);}let o=this.getKey(t);this.#e.set(o,r);}delete(t){if(t.startsWith("http")){let o=this.getHttpRegistriesWithTokens(),n=t.slice(5),i=o.indexOf(n);i!==-1&&(o=[...o.slice(0,i),...o.slice(i+1)]),this.#e.set(Br,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Br);return t||[]}};var Wr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await _o("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
3
- ${JSON.stringify(a,null," ")}`);let c=await Di({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:Mr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},"OpenAI o3-mini":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await _o("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting OpenAI o3-mini with:
4
- ${JSON.stringify(a,null," ")}`);let c=await Oi({model:"o3-mini",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("OpenAI o3-mini updated the file"),c?{content:Mr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},Phi4:{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{o||r.start("Asking Phi4");let s=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Phi4 with:
5
- ${JSON.stringify(s,null," ")}`);let a=await Ti({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Mr(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function Oi({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new Ii({apiKey:o}).chat.completions.create({model:r,max_completion_tokens:t,messages:[{role:"system",content:e.system},...n??[],{role:"user",content:e.message}]})).choices[0];return a.message.content===null?null:a.message.content}async function Di({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new Ri({apiKey:n}),s=[];if(t)for(let l of t)s.push({role:l.role,content:[{type:"text",text:l.content}]});s.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await i.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:s})).content[0];return c.type!=="text"?null:c.text}async function Ti({prompt:e,messages:t,model:r}){return (await Ei.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function _r({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o}){return {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:o?r??"":`
2
+ import {h,g,f,j,z as z$1,c,w,m,o,p,x as x$1,y,a,v,u,b,l,B,A as A$1}from'./chunk-UBBLYFUD.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import fe from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import A from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import oe from'pathe';import*as k from'valibot';import ui from'is-unicode-supported';import {stripVTControlCharacters}from'util';import {builtinModules}from'module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import Pn from'validate-npm-package-name';import vi from'os';import rs from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import Ho from'boxen';import {diffLines,diffChars}from'diff';import Jo from'semver';import {cursor,erase}from'sisteransi';import Ci from'@anthropic-ai/sdk';import Pi from'ollama';import Ei from'openai';import xi from'conf';import Ni from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as on from'css-dependency';import*as nn from'prettier';import*as an from'parse5';import ds from'oxc-parser';import {walk}from'estree-walker';import*as bn from'svelte/compiler';import*as Cn from'vue/compiler-sfc';import Xs from'node-machine-id';import oa from'ignore';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {CallToolRequestSchema,ListToolsRequestSchema}from'@modelcontextprotocol/sdk/types.js';import*as ni from'tar';var Dt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.4.3"};var gi=ui(),de=(e,t)=>gi?e:t,So=de("\u25C6","*"),jo=de("\u25C6","*"),Po=de("\u25A0","x"),T=A.gray(de("\u2502","|")),Ht=A.gray(de("\u2500","-")),Eo=A.gray(de("\u2510","+")),Io=A.gray(de("\u2518","+")),Kt=A.gray(de("\u251C","+")),Oo=A.gray(de("\u252C","+"));A.gray(de("\u250C","T"));var Do=A.gray(de("\u2514","-")),ce=A.bgRgb(245,149,66).black(" WARN "),Ee=A.bgBlueBright.white(" INFO "),Yt=A.bgRedBright.white(" ERROR "),Xe=A.hex("#f7df1e")("jsrepo"),We=A.hex("#f7df1e").bold("jsrepo.com");function mr(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function To(e,t){let r=0;for(let o of e)r=r+t(o);return r}function No(e){let t=0;for(let r of e){let o=stripVTControlCharacters(r);o.length>t&&(t=o.length);}return t}function Qt(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-o)+e}function Fo(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-o)}var wi=/\n|\r\n/g;function q(e){return e.split(wi)}function z(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Qt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(vi.EOL)}var bi={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},ki={"install-as-dev-dependency":"-D"},$i={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Lo={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Bo={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Lr={bun:bi,npm:$i,pnpm:Lo,deno:ki,yarn:Bo,"yarn@berry":Bo,"pnpm@6":Lo};function Ve(){return new xi({projectName:"jsrepo"})}var Br="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),o=this.#e.get(r,void 0);return t==="jsrepo"?o??process.env.JSREPO_TOKEN:o}set(t,r){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),i=t.slice(5);n||(n=[]),n.includes(i)||n.push(i),this.#e.set(Br,n);}let o=this.getKey(t);this.#e.set(o,r);}delete(t){if(t.startsWith("http")){let o=this.getHttpRegistriesWithTokens(),n=t.slice(5),i=o.indexOf(n);i!==-1&&(o=[...o.slice(0,i),...o.slice(i+1)]),this.#e.set(Br,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Br);return t||[]}};var Wr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await _o("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
3
+ ${JSON.stringify(a,null," ")}`);let c=await Oi({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:Mr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},"OpenAI o3-mini":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await _o("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting OpenAI o3-mini with:
4
+ ${JSON.stringify(a,null," ")}`);let c=await Ii({model:"o3-mini",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("OpenAI o3-mini updated the file"),c?{content:Mr(c),prompt:a.message}:{content:t.content,prompt:a.message}}},Phi4:{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{o||r.start("Asking Phi4");let s=_r({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Phi4 with:
5
+ ${JSON.stringify(s,null," ")}`);let a=await Di({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Mr(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function Ii({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new Ei({apiKey:o}).chat.completions.create({model:r,max_completion_tokens:t,messages:[{role:"system",content:e.system},...n??[],{role:"user",content:e.message}]})).choices[0];return a.message.content===null?null:a.message.content}async function Oi({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new Ci({apiKey:n}),s=[];if(t)for(let l of t)s.push({role:l.role,content:[{type:"text",text:l.content}]});s.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await i.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:s})).content[0];return c.type!=="text"?null:c.text}async function Di({prompt:e,messages:t,model:r}){return (await Pi.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function _r({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o}){return {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:o?r??"":`
6
6
  This is my current file ${e.path}:
7
7
  <code>
8
8
  ${e.content}
@@ -15,42 +15,42 @@ ${t.content}
15
15
  `}}function Mr(e){let t=e.trim();if(t.startsWith("```")&&(t=q(t).slice(1).join(`
16
16
  `).trim()),t.endsWith("```")){let r=q(t);t=r.slice(0,r.length-1).join(`
17
17
  `).trim();}return t}async function _o(e){let t=new pe,r=t.get(e);if(!r){let o=await password({message:`Paste your ${e} API key:`,validate(n){if(n.trim()==="")return "Please provide an API key"}});(isCancel(o)||!o)&&(cancel("Canceled!"),process.exit(0)),r=o;}return t.set(e,r),r}var Fe=Dt;function Mo(e){return /^\s+$/g.test(e)}function Tt(e){let t=e.length-1;for(;Mo(e[t])&&t>=0;){if(e[t]===`
18
- `)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function Wo({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:i=A.redBright,colorAdded:s=A.greenBright,colorCharsRemoved:a=A.bgRedBright,colorCharsAdded:c=A.bgGreenBright,prefix:l,onUnchanged:f,intro:g}){let m="",b=To(r,y=>y.count??0).toString().length+1,d=0;if(r.length===1&&!r[0].added&&!r[0].removed)return f({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:g});m+=g({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:g});let h=y=>A.gray(`${l?.()??""}${Qt(`${y+1+d} `,b)} `);for(let y=0;y<r.length;y++){let u=r[y],S=r[y-1]?.added||r[y-1]?.removed,C=r[y+1]?.added||r[y+1]?.removed;if(!u.added&&!u.removed){if(!o&&u.count!==void 0&&u.count>n){let x=d,R=q(Tt(u.value)),E=0;if(C&&(E+=n),S&&(E+=n),E>=R.length){m+=`${z(R,{prefix:h})}
19
- `,d+=R.length;continue}if(S&&(m+=`${z(R.slice(0,n),{prefix:h})}
20
- `),R.length>E){let K=R.length-E;m+=`${z(q(A.gray(`+ ${K} more unchanged (${A.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Qt(" ",b)} `})}
21
- `;}C&&(d=d+R.length-n,m+=`${z(R.slice(R.length-n),{prefix:h})}
22
- `),d=x+u.count;continue}m+=`${z(q(Tt(u.value)),{prefix:h})}
23
- `,d+=u.count??0;continue}let p=x=>x.added?s(Tt(x.value)):x.removed?i(Tt(x.value)):x.value,w=x=>x.added?c(Tt(x.value)):x.removed?a(Tt(x.value)):x.value;if(u.removed&&u.count===1&&r[y+1]?.added&&r[y+1]?.count===1){let R=diffChars(u.value,r[y+1].value).map(E=>w(E)).join("");m+=`${h(0)}${R}`,d+=1,y++;}else Mo(u.value)?(m+=`${z(q(w(u)),{prefix:x=>`${h(x)}${w({removed:true,value:" ",added:false})}`})}
24
- `,u.removed||(d+=u.count??0)):(m+=`${z(q(p(u)),{prefix:h})}
18
+ `)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function Wo({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:i=A.redBright,colorAdded:s=A.greenBright,colorCharsRemoved:a=A.bgRedBright,colorCharsAdded:c=A.bgGreenBright,prefix:l,onUnchanged:f,intro:h}){let m="",b=To(r,y=>y.count??0).toString().length+1,d=0;if(r.length===1&&!r[0].added&&!r[0].removed)return f({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:h});m+=h({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:h});let g=y=>A.gray(`${l?.()??""}${Qt(`${y+1+d} `,b)} `);for(let y=0;y<r.length;y++){let u=r[y],S=r[y-1]?.added||r[y-1]?.removed,C=r[y+1]?.added||r[y+1]?.removed;if(!u.added&&!u.removed){if(!o&&u.count!==void 0&&u.count>n){let x=d,R=q(Tt(u.value)),P=0;if(C&&(P+=n),S&&(P+=n),P>=R.length){m+=`${z(R,{prefix:g})}
19
+ `,d+=R.length;continue}if(S&&(m+=`${z(R.slice(0,n),{prefix:g})}
20
+ `),R.length>P){let K=R.length-P;m+=`${z(q(A.gray(`+ ${K} more unchanged (${A.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Qt(" ",b)} `})}
21
+ `;}C&&(d=d+R.length-n,m+=`${z(R.slice(R.length-n),{prefix:g})}
22
+ `),d=x+u.count;continue}m+=`${z(q(Tt(u.value)),{prefix:g})}
23
+ `,d+=u.count??0;continue}let p=x=>x.added?s(Tt(x.value)):x.removed?i(Tt(x.value)):x.value,w=x=>x.added?c(Tt(x.value)):x.removed?a(Tt(x.value)):x.value;if(u.removed&&u.count===1&&r[y+1]?.added&&r[y+1]?.count===1){let R=diffChars(u.value,r[y+1].value).map(P=>w(P)).join("");m+=`${g(0)}${R}`,d+=1,y++;}else Mo(u.value)?(m+=`${z(q(w(u)),{prefix:x=>`${g(x)}${w({removed:true,value:" ",added:false})}`})}
24
+ `,u.removed||(d+=u.count??0)):(m+=`${z(q(p(u)),{prefix:g})}
25
25
  `,u.removed||(d+=u.count??0));}return m.endsWith(`
26
26
  `)||(m=m+=`
27
- `),m}var Re=Ai.defaults({cachePath:te.join(import.meta.dirname,"cache")});var Vr="latest-version",Li=60*60*1e3;async function Vo({noCache:e=false}={}){try{let t=Ve(),r;if(!e){let i=t.get(Vr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Vr);}}let o=await Re("https://raw.githubusercontent.com/jsrepojs/jsrepo/refs/heads/main/packages/cli/package.json",{timeout:1e3});if(!o.ok)return b("Error getting version");let{version:n}=await o.json();return r=n,t.set(Vr,{expiration:Date.now()+Li,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var Bi=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,_i=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Ze(e){let t=Bi.exec(e)||_i.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Ur(e,t){let r=te.join(e,"package.json");if(fe.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Ur(o.slice(0,o.length-1).join("/"),t)}function Gr(e){if(!fe.existsSync(e))return b(`${e} doesn't exist`);let t=fe.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function gr(e){return e[0]==="^"?e.slice(1):e}function Go(e,t,{cwd:r}){let o=e,n=t,i=Gr(te.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=Ze(a).unwrap(),f=s.dependencies[c];if(l===void 0&&f){o.delete(a);continue}f&&Jo.satisfies(gr(f),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Ze(a).unwrap(),f=s.devDependencies[c];if(l===void 0&&f){n.delete(a);continue}f&&Jo.satisfies(gr(f),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function Ko(e,{loading:t}){for(let r of e){t.start(r.loadingMessage);try{await r.run();}catch(o){t.stop(`Error while ${r.loadingMessage}`),console.error(o);}t.stop(r.completedMessage);}}async function Yo({tasks:e,startMessage:t,stopMessage:r,loading:o}){o.start(t),await Promise.all([...e.map(n=>n.run({message:o.message}))]),o.stop(r);}function ve({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);}}}function ft(e){let t=Ho(e.join(`
27
+ `),m}var Re=Ni.defaults({cachePath:oe.join(import.meta.dirname,"cache")});var Vr="latest-version",Fi=60*60*1e3;async function Vo({noCache:e=false}={}){try{let t=Ve(),r;if(!e){let i=t.get(Vr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Vr);}}let o=await Re("https://raw.githubusercontent.com/jsrepojs/jsrepo/refs/heads/main/packages/cli/package.json",{timeout:1e3});if(!o.ok)return b("Error getting version");let{version:n}=await o.json();return r=n,t.set(Vr,{expiration:Date.now()+Fi,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var Li=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Bi=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Ze(e){let t=Li.exec(e)||Bi.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Ur(e,t){let r=oe.join(e,"package.json");if(fe.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Ur(o.slice(0,o.length-1).join("/"),t)}function Gr(e){if(!fe.existsSync(e))return b(`${e} doesn't exist`);let t=fe.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function gr(e){return e[0]==="^"?e.slice(1):e}function Go(e,t,{cwd:r}){let o=e,n=t,i=Gr(oe.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=Ze(a).unwrap(),f=s.dependencies[c];if(l===void 0&&f){o.delete(a);continue}f&&Jo.satisfies(gr(f),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Ze(a).unwrap(),f=s.devDependencies[c];if(l===void 0&&f){n.delete(a);continue}f&&Jo.satisfies(gr(f),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function Ko(e,{loading:t}){for(let r of e){t.start(r.loadingMessage);try{await r.run();}catch(o){t.stop(`Error while ${r.loadingMessage}`),console.error(o);}t.stop(r.completedMessage);}}async function Yo({tasks:e,startMessage:t,stopMessage:r,loading:o}){o.start(t),await Promise.all([...e.map(n=>n.run({message:o.message}))]),o.stop(r);}function ve({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);}}}function ft(e){let t=Ho(e.join(`
28
28
  `),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Kt),bottomLeft:stripVTControlCharacters(Kt),topRight:stripVTControlCharacters(Eo),top:stripVTControlCharacters(Ht),bottom:stripVTControlCharacters(Ht),bottomRight:stripVTControlCharacters(Io),left:stripVTControlCharacters(T),right:stripVTControlCharacters(T)}});return `${T}
29
29
  ${t}
30
- `}function Qo(e,t=3){let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`}async function Qi(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${A.redBright(t)} -> ${A.greenBright(r)}`,`${A.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${A.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${A.yellowBright("Star")} on GitHub for updates: https://github.com/jsrepojs/jsrepo`];return Ho(i.join(`
31
- `),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await Vo();e.isOk()&&Jo.lt(Fe.version,e.unwrap())&&console.info(await Qi(Fe.name,Fe.version,e.unwrap())),intro(`${A.bgHex("#f7df1e").black(` ${Fe.name} `)}${A.gray(` v${Fe.version} `)}`);}var zo="model-preference";async function Nt({incoming:e,current:t,config:r,options:o}){let n=Ve();process.stdout.write(`${T}
32
- `);let i=false,s=e.content,a=n.get(zo,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),f=Wo({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:g,to:m,prefix:b})=>`${b?.()??""}${A.cyan(g)} \u2192 ${A.gray(m)} ${A.gray("(unchanged)")}
33
- `,intro:({from:g,to:m,changes:b,prefix:d})=>{let h=b.filter(y=>y.added||y.removed).length;return `${d?.()??""}${A.cyan(g)} \u2192 ${A.gray(m)} (${h} change${h===1?"":"s"})
30
+ `}function Qo(e,t=3){let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`}async function Yi(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${A.redBright(t)} -> ${A.greenBright(r)}`,`${A.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${A.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${A.yellowBright("Star")} on GitHub for updates: https://github.com/jsrepojs/jsrepo`];return Ho(i.join(`
31
+ `),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await Vo();e.isOk()&&Jo.lt(Fe.version,e.unwrap())&&console.info(await Yi(Fe.name,Fe.version,e.unwrap())),intro(`${A.bgHex("#f7df1e").black(` ${Fe.name} `)}${A.gray(` v${Fe.version} `)}`);}var zo="model-preference";async function Nt({incoming:e,current:t,config:r,options:o}){let n=Ve();process.stdout.write(`${T}
32
+ `);let i=false,s=e.content,a=n.get(zo,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),f=Wo({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:h,to:m,prefix:b})=>`${b?.()??""}${A.cyan(h)} \u2192 ${A.gray(m)} ${A.gray("(unchanged)")}
33
+ `,intro:({from:h,to:m,changes:b,prefix:d})=>{let g=b.filter(y=>y.added||y.removed).length;return `${d?.()??""}${A.cyan(h)} \u2192 ${A.gray(m)} (${g} change${g===1?"":"s"})
34
34
  ${d?.()??""}
35
- `}});if(process.stdout.write(f),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let g=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?g.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Start over)")}`,value:"update"}):g.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728`,value:"update"});let m=await select({message:"Accept changes?",options:g});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m==="update"||m==="update-iterate"){m==="update"&&(c=[]);let b=await select({message:"Select a model",options:Object.keys(Wr).map(h=>({label:h,value:h})),initialValue:a});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),b!==a&&n.set(zo,b),a=b;let d=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(d)&&(cancel("Canceled!"),process.exit(0));try{let{content:h,prompt:y}=await Wr[a].updateFile({originalFile:t,newFile:{content:m==="update-iterate"?s:e.content,path:e.path},additionalInstructions:d!=="None"?d:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=h,c.push({role:"user",content:y}),c.push({role:"assistant",content:h});}catch(h){o.loading.stop(),log.error(A.red(`Error getting completions: ${h}`)),process.stdout.write(`${T}
35
+ `}});if(process.stdout.write(f),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let h=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?h.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Start over)")}`,value:"update"}):h.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728`,value:"update"});let m=await select({message:"Accept changes?",options:h});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m==="update"||m==="update-iterate"){m==="update"&&(c=[]);let b=await select({message:"Select a model",options:Object.keys(Wr).map(g=>({label:g,value:g})),initialValue:a});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),b!==a&&n.set(zo,b),a=b;let d=await text({message:"Additional instructions:",defaultValue:"None",validate:g=>{if(c.length!==0&&g.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(d)&&(cancel("Canceled!"),process.exit(0));try{let{content:g,prompt:y}=await Wr[a].updateFile({originalFile:t,newFile:{content:m==="update-iterate"?s:e.content,path:e.path},additionalInstructions:d!=="None"?d:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=g,c.push({role:"user",content:y}),c.push({role:"assistant",content:g});}catch(g){o.loading.stop(),log.error(A.red(`Error getting completions: ${g}`)),process.stdout.write(`${T}
36
36
  `);continue}s=await vr({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${T}
37
- `);continue}i=m==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function et(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Go(e,t,{cwd:n});if(a.size>0||c.size>0){let f=r;if(!r&&!o){let g=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),f=g;}if(f)return a.size>0&&await qr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await qr({pm:i,deps:Array.from(c),dev:true,cwd:n,ignoreWorkspace:s}),{installed:true,dependencies:a,devDependencies:c}}return {installed:false,dependencies:a,devDependencies:c}}function Xo(e){let t=A.dim(T),r=A.green(So),o=A.green(jo),n=A.red(Po);process.stdout.write(`${t}
37
+ `);continue}i=m==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function et(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Go(e,t,{cwd:n});if(a.size>0||c.size>0){let f=r;if(!r&&!o){let h=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),f=h;}if(f)return a.size>0&&await qr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await qr({pm:i,deps:Array.from(c),dev:true,cwd:n,ignoreWorkspace:s}),{installed:true,dependencies:a,devDependencies:c}}return {installed:false,dependencies:a,devDependencies:c}}function Xo(e){let t=A.dim(T),r=A.green(So),o=A.green(jo),n=A.red(Po);process.stdout.write(`${t}
38
38
  `),process.stdout.write(`${r} ${e}
39
39
  `);let i="",s="",a=(l=false)=>{if(!s)return;let f=process.stdout.columns,m=s.split(`
40
40
  `).reduce((b,d)=>b+Math.ceil(d.length/f),0)+(l?1:0);process.stdout.write(cursor.up(m)),process.stdout.write(erase.down());},c=(l=0)=>{let f=i.split(`
41
- `).slice(-l);s="";for(let g of f)s+=`${t} ${g}
41
+ `).slice(-l);s="";for(let h of f)s+=`${t} ${h}
42
42
  `;process.stdout.write(A.dim(s));};return {set text(l){a(),i+=l;let f=Math.ceil(process.stdout.rows/2);c(f);},fail(l){a(true),process.stdout.write(`${n} ${l}
43
43
  `),c();},success(l){a(true),process.stdout.write(`${o} ${l}
44
44
  `);}}}async function qr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Lr[e]["install-as-dev-dependency"]);let s=Lr[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(A.red(`Could not resolve add command for '${e}'.`));let c=Xo(`Installing dependencies with ${e}...`);try{let l=x(a.command,[...a.args],{nodeOptions:{cwd:o}});for await(let f of l)c.text=`${f}
45
- `;c.success(`Installed ${A.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var ts=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function en({template:e,config:t,destPath:r,cwd:o}){let n=te.join(r,"../");return e.replace(ts,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=te.relative(n,te.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return te.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=te.relative(n,te.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return te.join(t.paths[s],a)})}async function Zt({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=ut.find(f=>f.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
45
+ `;c.success(`Installed ${A.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var es=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function en({template:e,config:t,destPath:r,cwd:o}){let n=oe.join(r,"../");return e.replace(es,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=oe.relative(n,oe.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return oe.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=oe.relative(n,oe.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return oe.join(t.paths[s],a)})}async function Zt({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=ut.find(f=>f.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
46
46
 
47
- ${l}`),a$1?.(`Formatting ${A.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(f){return b(`Error formatting ${A.bold(e.destPath)} ${f}`)}}for(let[f,g]of Object.entries(r)){let m=en({template:g,config:t,destPath:e.destPath,cwd:s}),b=new RegExp(`(['"])${os(f)}\\1`,"g");l=l.replaceAll(b,`$1${m}$1`);}return a(l)}async function vr({file:e,formatter:t,prettierOptions:r,biomeOptions:o}){let n=ut.find(s=>s.matches(e.destPath)),i=e.content;if(n)try{i=await n.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r,biomeOptions:o});}catch{return i}return i}function rn(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=te.dirname(e),o=fe.readdirSync(r),n=te.parse(e);for(let i of o)if(l(i,t)&&te.parse(i).name===n.name)return te.join(r,i)}function At(e){let t;try{if(t=getTsconfig(e,"tsconfig.json"),!t&&(t=getTsconfig(e,"jsconfig.json"),!t))return a(null)}catch(r){return b(`Error while trying to get ${A.bold("tsconfig.json")}: ${r}`)}return a(t)}var sn={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=on.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=De({moduleSpecifiers:c.map(f=>f.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(f=>Oe(f)).join(`
47
+ ${l}`),a$1?.(`Formatting ${A.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(f){return b(`Error formatting ${A.bold(e.destPath)} ${f}`)}}for(let[f,h]of Object.entries(r)){let m=en({template:h,config:t,destPath:e.destPath,cwd:s}),b=new RegExp(`(['"])${rs(f)}\\1`,"g");l=l.replaceAll(b,`$1${m}$1`);}return a(l)}async function vr({file:e,formatter:t,prettierOptions:r,biomeOptions:o}){let n=ut.find(s=>s.matches(e.destPath)),i=e.content;if(n)try{i=await n.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r,biomeOptions:o});}catch{return i}return i}function rn(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=oe.dirname(e),o=fe.readdirSync(r),n=oe.parse(e);for(let i of o)if(l(i,t)&&oe.parse(i).name===n.name)return oe.join(r,i)}function At(e){let t;try{if(t=getTsconfig(e,"tsconfig.json"),!t&&(t=getTsconfig(e,"jsconfig.json"),!t))return a(null)}catch(r){return b(`Error while trying to get ${A.bold("tsconfig.json")}: ${r}`)}return a(t)}var sn={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=on.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=De({moduleSpecifiers:c.map(f=>f.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(f=>Oe(f)).join(`
48
48
  `)):a(l.unwrap())},comment:e=>`/*
49
49
  ${z(q(e),{prefix:()=>" "})}
50
- */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await nn.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}};var ln={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=an.parse(s),c=[],l=(g,m)=>{if(g&&(m(g),g.childNodes&&g.childNodes.length>0))for(let b of g.childNodes)l(b,m);};for(let g of a$1.childNodes)l(g,m=>{if(m.tagName==="script")for(let b of m.attrs)b.name==="src"&&c.push(b.value);if(m.tagName==="link"&&m.attrs.find(b=>b.name==="rel"&&b.value==="stylesheet"))for(let b of m.attrs)b.name==="href"&&!b.value.startsWith("http")&&c.push(b.value);});let f=De({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(g=>Oe(g)).join(`
50
+ */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await nn.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}};var ln={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=an.parse(s),c=[],l=(h,m)=>{if(h&&(m(h),h.childNodes&&h.childNodes.length>0))for(let b of h.childNodes)l(b,m);};for(let h of a$1.childNodes)l(h,m=>{if(m.tagName==="script")for(let b of m.attrs)b.name==="src"&&c.push(b.value);if(m.tagName==="link"&&m.attrs.find(b=>b.name==="rel"&&b.value==="stylesheet"))for(let b of m.attrs)b.name==="href"&&!b.value.startsWith("http")&&c.push(b.value);});let f=De({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(h=>Oe(h)).join(`
51
51
  `)):a(f.unwrap())},comment:e=>`<!--
52
52
  ${z(q(e),{prefix:()=>" "})}
53
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"html",...r}):e};function br(e,t){let r=ps.parseSync(e,t),o=[];for(let n of r.module.staticImports)o.push(n.moduleRequest.value);for(let n of r.module.dynamicImports){let i=t.slice(n.moduleRequest.start+1,n.moduleRequest.end-1);o.push(i);}for(let n of r.module.staticExports)for(let i of n.entries)i.moduleRequest&&o.push(i.moduleRequest.value);return o}var pn={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=br(e,s),c=De({moduleSpecifiers:a$1,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return c.isErr()?b(c.unwrapErr().map(l=>Oe(l)).join(`
53
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"html",...r}):e};function br(e,t){let r=ds.parseSync(e,t),o=[];for(let n of r.module.staticImports)o.push(n.moduleRequest.value);for(let n of r.module.dynamicImports){let i=t.slice(n.moduleRequest.start+1,n.moduleRequest.end-1);o.push(i);}for(let n of r.module.staticExports)for(let i of n.entries)i.moduleRequest&&o.push(i.moduleRequest.value);return o}var pn={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=br(e,s),c=De({moduleSpecifiers:a$1,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return c.isErr()?b(c.unwrapErr().map(l=>Oe(l)).join(`
54
54
  `)):a(c.unwrap())},comment:e=>`/*
55
55
  ${z(q(e),{prefix:()=>" "})}
56
56
  */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await nn.format(e,{filepath:r,...o});let i=await Biome.create({distribution:Distribution.NODE});return n&&i.applyConfiguration(n),i.formatContent(e,{filePath:r}).content}};var mn=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await nn.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration({...o,json:{parser:{allowComments:true}}}),i.formatContent(e,{filePath:n}).content},kr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:mn},un={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
@@ -58,7 +58,7 @@ ${z(q(e),{prefix:()=>" "})}
58
58
  */`,format:mn};var yn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=on.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=De({moduleSpecifiers:c.map(f=>f.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(f=>Oe(f)).join(`
59
59
  `)):a(l.unwrap())},comment:e=>`/*
60
60
  ${z(q(e),{prefix:()=>" "})}
61
- */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"scss",...r}):e};var kn={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=bn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=g=>{(g.type==="ImportDeclaration"||g.type==="ExportAllDeclaration"||g.type==="ExportNamedDeclaration")&&typeof g.source?.value=="string"&&c.push(g.source.value),g.type==="ImportExpression"&&g.source.type==="Literal"&&typeof g.source.value=="string"&&c.push(g.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let f=De({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(g=>Oe(g)).join(`
61
+ */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"scss",...r}):e};var kn={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=bn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=h=>{(h.type==="ImportDeclaration"||h.type==="ExportAllDeclaration"||h.type==="ExportNamedDeclaration")&&typeof h.source?.value=="string"&&c.push(h.source.value),h.type==="ImportExpression"&&h.source.type==="Literal"&&typeof h.source.value=="string"&&c.push(h.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let f=De({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(h=>Oe(h)).join(`
62
62
  `)):a(f.unwrap())},comment:e=>`<!--
63
63
  ${z(q(e),{prefix:()=>" "})}
64
64
  -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await nn.format(e,{filepath:r,...o}):e};var $n={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
@@ -66,16 +66,16 @@ ${z(q(e),{prefix:()=>" "})}
66
66
  -->`,format:async e=>e};var Rn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=fe.readFileSync(e).toString(),a$1=Cn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let f=br("noop.ts",a$1.descriptor.script.content);c.push(...f);}if(a$1.descriptor.scriptSetup?.content){let f=br("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...f);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=De({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(f=>Oe(f)).join(`
67
67
  `)):a(l.unwrap())},comment:e=>`<!--
68
68
  ${z(q(e),{prefix:()=>" "})}
69
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"vue",...r}):e};var jn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>z(q(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"yaml",...r}):e};function Oe(e){return `${z(q(e),{prefix:t=>t===0?`${T} ${Yt} `:`${T} `})}`}function De({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,f={};for(let b of e){if(builtinModules.includes(b)||b.startsWith("node:"))continue;if(b.startsWith(".")){let y=In(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(y.isErr()){a$1.push(y.unwrapErr());continue}let u=y.unwrap();u&&(l.add(u.dependency),f[b]=u.template);continue}let d=ws(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(!d.isErr()){let y=d.unwrap();if(y){l.add(y.dependency),f[b]=y.template;continue}}let h=Ze(b);if(!h.isErr()){let y=h.unwrap();if(En(y.name).validForNewPackages){c.add(b);continue}}console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:g,dependencies:m}=$s(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:m,devDependencies:g,local:Array.from(l),imports:f})}function In(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:i,dirs:s,cwd:a$1}){if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=t?te.join(o,"../"):te.join(r,"../"),l=te.join(te.join(r,"../"),e),f=te.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(f))return a(Pn(l.slice(f.length),n));let g=te.resolve(l),m=null;for(let b of s){let d=te.resolve(te.join(a$1,b));g.startsWith(d)&&(m===null||m.length<d.length)&&(m=d);}return m!==null?a(Pn(g.slice(m.length+1),n)):b(`${r}:
70
- ${i||e} references code not contained in ${A.bold(s.join(", "))} and cannot be resolved.`)}function Pn(e,t=true){let[r,o,...n]=e.split("/");o===void 0&&(o="index");let i=o;t&&i.includes(".")&&(i=i.slice(0,i.length-te.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=te.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function ws(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=At(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let f of l){let g=ks(f);if(!g)continue;let m=te.relative(te.resolve(te.join(r,"../")),g.prettyPath),b$1=bs(g.prettyPath,g.path,[".js",".ts"]),d=In(m,t,{filePath:r,containingDir:i,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:g.type==="file"});if(d.isErr())return b(d.unwrapErr());if(d.unwrap())return a(d.unwrap());break}}return a(void 0)}function bs(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=te.parse(e),n=te.parse(t),i=te.join(o.dir,o.name),s=te.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function ks(e){if(fe.existsSync(e))return {path:e,prettyPath:e,type:fe.statSync(e).isDirectory()?"directory":"file"};let t=te.join(e,"../");if(!fe.existsSync(t))return;let r=te.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(fe.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=fe.readdirSync(t);for(let n of o){let i=te.parse(n);if(i.name===r.base){let s=te.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:fe.statSync(s).isDirectory()?"directory":"file"}}}}function $s(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Ur(te.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(fe.readFileSync(n,"utf-8"));for(let l of e){let f=Ze(l);if(f.isErr()){console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let g=f.unwrap();if(!En(g.name).validForNewPackages){console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(g.name))continue;let m;if(c!==void 0&&(m=c[g.name]),m!==void 0){i.add(`${g.name}@${m}`);continue}if(a!==void 0&&(m=a[g.name]),m!==void 0){s.add(`${g.name}@${m}`);continue}i.add(g.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ut=[sn,ln,kr,un,yn,kn,$n,pn,Rn,jn];var Dn=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"]),Tn=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),Cs=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),Nn={"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 ${A.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 o of e.localDependencies){let[n,i]=o.split("/"),s=t.categories.find(c=>c.name.trim()===n.trim()),a=`${A.bold(`${e.category}/${e.name}`)} depends on local dependency ${A.bold(o)} which doesn't exist`;if(!s){r.push(a);continue}s.blocks.find(c=>c.name===i)===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 o of e.localDependencies){let[n,i]=o.split("/");if(i!=="index")continue;let s=t.categories.find(c=>c.name===n);!s||!s.blocks.find(c=>c.name===i)||r.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(`${n}/${i}`)}`);}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=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${A.bold(`${e.category}/${e.name}`)} has too many local dependencies (${A.bold(e.localDependencies.length)}) limit (${A.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=xr(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${A.bold(o)}: ${A.bold(n.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}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(xr(r,n,t.categories))return;return [`${A.bold(r)} is unused and will be ${A.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(o=>Ze(o).unwrap().name).filter(o=>Dn.has(o));if(r.length>0)for(let o of r)t.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(o)} 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 o of e.configFiles)fe.existsSync(te.join(t,o.path))||r.push(`The ${A.bold(o.name)} config file doesn't exist at ${A.bold(te.join(t,o.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 o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>Ze(n).unwrap().name).filter(n=>Dn.has(n));if(o.length>0)for(let n of o)t.push(`${A.bold(r.name)} depends on ${A.bold(n)} 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 o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${A.bold(o)}`);return t.length>0?t:void 0}}}},An=k.record(Cs,k.union([Tn,k.tupleWithRest([Tn,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),er={"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"};function Cr(e,t,r,o=er){let n=[],i=[];for(let[s,a]of Object.entries(Nn)){if(a.scope==="block")continue;let c=o[s],l,f=[];if(Array.isArray(c)?(l=c[0],f.push(...c.slice(1))):l=c,l==="off")continue;let g=a.check({manifest:e,options:f,cwd:r,config:t});if(g){if(l==="error"){i.push(...g.map(m=>`${T} ${Yt} ${A.red(m)} ${A.gray(s)}`));continue}n.push(...g.map(m=>`${T} ${ce} ${m} ${A.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(Nn)){if(l.scope==="global")continue;let f=o[c],g,m=[];if(Array.isArray(f)?(g=f[0],m.push(...f.slice(1))):g=f,g==="off")continue;let b=l.check(a,{manifest:e,options:m,cwd:r,config:t});if(b){if(g==="error"){i.push(...b.map(d=>`${T} ${Yt} ${A.red(d)} ${A.gray(c)}`));continue}n.push(...b.map(d=>`${T} ${ce} ${d} ${A.gray(c)}`));}}return {warnings:n,errors:i}}function xr(e,t,r,o=[]){let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;if(o.includes(i))return;let[s,a]=i.split("/"),c=r.find(f=>f.name===s)?.blocks.find(f=>f.name===a);if(!c)continue;let l=xr(e,c,r,n);if(l)return [...l,e]}}function Fn(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(xr(e,o,t))return true}return false}var Mn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Wn=[".mdx",".md"];function ct(e){return l(e,Mn)!==void 0}function Rr(e){return l(e,Wn)!==void 0}function Sr(e,{cwd:t,ignore:r,config:o}){let n;try{n=fe.readdirSync(e);}catch{program.error(A.red(`Couldn't read the ${A.bold(e)} directory.`));}let i=[];for(let s of n){let a=te.join(e,s);if(fe.statSync(a).isFile())continue;let c=`${te.relative(t,a)}/`;if(r.ignores(c))continue;let l=te.basename(s);if(!Ss(l,o))continue;let f=Rs(l,o),g={name:l,blocks:[]},m=fe.readdirSync(a);for(let b of m){let d=te.join(a,b),h=te.relative(t,d);if(!r.ignores(h))if(fe.statSync(d).isFile()){if(ct(b))continue;if(Rr(b)){o.includeDocs||console.warn(`${T} ${ce} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`);continue}let y=js(b),u=Ln(y,o);if(!Bn(y,o))continue;let S=ut.find(J=>J.matches(b));if(!S){console.warn(`${T} ${ce} Skipped \`${A.bold(d)}\` \`*${A.bold(te.parse(b).ext)}\` files are not currently supported!`);continue}let C=m.find(J=>Mn.find(X=>J===`${y}${X}`)),p=m.find(J=>Wn.find(X=>J===`${y}${X}`)),{dependencies:w,devDependencies:x,local:R,imports:E}=S.resolveDependencies({filePath:d,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(J=>J,J=>{program.error(A.red(J));}),K={name:y,directory:te.relative(t,a),category:l,tests:C!==void 0,docs:p!==void 0,subdirectory:false,list:f?u:false,files:[b],localDependencies:R,_imports_:E,dependencies:w,devDependencies:x};C!==void 0&&K.files.push(C),p!==void 0&&K.files.push(p),g.blocks.push(K);}else {let y=b,u=Ln(y,o);if(!Bn(y,o))continue;let S=new Set,C=new Set,p=new Set,w={},x=false,R=false,E=[],K=(X,$)=>{for(let N of $){let v=te.join(X,N),W=v.slice(d.length+1);if(ct(N)){x=true,E.push(W);continue}if(Rr(N)){o.includeDocs||console.warn(`${T} ${ce} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`),R=true,E.push(W);continue}if(fe.statSync(v).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${ce} Skipped \`${A.bold(te.join(d,N))}\` subdirectories are not allowed! Allow them with ${A.bold("--allow-subdirectories")}!`);continue}let G=fe.readdirSync(v);K(v,G);continue}let j=ut.find(G=>G.matches(N));if(!j){console.warn(`${T} ${ce} Skipped \`${v}\` \`*${A.bold(te.parse(N).ext)}\` files are not currently supported!`);continue}let{local:U,dependencies:oe,devDependencies:ye,imports:nt}=j.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:d,filePath:v,cwd:t}).match(G=>G,G=>{program.error(A.red(G));});for(let G of U)G!==`${l}/${y}`&&S.add(G);for(let G of oe)C.add(G);for(let G of ye)p.add(G);for(let[G,Z]of Object.entries(nt))w[G]=Z;E.push(W);}};K(d,fe.readdirSync(d));let J={name:y,directory:te.relative(t,d),category:l,tests:x,docs:R,subdirectory:true,list:f?u:false,files:E,localDependencies:Array.from(S.keys()),dependencies:Array.from(C.keys()),devDependencies:Array.from(p.keys()),_imports_:w};g.blocks.push(J);}}i.push(g);}return i}function jr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ut.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:te.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(A.red(c));});a.length>0&&program.error(A.red(`${A.bold(o.name)} ${A.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:i,devDependencies:s});}return r}function Ln(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function Bn(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function Rs(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function Ss(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function js(e){return te.parse(te.basename(e)).name}function Pr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!Fn(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var Or=[".git","node_modules",".DS_Store"],yt="jsrepo.json",vt="jsrepo-build-config.json",Hr=k.union([k.literal("prettier"),k.literal("biome")]),Es=k.objectWithRest({"*":k.string()},k.string()),Kr=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),includeDocs:k.optional(k.boolean(),false),paths:Es,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(Hr)});function be(e){if(!fe.existsSync(te.join(e,yt)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse(Kr,JSON.parse(fe.readFileSync(te.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}var Is=k.object({$schema:k.string(),name:k.optional(k.string()),version:k.optional(k.string()),readme:k.optional(k.string(),"README.md"),access:k.optional(j),meta:k.optional(f),defaultPaths:k.optional(k.record(k.string(),k.string())),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string()),[]),includeCategories:k.optional(k.array(k.string()),[]),excludeBlocks:k.optional(k.array(k.string()),[]),excludeCategories:k.optional(k.array(k.string()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean(),false),rules:k.optional(An)});function Ft(e){if(!fe.existsSync(te.join(e,vt)))return a(null);let t=k.safeParse(Is,JSON.parse(fe.readFileSync(te.join(e,vt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${vt}\` file!`)}function Ue(e,t){let r=At(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=te.relative(t,te.join(te.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${A.bold("`./`")}.`);let a=Os(s,o,t);if(!a)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} 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 ${A.bold("`./`")}.`);n[i]=a;}return a(n)}function Os(e,t,r){let o=t(e);return o.length>0?te.relative(r,o[0]):void 0}function rr(e,t,r){let o;return t[e.category]!==void 0?o=te.join(r,t[e.category]):o=te.join(r,t["*"],e.category),o}async function Ge(e,t,{verbose:r}={}){return await A$1(e,t,{verbose:r,fetch:Re,token:Yr(e.provider,e.url)})}async function Lt(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Re,token:Yr(e.provider,e.url)})}function Yr(e,t){let r=new pe;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function lt(e,{noCache:t=false}={}){let r=z$1(e);if(r){let o=Ve();if(r.name!==u.name&&!t)if(t)o.delete(`${e}-state`);else {let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=r.parse(e,{fullyQualified:false}),i=await r.state(e,{token:Yr(r,n.url),fetch:Re});return r.name!==u.name&&!t&&o.set(`${e}-state`,i),a(i)}return b(`Only ${y.map((o,n)=>`${n===y.length-1?"and ":""}${A.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function qe(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await lt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function bt(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();for(let c$1 of a.categories)for(let l of c$1.blocks)r.set(c(i.url,`${l.category}/${l.name}`),{...l,sourceRepo:i});}))).find(i=>i!==void 0);return n||a(r)}function Bt(e){let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t}async function _t(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();r.push({state:i,manifest:a});}))).find(i=>i!==void 0);return n||a(r)}async function $t(e,t,r,o=new Map){let n=new Map;for(let i of e){let s,a=z$1(i);if(a){let{url:l,specifier:f}=a.parse(i,{fullyQualified:true});s=t.get(c(l,f));}else {if(r.length===0)return b(A.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${A.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:f,specifier:g}=l.provider.parse(c(l.url,i),{fullyQualified:true}),m=t.get(c(f,g));if(m!==void 0){s=m;break}}}if(!s)return b(`Invalid block! ${A.bold(i)} does not exist!`);let c$1=`${s.category}/${s.name}`;if(n.set(c$1,s),s.localDependencies&&s.localDependencies.length>0){let l=await $t(s.localDependencies.filter(f=>!n.has(f)&&!o.has(f)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let f of l.unwrap())n.set(`${f.category}/${f.name}`,f);}}return a(mr(n,(i,s)=>s))}function xt(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(A.red(i)));for(let[i,s]of e){let a=rr(s,n,r),c=te.join(a,s.files[0]);s.subdirectory&&(c=te.join(a,s.name)),fe.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function Mt(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>!(ct(s)&&!t.includeTests||Rr(s)&&!t.includeDocs)),i=Promise.all(n.map(async s=>{let a=await Ge(o.sourceRepo,te.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function nr(e,t,r,o){let n=rr(t,r,o);return t.subdirectory?te.join(n,t.name,e):te.join(n,e)}function ir(e){if(e===void 0)return;let t={};for(let r of e.split(",")){let[o,n]=r.split("=");if(o===void 0||n===void 0)throw new InvalidArgumentError("Expected map to be provided in the following format: `--option key=value,key=value`");t[o]=n;}return t}function Vn(e){return new Promise(t=>t(e))}async function Ct({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await nn.resolveConfig(te.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=te.join(t,"biome.json");fe.existsSync(n)&&(o=JSON.parse(fe.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function sr(e){return `Installed from ${e}`}function Wt(e,t,r){if(!t.peerDependencies)return;let o=Gr(te.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${A.bold("package.json")}. Please create one.`),program.error(A.red(s));}),n={...o.dependencies,...o.devDependencies},i=[];for(let[s,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let f=n[s];if(!f){i.push({name:s,expected:c,message:l,version:f,exists:false});continue}Jo.satisfies(gr(f),c)||i.push({name:s,expected:c,message:l,version:f,exists:true});}if(i.length>0){process.stdout.write(`${T}
69
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"vue",...r}):e};var jn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>z(q(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"yaml",...r}):e};function Oe(e){return `${z(q(e),{prefix:t=>t===0?`${T} ${Yt} `:`${T} `})}`}function De({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,f={};for(let b of e){if(builtinModules.includes(b)||b.startsWith("node:"))continue;if(b.startsWith(".")){let y=En(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(y.isErr()){a$1.push(y.unwrapErr());continue}let u=y.unwrap();u&&(l.add(u.dependency),f[b]=u.template);continue}let d=ws(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(!d.isErr()){let y=d.unwrap();if(y){l.add(y.dependency),f[b]=y.template;continue}}let g=Ze(b);if(!g.isErr()){let y=g.unwrap();if(Pn(y.name).validForNewPackages){c.add(b);continue}}console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:h,dependencies:m}=$s(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:m,devDependencies:h,local:Array.from(l),imports:f})}function En(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:i,dirs:s,cwd:a$1}){if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=oe.join(oe.join(r,"../"),e);if(o&&c.startsWith(o))return a(void 0);let l=oe.resolve(c),f=null;for(let h of s){let m=oe.resolve(oe.join(a$1,h));l.startsWith(m)&&(f===null||f.length<m.length)&&(f=m);}return f!==null?a(vs(l.slice(f.length+1),n)):b(`${r}:
70
+ ${i||e} references code not contained in ${A.bold(s.join(", "))} and cannot be resolved.`)}function vs(e,t=true){let[r,o,...n]=e.split("/");o===void 0&&(o="index");let i=o;t&&i.includes(".")&&(i=i.slice(0,i.length-oe.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=oe.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function ws(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=At(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let f of l){let h=ks(f);if(!h)continue;let m=oe.relative(oe.resolve(oe.join(r,"../")),h.prettyPath),b$1=bs(h.prettyPath,h.path,[".js",".ts"]),d=En(m,t,{filePath:r,containingDir:i,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:h.type==="file"});if(d.isErr())return b(d.unwrapErr());if(d.unwrap())return a(d.unwrap());break}}return a(void 0)}function bs(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=oe.parse(e),n=oe.parse(t),i=oe.join(o.dir,o.name),s=oe.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function ks(e){if(fe.existsSync(e))return {path:e,prettyPath:e,type:fe.statSync(e).isDirectory()?"directory":"file"};let t=oe.join(e,"../");if(!fe.existsSync(t))return;let r=oe.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(fe.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=fe.readdirSync(t);for(let n of o){let i=oe.parse(n);if(i.name===r.base){let s=oe.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:fe.statSync(s).isDirectory()?"directory":"file"}}}}function $s(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Ur(oe.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(fe.readFileSync(n,"utf-8"));for(let l of e){let f=Ze(l);if(f.isErr()){console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let h=f.unwrap();if(!Pn(h.name).validForNewPackages){console.warn(`${T} ${ce} Skipped adding import \`${A.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(h.name))continue;let m;if(c!==void 0&&(m=c[h.name]),m!==void 0){i.add(`${h.name}@${m}`);continue}if(a!==void 0&&(m=a[h.name]),m!==void 0){s.add(`${h.name}@${m}`);continue}i.add(h.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ut=[sn,ln,kr,un,yn,kn,$n,pn,Rn,jn];var On=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"]),Dn=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),Cs=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),Tn={"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 ${A.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 o of e.localDependencies){let[n,i]=o.split("/"),s=t.categories.find(c=>c.name.trim()===n.trim()),a=`${A.bold(`${e.category}/${e.name}`)} depends on local dependency ${A.bold(o)} which doesn't exist`;if(!s){r.push(a);continue}s.blocks.find(c=>c.name===i)===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 o of e.localDependencies){let[n,i]=o.split("/");if(i!=="index")continue;let s=t.categories.find(c=>c.name===n);!s||!s.blocks.find(c=>c.name===i)||r.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(`${n}/${i}`)}`);}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=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${A.bold(`${e.category}/${e.name}`)} has too many local dependencies (${A.bold(e.localDependencies.length)}) limit (${A.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=xr(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${A.bold(o)}: ${A.bold(n.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}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(xr(r,n,t.categories))return;return [`${A.bold(r)} is unused and will be ${A.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(o=>Ze(o).unwrap().name).filter(o=>On.has(o));if(r.length>0)for(let o of r)t.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(o)} 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 o of e.configFiles)fe.existsSync(oe.join(t,o.path))||r.push(`The ${A.bold(o.name)} config file doesn't exist at ${A.bold(oe.join(t,o.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 o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>Ze(n).unwrap().name).filter(n=>On.has(n));if(o.length>0)for(let n of o)t.push(`${A.bold(r.name)} depends on ${A.bold(n)} 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 o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${A.bold(o)}`);return t.length>0?t:void 0}}}},Nn=k.record(Cs,k.union([Dn,k.tupleWithRest([Dn,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),er={"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"};function Cr(e,t,r,o=er){let n=[],i=[];for(let[s,a]of Object.entries(Tn)){if(a.scope==="block")continue;let c=o[s],l,f=[];if(Array.isArray(c)?(l=c[0],f.push(...c.slice(1))):l=c,l==="off")continue;let h=a.check({manifest:e,options:f,cwd:r,config:t});if(h){if(l==="error"){i.push(...h.map(m=>`${T} ${Yt} ${A.red(m)} ${A.gray(s)}`));continue}n.push(...h.map(m=>`${T} ${ce} ${m} ${A.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(Tn)){if(l.scope==="global")continue;let f=o[c],h,m=[];if(Array.isArray(f)?(h=f[0],m.push(...f.slice(1))):h=f,h==="off")continue;let b=l.check(a,{manifest:e,options:m,cwd:r,config:t});if(b){if(h==="error"){i.push(...b.map(d=>`${T} ${Yt} ${A.red(d)} ${A.gray(c)}`));continue}n.push(...b.map(d=>`${T} ${ce} ${d} ${A.gray(c)}`));}}return {warnings:n,errors:i}}function xr(e,t,r,o=[]){let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;if(o.includes(i))return;let[s,a]=i.split("/"),c=r.find(f=>f.name===s)?.blocks.find(f=>f.name===a);if(!c)continue;let l=xr(e,c,r,n);if(l)return [...l,e]}}function An(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(xr(e,o,t))return true}return false}var _n=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Mn=[".mdx",".md"];function ct(e){return l(e,_n)!==void 0}function Rr(e){return l(e,Mn)!==void 0}function Sr(e,{cwd:t,ignore:r,config:o}){let n;try{n=fe.readdirSync(e);}catch{program.error(A.red(`Couldn't read the ${A.bold(e)} directory.`));}let i=[];for(let s of n){let a=oe.join(e,s);if(fe.statSync(a).isFile())continue;let c=`${oe.relative(t,a)}/`;if(r.ignores(c))continue;let l=oe.basename(s);if(!Ss(l,o))continue;let f=Rs(l,o),h={name:l,blocks:[]},m=fe.readdirSync(a);for(let b of m){let d=oe.join(a,b),g=oe.relative(t,d);if(!r.ignores(g))if(fe.statSync(d).isFile()){if(ct(b))continue;if(Rr(b)){o.includeDocs||console.warn(`${T} ${ce} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`);continue}let y=js(b),u=Fn(y,o);if(!Ln(y,o))continue;let S=ut.find(J=>J.matches(b));if(!S){console.warn(`${T} ${ce} Skipped \`${A.bold(d)}\` \`*${A.bold(oe.parse(b).ext)}\` files are not currently supported!`);continue}let C=m.find(J=>_n.find(X=>J===`${y}${X}`)),p=m.find(J=>Mn.find(X=>J===`${y}${X}`)),{dependencies:w,devDependencies:x,local:R,imports:P}=S.resolveDependencies({filePath:d,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(J=>J,J=>{program.error(A.red(J));}),K={name:y,directory:oe.relative(t,a),category:l,tests:C!==void 0,docs:p!==void 0,subdirectory:false,list:f?u:false,files:[b],localDependencies:R,_imports_:P,dependencies:w,devDependencies:x};C!==void 0&&K.files.push(C),p!==void 0&&K.files.push(p),h.blocks.push(K);}else {let y=b,u=Fn(y,o);if(!Ln(y,o))continue;let S=new Set,C=new Set,p=new Set,w={},x=false,R=false,P=[],K=(X,$)=>{for(let N of $){let v=oe.join(X,N),W=v.slice(d.length+1);if(ct(N)){x=true,P.push(W);continue}if(Rr(N)){o.includeDocs||console.warn(`${T} ${ce} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`),R=true,P.push(W);continue}if(fe.statSync(v).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${ce} Skipped \`${A.bold(oe.join(d,N))}\` subdirectories are not allowed! Allow them with ${A.bold("--allow-subdirectories")}!`);continue}let G=fe.readdirSync(v);K(v,G);continue}let j=ut.find(G=>G.matches(N));if(!j){console.warn(`${T} ${ce} Skipped \`${v}\` \`*${A.bold(oe.parse(N).ext)}\` files are not currently supported!`);continue}let{local:U,dependencies:re,devDependencies:ye,imports:nt}=j.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:d,filePath:v,cwd:t}).match(G=>G,G=>{program.error(A.red(G));});for(let G of U)G!==`${l}/${y}`&&S.add(G);for(let G of re)C.add(G);for(let G of ye)p.add(G);for(let[G,Z]of Object.entries(nt))w[G]=Z;P.push(W);}};K(d,fe.readdirSync(d));let J={name:y,directory:oe.relative(t,d),category:l,tests:x,docs:R,subdirectory:true,list:f?u:false,files:P,localDependencies:Array.from(S.keys()),dependencies:Array.from(C.keys()),devDependencies:Array.from(p.keys()),_imports_:w};h.blocks.push(J);}}i.push(h);}return i}function jr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ut.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:oe.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(A.red(c));});a.length>0&&program.error(A.red(`${A.bold(o.name)} ${A.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:i,devDependencies:s});}return r}function Fn(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function Ln(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function Rs(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function Ss(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function js(e){return oe.parse(oe.basename(e)).name}function Pr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!An(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var Or=[".git","node_modules",".DS_Store"],yt="jsrepo.json",vt="jsrepo-build-config.json",Hr=k.union([k.literal("prettier"),k.literal("biome")]),Es=k.objectWithRest({"*":k.string()},k.string()),Kr=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),includeDocs:k.optional(k.boolean(),false),paths:Es,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(Hr)});function be(e){if(!fe.existsSync(oe.join(e,yt)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse(Kr,JSON.parse(fe.readFileSync(oe.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}var Is=k.object({$schema:k.string(),name:k.optional(k.string()),version:k.optional(k.string()),readme:k.optional(k.string(),"README.md"),access:k.optional(j),meta:k.optional(f),defaultPaths:k.optional(k.record(k.string(),k.string())),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string()),[]),includeCategories:k.optional(k.array(k.string()),[]),excludeBlocks:k.optional(k.array(k.string()),[]),excludeCategories:k.optional(k.array(k.string()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean(),false),rules:k.optional(Nn)});function Ft(e){if(!fe.existsSync(oe.join(e,vt)))return a(null);let t=k.safeParse(Is,JSON.parse(fe.readFileSync(oe.join(e,vt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${vt}\` file!`)}function Ue(e,t){let r=At(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=oe.relative(t,oe.join(oe.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${A.bold("`./`")}.`);let a=Os(s,o,t);if(!a)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} 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 ${A.bold("`./`")}.`);n[i]=a;}return a(n)}function Os(e,t,r){let o=t(e);return o.length>0?oe.relative(r,o[0]):void 0}function rr(e,t,r){let o;return t[e.category]!==void 0?o=oe.join(r,t[e.category]):o=oe.join(r,t["*"],e.category),o}async function Ge(e,t,{verbose:r}={}){return await A$1(e,t,{verbose:r,fetch:Re,token:Yr(e.provider,e.url)})}async function Lt(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Re,token:Yr(e.provider,e.url)})}function Yr(e,t){let r=new pe;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function lt(e,{noCache:t=false}={}){let r=z$1(e);if(r){let o=Ve();if(r.name!==u.name&&!t)if(t)o.delete(`${e}-state`);else {let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=r.parse(e,{fullyQualified:false}),i=await r.state(e,{token:Yr(r,n.url),fetch:Re});return r.name!==u.name&&!t&&o.set(`${e}-state`,i),a(i)}return b(`Only ${y.map((o,n)=>`${n===y.length-1?"and ":""}${A.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function qe(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await lt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function bt(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();for(let c$1 of a.categories)for(let l of c$1.blocks)r.set(c(i.url,`${l.category}/${l.name}`),{...l,sourceRepo:i});}))).find(i=>i!==void 0);return n||a(r)}function Bt(e){let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t}async function _t(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();r.push({state:i,manifest:a});}))).find(i=>i!==void 0);return n||a(r)}async function $t(e,t,r,o=new Map){let n=new Map;for(let i of e){let s,a=z$1(i);if(a){let{url:l,specifier:f}=a.parse(i,{fullyQualified:true});s=t.get(c(l,f));}else {if(r.length===0)return b(A.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${A.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:f,specifier:h}=l.provider.parse(c(l.url,i),{fullyQualified:true}),m=t.get(c(f,h));if(m!==void 0){s=m;break}}}if(!s)return b(`Invalid block! ${A.bold(i)} does not exist!`);let c$1=`${s.category}/${s.name}`;if(n.set(c$1,s),s.localDependencies&&s.localDependencies.length>0){let l=await $t(s.localDependencies.filter(f=>!n.has(f)&&!o.has(f)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let f of l.unwrap())n.set(`${f.category}/${f.name}`,f);}}return a(mr(n,(i,s)=>s))}function xt(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(A.red(i)));for(let[i,s]of e){let a=rr(s,n,r),c=oe.join(a,s.files[0]);s.subdirectory&&(c=oe.join(a,s.name)),fe.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function Mt(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>!(ct(s)&&!t.includeTests||Rr(s)&&!t.includeDocs)),i=Promise.all(n.map(async s=>{let a=await Ge(o.sourceRepo,oe.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function nr(e,t,r,o){let n=rr(t,r,o);return t.subdirectory?oe.join(n,t.name,e):oe.join(n,e)}function ir(e){if(e===void 0)return;let t={};for(let r of e.split(",")){let[o,n]=r.split("=");if(o===void 0||n===void 0)throw new InvalidArgumentError("Expected map to be provided in the following format: `--option key=value,key=value`");t[o]=n;}return t}function Wn(e){return new Promise(t=>t(e))}async function Ct({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await nn.resolveConfig(oe.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=oe.join(t,"biome.json");fe.existsSync(n)&&(o=JSON.parse(fe.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function sr(e){return `Installed from ${e}`}function Wt(e,t,r){if(!t.peerDependencies)return;let o=Gr(oe.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${A.bold("package.json")}. Please create one.`),program.error(A.red(s));}),n={...o.dependencies,...o.devDependencies},i=[];for(let[s,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let f=n[s];if(!f){i.push({name:s,expected:c,message:l,version:f,exists:false});continue}Jo.satisfies(gr(f),c)||i.push({name:s,expected:c,message:l,version:f,exists:true});}if(i.length>0){process.stdout.write(`${T}
71
71
  ${A.yellow("\u25B2")} ${Oo} Issues with ${A.bold(e.url)} peer dependencies
72
- `);let s=i.map((a,c)=>{let l=i.length-1===c,f;a.exists?f=`${A.yellowBright("x unmet peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)} >> found ${A.yellowBright.bold(a.version)}`:f=`${A.red("x missing peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)}`;let g=`${T} ${l?Do:Kt}${Ht} ${f}`;return a.message?`${g}
73
- ${T} ${l?"":T} ${A.gray(a.message)}`:g}).join(`
72
+ `);let s=i.map((a,c)=>{let l=i.length-1===c,f;a.exists?f=`${A.yellowBright("x unmet peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)} >> found ${A.yellowBright.bold(a.version)}`:f=`${A.red("x missing peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)}`;let h=`${T} ${l?Do:Kt}${Ht} ${f}`;return a.message?`${h}
73
+ ${T} ${l?"":T} ${A.gray(a.message)}`:h}).join(`
74
74
  `);process.stdout.write(`${s}
75
- `);}}var Gs=k.object({watermark:k.optional(k.boolean()),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(k.union([k.literal("prettier"),k.literal("biome"),k.literal("none")])),paths:k.optional(k.record(k.string(),k.string())),expand:k.boolean(),maxUnchanged:k.number(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Xr=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").addOption(new Option("--formatter <choice>","The formatter to use when adding blocks.").choices(["prettier","biome","none"])).addOption(new Option("--watermark <choice>","Include a watermark at the top of added files.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--tests <choice>","Include tests when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--docs <choice>","Include docs when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",ir,void 0).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("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Gs,t);await ie(),await qs(e,r),outro(A.green("All done!"));});async function qs(e,t){let r=$=>{t.verbose&&console.info(`${Ee} ${$}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=ve({verbose:t.verbose?r:void 0}),n=be(t.cwd),i=n.isErr(),s;if(n.isErr()){let $=t.yes;if(!t.yes){let N=await confirm({message:`You don't have ${Xe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(N)&&(cancel("Canceled!"),process.exit(0)),$=N;}$||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else s=n.unwrap();s.formatter=t.formatter!==void 0&&t.formatter!=="none"?t.formatter:s.formatter,s.watermark=t.watermark!==void 0?t.watermark:s.watermark,s.includeTests=t.tests!==void 0?t.tests:s.includeTests,s.includeDocs=t.docs!==void 0?t.docs:s.includeDocs,s.paths=t.paths!==void 0?{...s.paths,...t.paths}:s.paths;let a=s.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let $ of e){let N=z$1($);if(!N){l=true;continue}let{url:v}=N.parse($,{fullyQualified:true});if(!(!s.repos.find(j=>j===v)&&!c$1.has(v))){if(!t.allow){let j=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}c$1.add(v);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let $=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel($)||!$)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(A.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${A.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(a.join(", "))}`);let f=(await qe(a,{noCache:!t.cache})).match($=>$,({repo:$,message:N})=>{o.stop(`Failed to get info for ${A.cyan($)}`),program.error(A.red(N));});r(`Resolved ${A.cyan(a.join(", "))}`),r(`Fetching blocks from ${A.cyan(a.join(", "))}`);let g=(await _t(f,{verbose:t.verbose?r:void 0})).match($=>$,({repo:$,message:N})=>{o.stop(`Failed fetching blocks from ${A.cyan($)}`),program.error(A.red(N));}),m=Bt(g);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(a.join(", "))}`),r(`Retrieved blocks from ${A.cyan(a.join(", "))}`);for(let $ of g)Wt($.state,$.manifest,t.cwd);let b=xt(m,s,t.cwd).map($=>$.specifier),d=e;if(d.length===0){let $=await multiselect({message:"Select which blocks to add.",options:Array.from(m.entries()).filter(([N,v])=>v.list).map(([N,v])=>{let W=`${v.category}/${v.name}`,j=b.findIndex(oe=>oe===W)!==-1,U;return a.length>1?U=`${A.cyan(c(v.sourceRepo.url,v.category))}/${v.name}`:U=`${A.cyan(v.category)}/${v.name}`,{label:j?A.gray(U):U,value:N,hint:j?"Installed":void 0}}),required:true});isCancel($)&&(cancel("Canceled!"),process.exit(0)),d=$;}r(`Installing blocks ${A.cyan(d.join(", "))}`);let h=(await $t(d,m,f)).match($=>$,$=>program.error($)),y=new Set,u=new Set,S=Ve();if(i){let $=`${t.cwd}-zero-config`,N=k.safeParse(Kr,S.get($)),v=N.success?N.output:s,W=Array.from(new Set(h.map(j=>j.category)));if(t.paths===void 0)for(let j of W){let U=await text({message:`Where would you like to add ${A.cyan(j)}?`,placeholder:v?v.paths[j]:`./src/${j}`,initialValue:v?v.paths[j]:`./src/${j}`,defaultValue:v?v.paths[j]:`./src/${j}`,validate(oe){if(oe.trim()==="")return "Please provide a value"}});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),s.paths[j]=U;}if(!t.yes&&t.tests===void 0){let j=await confirm({message:"Include tests?",initialValue:v.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=j;}if(!t.yes&&t.watermark===void 0){let j=await confirm({message:"Add watermark?",initialValue:v.watermark});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.watermark=j;}if(t.formatter===void 0){let j="none";fe.existsSync(te.join(t.cwd,".prettierrc"))&&(j="prettier"),fe.existsSync(te.join(t.cwd,"biome.json"))&&(j="biome");let U=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(oe=>({value:oe.toLowerCase(),label:oe})),initialValue:j==="none"?v.formatter?v.formatter:"none":j});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),U!=="none"&&(s.formatter=U);}S.set($,s),b=xt(m,s,t.cwd).map(j=>j.specifier);}let{prettierOptions:C,biomeOptions:p}=await Ct({formatter:s.formatter,cwd:t.cwd}),w=Ue(s.paths,t.cwd).match($=>$,$=>program.error(A.red($))),x=new Set,R,E=Mt(h,s),K=[];for(let $ of E){let N=c($.block.sourceRepo.url,$.block.category,$.block.name),v=`${$.block.category}/${$.block.name}`;r(`Setting up ${N}`);let W=b.find(j=>v===j);s.includeTests&&$.block.tests&&(r("Trying to include tests"),y.add("vitest"));for(let j of $.block.devDependencies)y.add(j);for(let j of $.block.dependencies)u.add(j);if(W&&!t.yes&&!R){if(R===void 0){let j=h.map(oe=>`${oe.category}/${oe.name}`).filter(oe=>b.find(ye=>ye===oe));log.warn(`The following components ${A.bold.yellow("already exist")}: ${A.cyan(Qo(j))}`);let U=await confirm({message:`Would you like to ${A.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),R=U;}if(!R){let j=await $.files;process.stdout.write(`${T}
75
+ `);}}var Gs=k.object({watermark:k.optional(k.boolean()),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(k.union([k.literal("prettier"),k.literal("biome"),k.literal("none")])),paths:k.optional(k.record(k.string(),k.string())),expand:k.boolean(),maxUnchanged:k.number(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),Xr=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").addOption(new Option("--formatter <choice>","The formatter to use when adding blocks.").choices(["prettier","biome","none"])).addOption(new Option("--watermark <choice>","Include a watermark at the top of added files.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--tests <choice>","Include tests when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--docs <choice>","Include docs when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",ir,void 0).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("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Gs,t);await ie(),await qs(e,r),outro(A.green("All done!"));});async function qs(e,t){let r=$=>{t.verbose&&console.info(`${Ee} ${$}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=ve({verbose:t.verbose?r:void 0}),n=be(t.cwd),i=n.isErr(),s;if(n.isErr()){let $=t.yes;if(!t.yes){let N=await confirm({message:`You don't have ${Xe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(N)&&(cancel("Canceled!"),process.exit(0)),$=N;}$||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else s=n.unwrap();s.formatter=t.formatter!==void 0&&t.formatter!=="none"?t.formatter:s.formatter,s.watermark=t.watermark!==void 0?t.watermark:s.watermark,s.includeTests=t.tests!==void 0?t.tests:s.includeTests,s.includeDocs=t.docs!==void 0?t.docs:s.includeDocs,s.paths=t.paths!==void 0?{...s.paths,...t.paths}:s.paths;let a=s.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let $ of e){let N=z$1($);if(!N){l=true;continue}let{url:v}=N.parse($,{fullyQualified:true});if(!(!s.repos.find(j=>j===v)&&!c$1.has(v))){if(!t.allow){let j=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}c$1.add(v);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let $=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel($)||!$)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(A.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${A.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(a.join(", "))}`);let f=(await qe(a,{noCache:!t.cache})).match($=>$,({repo:$,message:N})=>{o.stop(`Failed to get info for ${A.cyan($)}`),program.error(A.red(N));});r(`Resolved ${A.cyan(a.join(", "))}`),r(`Fetching blocks from ${A.cyan(a.join(", "))}`);let h=(await _t(f,{verbose:t.verbose?r:void 0})).match($=>$,({repo:$,message:N})=>{o.stop(`Failed fetching blocks from ${A.cyan($)}`),program.error(A.red(N));}),m=Bt(h);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(a.join(", "))}`),r(`Retrieved blocks from ${A.cyan(a.join(", "))}`);for(let $ of h)Wt($.state,$.manifest,t.cwd);let b=xt(m,s,t.cwd).map($=>$.specifier),d=e;if(d.length===0){let $=await multiselect({message:"Select which blocks to add.",options:Array.from(m.entries()).filter(([N,v])=>v.list).map(([N,v])=>{let W=`${v.category}/${v.name}`,j=b.findIndex(re=>re===W)!==-1,U;return a.length>1?U=`${A.cyan(c(v.sourceRepo.url,v.category))}/${v.name}`:U=`${A.cyan(v.category)}/${v.name}`,{label:j?A.gray(U):U,value:N,hint:j?"Installed":void 0}}),required:true});isCancel($)&&(cancel("Canceled!"),process.exit(0)),d=$;}r(`Installing blocks ${A.cyan(d.join(", "))}`);let g=(await $t(d,m,f)).match($=>$,$=>program.error($)),y=new Set,u=new Set,S=Ve();if(i){let $=`${t.cwd}-zero-config`,N=k.safeParse(Kr,S.get($)),v=N.success?N.output:s,W=Array.from(new Set(g.map(j=>j.category)));if(t.paths===void 0)for(let j of W){let U=await text({message:`Where would you like to add ${A.cyan(j)}?`,placeholder:v?v.paths[j]:`./src/${j}`,initialValue:v?v.paths[j]:`./src/${j}`,defaultValue:v?v.paths[j]:`./src/${j}`,validate(re){if(re.trim()==="")return "Please provide a value"}});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),s.paths[j]=U;}if(!t.yes&&t.tests===void 0){let j=await confirm({message:"Include tests?",initialValue:v.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=j;}if(!t.yes&&t.watermark===void 0){let j=await confirm({message:"Add watermark?",initialValue:v.watermark});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.watermark=j;}if(t.formatter===void 0){let j="none";fe.existsSync(oe.join(t.cwd,".prettierrc"))&&(j="prettier"),fe.existsSync(oe.join(t.cwd,"biome.json"))&&(j="biome");let U=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(re=>({value:re.toLowerCase(),label:re})),initialValue:j==="none"?v.formatter?v.formatter:"none":j});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),U!=="none"&&(s.formatter=U);}S.set($,s),b=xt(m,s,t.cwd).map(j=>j.specifier);}let{prettierOptions:C,biomeOptions:p}=await Ct({formatter:s.formatter,cwd:t.cwd}),w=Ue(s.paths,t.cwd).match($=>$,$=>program.error(A.red($))),x=new Set,R,P=Mt(g,s),K=[];for(let $ of P){let N=c($.block.sourceRepo.url,$.block.category,$.block.name),v=`${$.block.category}/${$.block.name}`;r(`Setting up ${N}`);let W=b.find(j=>v===j);s.includeTests&&$.block.tests&&(r("Trying to include tests"),y.add("vitest"));for(let j of $.block.devDependencies)y.add(j);for(let j of $.block.dependencies)u.add(j);if(W&&!t.yes&&!R){if(R===void 0){let j=g.map(re=>`${re.category}/${re.name}`).filter(re=>b.find(ye=>ye===re));log.warn(`The following components ${A.bold.yellow("already exist")}: ${A.cyan(Qo(j))}`);let U=await confirm({message:`Would you like to ${A.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(U)&&(cancel("Canceled!"),process.exit(0)),R=U;}if(!R){let j=await $.files;process.stdout.write(`${T}
76
76
  `),process.stdout.write(`${T} ${N}
77
- `);for(let U of j){let oe=U.content.match(Pe=>Pe,Pe=>program.error(A.red(Pe))),ye=nr(U.name,$.block,w,t.cwd),nt=(await Zt({file:{content:oe,destPath:ye},biomeOptions:p,prettierOptions:C,config:s,imports:$.block._imports_,watermark:sr($.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Pe=>Pe,Pe=>program.error(A.red(Pe))),G="";fe.existsSync(ye)&&(G=fe.readFileSync(ye).toString());let Z=await Nt({config:{biomeOptions:p,prettierOptions:C,formatter:s.formatter},current:{path:ye,content:G},incoming:{path:c(N,U.name),content:nt},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});Z.applyChanges&&(K.push(Vn({destination:ye,content:Z.updatedContent,block:$.block})),x.add(v));}continue}}$.files.then(j=>{j.map(async U=>{let oe=U.content.match(G=>G,G=>program.error(A.red(G))),ye=nr(U.name,$.block,w,t.cwd),nt=Zt({file:{content:oe,destPath:ye},biomeOptions:p,prettierOptions:C,config:s,imports:$.block._imports_,watermark:sr($.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(G=>(G.isErr()&&program.error(A.red(G.unwrapErr())),{destination:ye,content:G.unwrap(),block:$.block}));K.push(nt);});}),x.add(v);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(E.map($=>$.files)),await Promise.all(K.map(async $=>{let N=await $,v=te.dirname(N.destination);fe.existsSync(v)||(r(`Creating directory ${A.bold(v)}`),fe.mkdirSync(v,{recursive:true})),r(`Writing to ${A.bold(N.destination)}`),fe.writeFileSync(N.destination,N.content);})),o.stop(`Added blocks ${A.cyan(Array.from(x).join(", "))}`));let J=(await detect({cwd:t.cwd}))?.agent??"npm",X=await et(u,y,{yes:t.yes,cwd:t.cwd,pm:J});if(X.dependencies.size>0||X.devDependencies.size>0){let $=[];if(!X.installed){if(u.size>0){let v=resolveCommand(J,"add",[...u]);$.push(`Install dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(y.size>0){let v=resolveCommand(J,"add",[...y,"-D"]);$.push(`Install dev dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}$=$.map((v,W)=>`${W+1}. ${v}`),X.installed||$.push(""),$.push("Import and use the blocks!");let N=ft($);process.stdout.write(N);}}function Kn(e){return new Promise(t=>setTimeout(t,e))}var Zs=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),to=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(Zs,e);await ie(),await ea(t),outro(A.green("All done!"));});async function ea(e){let t=new pe;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${We}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${We}!`);return}if(t.get("jsrepo")!==void 0){let a=await confirm({message:"You are currently signed into jsrepo do you want to sign out?",initialValue:false});(isCancel(a)||!a)&&(cancel("Canceled!"),process.exit(0));}let r=Xs.machineIdSync(true),o;try{let a=await Re(`${w}/api/login/device`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!a.ok)throw new Error("There was an error creating the session");o=(await a.json()).id;}catch(a){program.error(A.red(a));}log.step(`Sign in at ${A.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=ve(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(A.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await Kn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Re(a,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!c.ok)continue;clearTimeout(s);let l=await c.text();t.set("jsrepo",l),i.stop(`Logged into ${We}!`);break}catch{}}}var na=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),ro=new Command("build").description(`Builds the provided --dirs in the project root into a \`${m}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--include-docs","Include docs files (*.mdx, *.md) in the registry.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(na,e);await ie(),await ia(t),outro(A.green("All done!"));});async function ia(e){let t=d=>{e.verbose&&console.info(`${Ee} ${d}`);},r=ve({verbose:e.verbose?t:void 0}),o$1=[],n=Ft(e.cwd).match(d=>{if(d===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview,includeDocs:e.includeDocs??false};let h=d;return e.dirs&&(h.dirs=e.dirs),e.outputDir&&(h.outputDir=e.outputDir),e.doNotListBlocks&&(h.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(h.doNotListCategories=e.doNotListCategories),e.listBlocks&&(h.listBlocks=e.listBlocks),e.listCategories&&(h.listCategories=e.listCategories),e.includeBlocks&&(h.includeBlocks=e.includeBlocks),e.includeCategories&&(h.includeCategories=e.includeCategories),e.excludeBlocks&&(h.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(h.excludeCategories=e.excludeCategories),e.excludeDeps&&(h.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(h.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(h.preview=e.preview),e.includeDocs!==void 0&&(h.includeDocs=e.includeDocs),h.rules={...er,...h.rules},h},d=>program.error(A.red(d))),i;n.outputDir?i=te.join(e.cwd,n.outputDir):i=e.cwd;let s=te.join(i,m);if(e.output&&fe.existsSync(s)){if(n.outputDir){let d=o(fe.readFileSync(s).toString());if(d.isOk())for(let h of d.unwrap().categories)for(let y of h.blocks){let u=te.join(i,y.directory);fe.existsSync(u)&&fe.rmSync(u,{recursive:true});}}fe.rmSync(s);}let a=oa();try{let d=fe.readFileSync(te.join(e.cwd,".gitignore")).toString();a.add(d);}catch{}a.add(Or);for(let d of n.dirs){let h=te.join(e.cwd,d);r.start(`Building ${A.cyan(h)}`);let y=Sr(h,{cwd:e.cwd,ignore:a,config:n});for(let u of y){if(o$1.find(S=>S.name===u.name)!==void 0){console.warn(`${T} ${ce} Skipped adding \`${A.cyan(`${d}/${u.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(u);}r.stop(`Built ${A.cyan(h)}`);}let c=jr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:f,errors:g}=Cr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(f.length>0||g.length>0)&&console.log(T);for(let d of f)console.log(d);if(g.length>0){for(let d of g)console.log(d);program.error(A.red(`Completed checking manifest with ${A.bold(`${g.length} error(s)`)} and ${A.bold(`${f.length} warning(s)`)}`));}let[m$1,b]=Pr(l.categories);if(l.categories=m$1,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n.preview){let d=l.categories.flatMap(h=>h.blocks.filter(y=>y.list).map(y=>`${A.cyan(y.category)}/${y.name}`));log.message(`${A.yellow("Preview")}:`);for(let h of d)console.log(`${T} \u25FB ${h}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${A.cyan(i)}\``),l.configFiles)for(let d of l.configFiles){let h=te.join(e.cwd,d.path),y=te.join(i,d.path),u=te.join(y,"../");fe.existsSync(u)||fe.mkdirSync(u,{recursive:true}),fe.copyFileSync(h,y);}for(let d of l.categories)for(let h of d.blocks){let y=te.join(e.cwd,h.directory),u=te.join(i,h.directory);for(let S of h.files){let C=te.join(u,S,"../");fe.existsSync(C)||fe.mkdirSync(C,{recursive:true}),fe.copyFileSync(te.join(y,S),te.join(u,S));}}r.stop(`Copied registry files to \`${A.cyan(i)}\``);}r.start(`Writing output to \`${A.cyan(s)}\``),fe.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${A.cyan(s)}\``);}}var fa=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),io=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(fa,t);await ie(),await ma(e,o,r);});async function ma(e,t,r){let o=v=>{t.verbose&&console.info(`${Ee} ${v}`);},n=e,i=ve({verbose:t.verbose?o:void 0}),s=be(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let f=n?z$1(n):void 0;if(n&&f){let{url:v}=f.parse(n,{fullyQualified:true});if(!l.find(W=>W===v)){if(!t.allow){let W=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(W)||!W)&&(cancel("Canceled!"),process.exit(0));}l=[v];}}if(!t.allow&&t.repo){let v=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(v)||!v)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(A.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${A.cyan(l.join(", "))}`);let g=(await qe(l,{noCache:!t.cache})).match(v=>v,({repo:v,message:W})=>{i.stop(`Failed to get info for ${A.cyan(v)}`),program.error(A.red(W));}),m=(await bt(g,{verbose:t.verbose?o:void 0})).match(v=>v,({repo:v,message:W})=>{i.stop(`Failed fetching scripts from ${A.cyan(v)}`),program.error(A.red(W));});if(i.stop(`Retrieved scripts from ${A.cyan(l.join(", "))}`),!n){let v=await select({message:"Select which script to run.",options:Array.from(m.entries()).filter(([W,j])=>j.list).map(([W,j])=>{let U;return l.length>1?U=`${A.cyan(c(j.sourceRepo.url,j.category))}/${j.name}`:U=`${A.cyan(j.category)}/${j.name}`,{label:U,value:W}})});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),n=v;}let b=(await $t([n],m,g)).match(v=>v,v=>program.error(v)),d="temp-jsrepo-exec",h=`./${d}/${encodeURIComponent(n)}`,y=te.join(process.cwd(),h);c$1.paths["*"]=h,fe.mkdirSync(y,{recursive:true});let u=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],C=new Set,p=new Set,w=Ue(c$1.paths,t.cwd);w.isErr()&&program.error(A.red(w.unwrapErr()));let x$1=w.unwrap(),R=[];for(let v of b){let W=`${v.sourceRepo.url}/${v.category}/${v.name}`,j=`${v.category}/${v.name}`,U=v.sourceRepo,oe=te.join(t.cwd,x$1["*"],v.category);R.push(j),S.push({run:async({message:ye})=>{ye(`Adding ${A.cyan(W)}`),fe.mkdirSync(oe,{recursive:true});let nt=[],G=async Z=>{let Pe=await Ge(U,Z);return Pe.isErr()&&(i.stop(A.red(`Error fetching ${A.bold(Z)}`)),program.error(A.red(`There was an error trying to get ${W}`))),Pe.unwrap()};for(let Z of v.files){if(!c$1.includeTests&&ct(Z))continue;let Pe=te.join(v.directory,Z),zt;v.subdirectory?zt=te.join(oe,v.name,Z):zt=te.join(oe,Z);let fi=await G(Pe),mi=zt.slice(0,zt.length-Z.length);fe.mkdirSync(mi,{recursive:true}),nt.push({content:fi,destPath:zt});}for(let Z of nt)fe.writeFileSync(Z.destPath,Z.content);if(c$1.includeTests&&v.tests){let{devDependencies:Z}=JSON.parse(fe.readFileSync(te.join(t.cwd,"package.json")).toString());(Z===void 0||Z.vitest===void 0)&&C.add("vitest");}for(let Z of v.devDependencies)C.add(Z);for(let Z of v.dependencies)p.add(Z);}});}if(await Yo({startMessage:"Adding blocks",stopMessage:`Added ${A.cyan(R.join(", "))}`,loading:i,tasks:S}),p.size>0||C.size>0){let v={name:"temp-package",type:"module",version:"0.0.1"},W=te.join(y,"package.json");fe.writeFileSync(W,JSON.stringify(v,null," "));}await et(p,C,{yes:true,no:false,cwd:y,pm:u,ignoreWorkspace:true});let K=r.parent.rawArgs.findIndex(v=>v==="--"),J=[];K!==-1&&(J=r.parent.rawArgs.slice(K+1)),o(`Passing args ${A.cyan(J.join(" "))}`),console.clear();let X=b[0],$;X.subdirectory?$=te.join(y,`${X.category}/${X.name}/index.js`):$=te.join(y,`${X.category}/${X.name}.js`);let N=resolveCommand(u,"execute",["tsx",$,...J]);N||program.error(A.red("Error resolving run command!"));try{let v=x(N.command,N.args,{nodeOptions:{cwd:process.cwd()}});for await(let W of v)process.stdout.write(`${W}
78
- `);}finally{fe.rmSync(te.join(process.cwd(),d),{recursive:true,force:true});}}var ha=k.object({json:k.boolean()}),so=new Command("info").description("Get info about a registry on jsrepo.com").argument("registry","Name of the registry to get the info for i.e. @ieedan/std").option("--json","Output the response in formatted JSON.",false).action(async(e,t)=>{let r=k.parse(ha,t);await ya(e,r);});async function ya(e,t){let o=new pe().get(x$1.name),n={};if(o){let[c,l]=x$1.authHeader(o);n[c]=l;}let i=new URL(`/api/scopes/${e}`,w).toString(),s=await Ai(i,{headers:n});s.ok||(s.status===404?program.error(A.red("Registry not found!")):program.error(A.red(`Error fetching registry! Error: ${s.status} - ${s.statusText}`)));let a=await s.json();if(t.json)return process.stdout.write(JSON.stringify(a,null," "));process.stdout.write(va(a));}function va(e){let t=`${A.cyan(`${e.name}@${e.version}`)} | versions: ${A.cyan(e.versions.length.toString())}
77
+ `);for(let U of j){let re=U.content.match(Pe=>Pe,Pe=>program.error(A.red(Pe))),ye=nr(U.name,$.block,w,t.cwd),nt=(await Zt({file:{content:re,destPath:ye},biomeOptions:p,prettierOptions:C,config:s,imports:$.block._imports_,watermark:sr($.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Pe=>Pe,Pe=>program.error(A.red(Pe))),G="";fe.existsSync(ye)&&(G=fe.readFileSync(ye).toString());let Z=await Nt({config:{biomeOptions:p,prettierOptions:C,formatter:s.formatter},current:{path:ye,content:G},incoming:{path:c(N,U.name),content:nt},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});Z.applyChanges&&(K.push(Wn({destination:ye,content:Z.updatedContent,block:$.block})),x.add(v));}continue}}$.files.then(j=>{j.map(async U=>{let re=U.content.match(G=>G,G=>program.error(A.red(G))),ye=nr(U.name,$.block,w,t.cwd),nt=Zt({file:{content:re,destPath:ye},biomeOptions:p,prettierOptions:C,config:s,imports:$.block._imports_,watermark:sr($.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(G=>(G.isErr()&&program.error(A.red(G.unwrapErr())),{destination:ye,content:G.unwrap(),block:$.block}));K.push(nt);});}),x.add(v);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(P.map($=>$.files)),await Promise.all(K.map(async $=>{let N=await $,v=oe.dirname(N.destination);fe.existsSync(v)||(r(`Creating directory ${A.bold(v)}`),fe.mkdirSync(v,{recursive:true})),r(`Writing to ${A.bold(N.destination)}`),fe.writeFileSync(N.destination,N.content);})),o.stop(`Added blocks ${A.cyan(Array.from(x).join(", "))}`));let J=(await detect({cwd:t.cwd}))?.agent??"npm",X=await et(u,y,{yes:t.yes,cwd:t.cwd,pm:J});if(X.dependencies.size>0||X.devDependencies.size>0){let $=[];if(!X.installed){if(u.size>0){let v=resolveCommand(J,"add",[...u]);$.push(`Install dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(y.size>0){let v=resolveCommand(J,"add",[...y,"-D"]);$.push(`Install dev dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}$=$.map((v,W)=>`${W+1}. ${v}`),X.installed||$.push(""),$.push("Import and use the blocks!");let N=ft($);process.stdout.write(N);}}function Hn(e){return new Promise(t=>setTimeout(t,e))}var Zs=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),to=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(Zs,e);await ie(),await ea(t),outro(A.green("All done!"));});async function ea(e){let t=new pe;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${We}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${We}!`);return}if(t.get("jsrepo")!==void 0){let a=await confirm({message:"You are currently signed into jsrepo do you want to sign out?",initialValue:false});(isCancel(a)||!a)&&(cancel("Canceled!"),process.exit(0));}let r=Xs.machineIdSync(true),o;try{let a=await Re(`${w}/api/login/device`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!a.ok)throw new Error("There was an error creating the session");o=(await a.json()).id;}catch(a){program.error(A.red(a));}log.step(`Sign in at ${A.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=ve(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(A.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await Hn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Re(a,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!c.ok)continue;clearTimeout(s);let l=await c.text();t.set("jsrepo",l),i.stop(`Logged into ${We}!`);break}catch{}}}var na=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),ro=new Command("build").description(`Builds the provided --dirs in the project root into a \`${m}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--include-docs","Include docs files (*.mdx, *.md) in the registry.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(na,e);await ie(),await ia(t),outro(A.green("All done!"));});async function ia(e){let t=d=>{e.verbose&&console.info(`${Ee} ${d}`);},r=ve({verbose:e.verbose?t:void 0}),o$1=[],n=Ft(e.cwd).match(d=>{if(d===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview,includeDocs:e.includeDocs??false};let g=d;return e.dirs&&(g.dirs=e.dirs),e.outputDir&&(g.outputDir=e.outputDir),e.doNotListBlocks&&(g.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(g.doNotListCategories=e.doNotListCategories),e.listBlocks&&(g.listBlocks=e.listBlocks),e.listCategories&&(g.listCategories=e.listCategories),e.includeBlocks&&(g.includeBlocks=e.includeBlocks),e.includeCategories&&(g.includeCategories=e.includeCategories),e.excludeBlocks&&(g.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(g.excludeCategories=e.excludeCategories),e.excludeDeps&&(g.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(g.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(g.preview=e.preview),e.includeDocs!==void 0&&(g.includeDocs=e.includeDocs),g.rules={...er,...g.rules},g},d=>program.error(A.red(d))),i;n.outputDir?i=oe.join(e.cwd,n.outputDir):i=e.cwd;let s=oe.join(i,m);if(e.output&&fe.existsSync(s)){if(n.outputDir){let d=o(fe.readFileSync(s).toString());if(d.isOk())for(let g of d.unwrap().categories)for(let y of g.blocks){let u=oe.join(i,y.directory);fe.existsSync(u)&&fe.rmSync(u,{recursive:true});}}fe.rmSync(s);}let a=oa();try{let d=fe.readFileSync(oe.join(e.cwd,".gitignore")).toString();a.add(d);}catch{}a.add(Or);for(let d of n.dirs){let g=oe.join(e.cwd,d);r.start(`Building ${A.cyan(g)}`);let y=Sr(g,{cwd:e.cwd,ignore:a,config:n});for(let u of y){if(o$1.find(S=>S.name===u.name)!==void 0){console.warn(`${T} ${ce} Skipped adding \`${A.cyan(`${d}/${u.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(u);}r.stop(`Built ${A.cyan(g)}`);}let c=jr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:f,errors:h}=Cr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(f.length>0||h.length>0)&&console.log(T);for(let d of f)console.log(d);if(h.length>0){for(let d of h)console.log(d);program.error(A.red(`Completed checking manifest with ${A.bold(`${h.length} error(s)`)} and ${A.bold(`${f.length} warning(s)`)}`));}let[m$1,b]=Pr(l.categories);if(l.categories=m$1,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n.preview){let d=l.categories.flatMap(g=>g.blocks.filter(y=>y.list).map(y=>`${A.cyan(y.category)}/${y.name}`));log.message(`${A.yellow("Preview")}:`);for(let g of d)console.log(`${T} \u25FB ${g}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${A.cyan(i)}\``),l.configFiles)for(let d of l.configFiles){let g=oe.join(e.cwd,d.path),y=oe.join(i,d.path),u=oe.join(y,"../");fe.existsSync(u)||fe.mkdirSync(u,{recursive:true}),fe.copyFileSync(g,y);}for(let d of l.categories)for(let g of d.blocks){let y=oe.join(e.cwd,g.directory),u=oe.join(i,g.directory);for(let S of g.files){let C=oe.join(u,S,"../");fe.existsSync(C)||fe.mkdirSync(C,{recursive:true}),fe.copyFileSync(oe.join(y,S),oe.join(u,S));}}r.stop(`Copied registry files to \`${A.cyan(i)}\``);}r.start(`Writing output to \`${A.cyan(s)}\``),fe.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${A.cyan(s)}\``);}}var fa=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),io=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(fa,t);await ie(),await ma(e,o,r);});async function ma(e,t,r){let o=v=>{t.verbose&&console.info(`${Ee} ${v}`);},n=e,i=ve({verbose:t.verbose?o:void 0}),s=be(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let f=n?z$1(n):void 0;if(n&&f){let{url:v}=f.parse(n,{fullyQualified:true});if(!l.find(W=>W===v)){if(!t.allow){let W=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(W)||!W)&&(cancel("Canceled!"),process.exit(0));}l=[v];}}if(!t.allow&&t.repo){let v=await confirm({message:`Allow ${Xe} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(v)||!v)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(A.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${A.cyan(l.join(", "))}`);let h=(await qe(l,{noCache:!t.cache})).match(v=>v,({repo:v,message:W})=>{i.stop(`Failed to get info for ${A.cyan(v)}`),program.error(A.red(W));}),m=(await bt(h,{verbose:t.verbose?o:void 0})).match(v=>v,({repo:v,message:W})=>{i.stop(`Failed fetching scripts from ${A.cyan(v)}`),program.error(A.red(W));});if(i.stop(`Retrieved scripts from ${A.cyan(l.join(", "))}`),!n){let v=await select({message:"Select which script to run.",options:Array.from(m.entries()).filter(([W,j])=>j.list).map(([W,j])=>{let U;return l.length>1?U=`${A.cyan(c(j.sourceRepo.url,j.category))}/${j.name}`:U=`${A.cyan(j.category)}/${j.name}`,{label:U,value:W}})});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),n=v;}let b=(await $t([n],m,h)).match(v=>v,v=>program.error(v)),d="temp-jsrepo-exec",g=`./${d}/${encodeURIComponent(n)}`,y=oe.join(process.cwd(),g);c$1.paths["*"]=g,fe.mkdirSync(y,{recursive:true});let u=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],C=new Set,p=new Set,w=Ue(c$1.paths,t.cwd);w.isErr()&&program.error(A.red(w.unwrapErr()));let x$1=w.unwrap(),R=[];for(let v of b){let W=`${v.sourceRepo.url}/${v.category}/${v.name}`,j=`${v.category}/${v.name}`,U=v.sourceRepo,re=oe.join(t.cwd,x$1["*"],v.category);R.push(j),S.push({run:async({message:ye})=>{ye(`Adding ${A.cyan(W)}`),fe.mkdirSync(re,{recursive:true});let nt=[],G=async Z=>{let Pe=await Ge(U,Z);return Pe.isErr()&&(i.stop(A.red(`Error fetching ${A.bold(Z)}`)),program.error(A.red(`There was an error trying to get ${W}`))),Pe.unwrap()};for(let Z of v.files){if(!c$1.includeTests&&ct(Z))continue;let Pe=oe.join(v.directory,Z),zt;v.subdirectory?zt=oe.join(re,v.name,Z):zt=oe.join(re,Z);let pi=await G(Pe),fi=zt.slice(0,zt.length-Z.length);fe.mkdirSync(fi,{recursive:true}),nt.push({content:pi,destPath:zt});}for(let Z of nt)fe.writeFileSync(Z.destPath,Z.content);if(c$1.includeTests&&v.tests){let{devDependencies:Z}=JSON.parse(fe.readFileSync(oe.join(t.cwd,"package.json")).toString());(Z===void 0||Z.vitest===void 0)&&C.add("vitest");}for(let Z of v.devDependencies)C.add(Z);for(let Z of v.dependencies)p.add(Z);}});}if(await Yo({startMessage:"Adding blocks",stopMessage:`Added ${A.cyan(R.join(", "))}`,loading:i,tasks:S}),p.size>0||C.size>0){let v={name:"temp-package",type:"module",version:"0.0.1"},W=oe.join(y,"package.json");fe.writeFileSync(W,JSON.stringify(v,null," "));}await et(p,C,{yes:true,no:false,cwd:y,pm:u,ignoreWorkspace:true});let K=r.parent.rawArgs.findIndex(v=>v==="--"),J=[];K!==-1&&(J=r.parent.rawArgs.slice(K+1)),o(`Passing args ${A.cyan(J.join(" "))}`),console.clear();let X=b[0],$;X.subdirectory?$=oe.join(y,`${X.category}/${X.name}/index.js`):$=oe.join(y,`${X.category}/${X.name}.js`);let N=resolveCommand(u,"execute",["tsx",$,...J]);N||program.error(A.red("Error resolving run command!"));try{let v=x(N.command,N.args,{nodeOptions:{cwd:process.cwd()}});for await(let W of v)process.stdout.write(`${W}
78
+ `);}finally{fe.rmSync(oe.join(process.cwd(),d),{recursive:true,force:true});}}var ha=k.object({json:k.boolean()}),so=new Command("info").description("Get info about a registry on jsrepo.com").argument("registry","Name of the registry to get the info for i.e. @ieedan/std").option("--json","Output the response in formatted JSON.",false).action(async(e,t)=>{let r=k.parse(ha,t);await ya(e,r);});async function ya(e,t){let o=new pe().get(x$1.name),n={};if(o){let[c,l]=x$1.authHeader(o);n[c]=l;}let i=new URL(`/api/scopes/${e}`,w).toString(),s=await Ni(i,{headers:n});s.ok||(s.status===404?program.error(A.red("Registry not found!")):program.error(A.red(`Error fetching registry! Error: ${s.status} - ${s.statusText}`)));let a=await s.json();if(t.json)return process.stdout.write(JSON.stringify(a,null," "));process.stdout.write(va(a));}function va(e){let t=`${A.cyan(`${e.name}@${e.version}`)} | versions: ${A.cyan(e.versions.length.toString())}
79
79
  `;e.meta.description&&(t+=`${e.meta.description}
80
80
  `),e.meta.homepage&&(t+=`${A.blue(e.meta.homepage)}
81
81
  `),t+=`
@@ -93,7 +93,7 @@ ${e.meta.authors.map(i=>`- ${A.blue(i)}`).join(`
93
93
  ${Object.entries(e.tags).map(([i,s])=>`${A.blue(i)}: ${s}`).join(`
94
94
  `)}
95
95
 
96
- `,t}var Ca=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(Hr),paths:k.optional(k.record(k.string(),k.string())),configFiles:k.optional(k.record(k.string(),k.string())),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),buildScript:k.string(),publishScript:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),po=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").option("--docs","Will include docs with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).addOption(new Option("--paths <category=path>,<category=path>","The paths to install the blocks to.").argParser(ir).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(ir).default({})).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").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("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Ca,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(A.red(`You cannot provide both ${A.bold("--project")} and ${A.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${A.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${A.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await Ra(e,r):await ja(r),outro(A.green("All done!"));}),Ra=async(e,t)=>{let r=be(t.cwd),o=spinner(),n,i={},s=At(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(A.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let C=await text({message:"Please enter a default path to install the blocks",validate(p){if(p.trim()==="")return "Please provide a value";if(!p.startsWith("./")){let w="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return w;let x=createPathsMatcher(s);if(x&&x(p).length===0)return w}},placeholder:"./src/blocks",initialValue:a});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),a=C;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";fe.existsSync(te.join(t.cwd,".prettierrc"))&&(C="prettier"),fe.existsSync(te.join(t.cwd,"biome.json"))&&(C="biome");let p=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(w=>({value:w.toLowerCase(),label:w})),initialValue:C});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p!=="none"&&(t.formatter=p);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,f=new Set,g=async C=>{let p=await Sa({url:C,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let w of p.dependencies)l.add(w);for(let w of p.devDependencies)f.add(w);n=p.paths,i=p.configFiles;};if(c.length>0)for(let C of c){if(!e.find(p=>p===C)&&r.isOk()&&r.unwrap().repos.find(p=>p===C)){let p=await confirm({message:`Initialize ${C}?`,initialValue:t.yes});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)continue}log.info(`Initializing ${A.cyan(C)}`),await g(C);}for(;!t.yes;){{let p=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)break}let C=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:p=>{if(p.trim().length===0)return "Please provide a value";if(!z$1(p))return `Invalid provider! Valid providers (${y.map(w=>w.name).join(", ")})`}});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),await g(C),c.push(C);}let m={$schema:`https://unpkg.com/jsrepo@${Fe.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,includeDocs:r.isOk()&&t.docs===void 0?r.unwrap().includeDocs:t.docs??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${yt}\``);let{prettierOptions:b,biomeOptions:d}=await Ct({formatter:m.formatter,cwd:t.cwd}),h=te.join(t.cwd,yt),y$1=await kr.format(JSON.stringify(m,null," "),{biomeOptions:d,prettierOptions:b,filePath:h,formatter:m.formatter});fe.existsSync(t.cwd)||fe.mkdirSync(t.cwd,{recursive:true}),fe.writeFileSync(h,y$1),o.stop(`Wrote config to \`${yt}\`.`);let u=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await et(l,f,{yes:t.yes,cwd:t.cwd,pm:u});if(S.dependencies.size>0||S.devDependencies.size>0){let C=[];if(!S.installed){if(l.size>0){let w=resolveCommand$1(u,"add",[...l]);C.push(`Install dependencies \`${A.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(f.size>0){let w=resolveCommand$1(u,"add",[...f,"-D"]);C.push(`Install dev dependencies \`${A.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}C=C.map((w,x)=>`${x+1}. ${w}`),S.installed||C.push(""),C.push(`Add blocks with ${A.cyan("jsrepo add")}!`);let p=ft(C);process.stdout.write(p);}};async function Sa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new pe,a=z$1(e);a||program.error(A.red(`Invalid provider! Valid providers (${y.map(d=>d.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let d=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(d.url).origin}`;}if(!s.get(c$1)&&!n.yes){let d=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d){let h=await password({message:"Paste your token",validate(y){if(y.trim()==="")return "Please provide a value"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,h);}}i.start(`Fetching manifest from ${A.cyan(e)}`);let f=(await lt(e,{noCache:!n.cache})).match(d=>d,d=>program.error(A.red(d))),g=(await Lt(f)).match(d=>d,d=>program.error(A.red(d)));i.stop(`Fetched manifest from ${A.cyan(e)}`),Wt(f,g,n.cwd);let m=[],b=[];if(g.configFiles){let{prettierOptions:d,biomeOptions:h}=await Ct({formatter:o,cwd:n.cwd});for(let y of g.configFiles){if(y.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${y.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(m.push(...y.dependencies??[]),b.push(...y.devDependencies??[]),!r[y.name])if(n.configFiles?.[y.name])r[y.name]=n.configFiles[y.name];else if(n.yes)y.expectedPath||program.error(A.red(`You must provide a path for ${y.name} when using --yes!`)),r[y.name]=y.expectedPath;else {let x=await text({message:`Where is your ${y.name} file?`,defaultValue:y.expectedPath,initialValue:y.expectedPath,placeholder:y.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[y.name]=x;}let u=te.join(n.cwd,r[y.name]),S;if(fe.existsSync(u))S=fe.readFileSync(u).toString();else {let x=te.dirname(u);if(fe.existsSync(x)){let R=rn(u);if(R){S=fe.readFileSync(R).toString();let E=te.relative(n.cwd,R);log.warn(`Located ${A.bold(r[y.name])} at ${A.bold(E)}`),r[y.name]=E,u=te.join(n.cwd,E);}}}i.start(`Fetching the ${A.cyan(y.name)} from ${A.cyan(e)}`);let C=(await Ge(f,y.path)).match(x=>x,x=>program.error(A.red(x))),p=await vr({file:{content:C,destPath:u},biomeOptions:h,prettierOptions:d,formatter:o});i.stop(`Fetched the ${A.cyan(y.name)} from ${A.cyan(e)}`);let w=n.yes||S===void 0;if(S){if(!n.yes){let x=c(f.url,y.name),R=await Nt({config:{biomeOptions:h,prettierOptions:d,formatter:o},current:{content:S,path:u},incoming:{content:p,path:x},options:{...n,loading:i,no:false}});R.applyChanges&&(w=true,S=R.updatedContent);}}else {let x=te.dirname(u);fe.existsSync(x)||fe.mkdirSync(x,{recursive:true}),S=p;}w&&S&&(i.start(`Writing ${A.cyan(y.name)} to ${A.cyan(u)}`),fe.writeFileSync(u,S),i.stop(`Wrote ${A.cyan(y.name)} to ${A.cyan(u)}`));}}if(!n.yes){let d=await multiselect({message:"Which category paths would you like to configure?",options:g.categories.map(h=>({label:h.name,value:h.name,hint:g.defaultPaths?.[h.name]?`Default: ${g.defaultPaths?.[h.name]}`:void 0})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let h of d){let y=t[h]??g.defaultPaths?.[h],u=await text({message:`Where should ${h} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:y||`./src/${h}`,defaultValue:y,initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),t[h]=u;}}for(let d of g.categories){if(t[d.name]!==void 0)continue;let h=g.defaultPaths?.[d.name];h&&(t[d.name]=h);}return {paths:t,configFiles:r,dependencies:m,devDependencies:b}}var ja=async e=>{let t=spinner(),r=te.join(e.cwd,"package.json");fe.existsSync(r)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let o=Ft(e.cwd).match(d=>d,d=>program.error(A.red(d)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false,includeDocs:false}),o.$schema=`https://unpkg.com/jsrepo@${Fe.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let h=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)break}let d=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:h=>{if(h.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(d);}let n=JSON.parse(fe.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let d=await confirm({message:`Configure to publish to ${We}?`,initialValue:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),i=d;}if(i){if(!o.name){let d=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:h=>{if(h.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.name=d;}o.version||(o.version="0.0.1"),e.publishScript=await ti(e.publishScript,n,e,"release:registry");}else e.buildScript=await ti(e.buildScript,n,e,"build:registry");let s=n.devDependencies&&n.devDependencies.jsrepo!==void 0,a=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="jsrepo build",l="jsrepo publish";n.scripts===void 0&&(n.scripts={}),i?n.scripts[e.publishScript]=l:n.scripts[e.buildScript]=c;let f=[];f.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{fe.writeFileSync(r,JSON.stringify(n,null," "));}catch(d){program.error(A.red(`Error writing to \`${A.bold(r)}\`. Error: ${d}`));}}}),f.push({loadingMessage:`Writing config to \`${A.cyan(vt)}\``,completedMessage:`Wrote config to \`${A.cyan(vt)}\``,run:async()=>{let d=te.join(e.cwd,vt);try{fe.writeFileSync(te.join(d),JSON.stringify(o,null," "));}catch(h){program.error(A.red(`Error writing to \`${A.bold(d)}\`. Error: ${h}`));}}}),await Ko(f,{loading:t});let g=s;s||(g=(await et(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let m=[];if(!g){let d=resolveCommand$1(a,"add",["jsrepo","-D"]);m.push(`Install ${Xe} as a dev dependency \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\``);}if(m.push(`Add categories to \`${A.cyan(o.dirs.join(", "))}\`.`),i){let d=resolveCommand$1(a,"run",[e.publishScript]);m.push(`Run \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to publish the registry.`);}else {let d=resolveCommand$1(a,"run",[e.buildScript]);m.push(`Run \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to build the registry.`);}m=m.map((d,h)=>`${h+1}. ${d}`);let b=ft(m);process.stdout.write(b);};async function ti(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${A.cyan(n)}\` already exists overwrite?`,initialValue:false});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),i)break;{let s=await text({message:"What would you like to call the script?",placeholder:o,validate:a=>{if(a.trim().length===0)return "Please provide a value!"}});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),n=s;}}return n}var Da={name:"list-components",description:"Lists all available components/utilities for the provided registries. If registries are not provided tries to use the registries in the users jsrepo.json file.",inputSchema:{type:"object",properties:{registries:{type:"array",description:"Registries to list components from. If not provided will use the registries in the users jsrepo.json file.",items:{type:"string"}},cwd:{type:"string",description:"The current working directory of the users project."}},required:["cwd"]}};async function Ta({registries:e,cwd:t}){if(!e){let n=be(t).match(i=>i,()=>{throw new Error("Could not find your configuration file! Please provide `registries`.")});if(n.repos.length===0)throw new Error("No registries (repos) in your configuration file! Please provide `registries`.");e=n.repos;}let r=(await qe(e)).match(n=>n,n=>{throw new Error(`Error getting registry state for ${n.repo}: ${n.message}`)}),o=(await bt(r)).match(n=>n,n=>{throw new Error(`Error getting components for ${n.repo}: ${n.message}`)});return {components:mr(o,(n,i)=>i).map(n=>c(n.sourceRepo.url,`${n.category}/${n.name}`))}}var Na={name:"get-component-code",description:"Returns the associated code files for the provided component.",inputSchema:{type:"object",properties:{component:{type:"string",description:"The component to get the code for. Format: <registry>/<category>/<block>"},includeTests:{type:"boolean",description:"Should tests be included with the component code.",default:false},includeDocs:{type:"boolean",description:"Should docs be included with the component code.",default:false}},required:["component"]}};async function Aa({component:e,includeTests:t=false,includeDocs:r=false}){let o=z$1(e);if(!o)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let{url:n,specifier:i}=o.parse(e,{fullyQualified:true});if(!i)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let s=(await lt(n)).match(m=>m,m=>{throw new Error(`Error getting state for ${n}: ${m}`)}),a=(await _t([s])).match(m=>m,m=>{throw new Error(`Error getting manifest for ${n}: ${m}`)}),l=Bt(a).get(c(n,i));if(!l)throw new Error(`${i} does not exist in ${n}`);let f=Mt([l],{includeTests:t,includeDocs:r}),g=(await Promise.all(f.map(m=>m.files))).flatMap(m=>[...m.map(b=>({name:b.name,content:b.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:n,component:i,files:g,commands:{add:`jsrepo add ${e} -y -A`,addMultiple:`jsrepo add ${e} ... -y -A`,update:`jsrepo update ${e} -y -A`}}}var Fa={name:"get-config-files",description:"Lists the config files for this registry. These are files that are either necessary for the registry to work or optional as marked by the `optional` boolean on each file.",inputSchema:{type:"object",properties:{registry:{type:"string",description:"Registry to list config files from.",examples:["@ieedan/std","github/ieedan/std","gitlab/ieedan/std","bitbucket/ieedan/std","azure/ieedan/std/std","https://example.com/r"]},requiredOnly:{type:"boolean",description:"When true only returns the config files required for the registry to work properly."}},required:["registry"]}};async function La({registry:e,requiredOnly:t=false}){let r=(await lt(e)).match(i=>i,i=>{throw new Error(`Error getting state for ${e}: ${i}`)}),o=(await Lt(r)).match(i=>i,i=>{throw new Error(`Error getting manifest for ${e}: ${i}`)});return !o.configFiles||o.configFiles.length===0?[]:{configFiles:await Promise.all(o.configFiles.filter(i=>!t||!i.optional).map(async i=>{let s=(await Ge(r,i.path)).unwrapOr("<FETCH ERROR>");return {...i,content:s}}))}}var Ba={name:"search-registries",description:"Search jsrepo.com for registries that could include components the user needs in their project.",inputSchema:{type:"object",properties:{query:{description:"A term to search for the registries by.",type:"string"}},required:["query"]}};async function _a({query:e}){let t=await Re(`${w}/api/registries?order_by=most_popular&q=${e}`);if(!t.ok)return [];let{data:r}=await t.json();return {registries:r.map(o=>{let n=`@${o.scope.name}/${o.name}`;return {name:n,description:o.metaDescription,repository:o.metaRepository,keywords:o.metaTags,homepage:o.metaHomepage,rating:o.rating,primaryLanguage:o.metaPrimaryLanguage,monthlyDownloads:o.monthlyFetches,latestVersion:o.latestVersion,access:o.access,commands:{init:`jsrepo init ${n}`}}})}}var Ma={name:"cli-reference",description:"A reference for the usage of the jsrepo CLI.",inputSchema:{type:"object"}};function Wa(){return {name:Et.name(),description:Et.description(),version:Et.version(),commands:Et.commands.map(e=>({name:e.name(),description:e.description(),usage:e.usage(),options:e.options.map(t=>({flags:t.flags,description:t.description,defaultValue:t.defaultValue}))}))}}async function ni(){let e=new Server({name:"jsrepo",version:Fe.version},{capabilities:{tools:{}}});e.setRequestHandler(CallToolRequestSchema,async r=>{console.error(`Received CallToolRequest calling: ${A.bold(r.params.name)}`);try{switch(r.params.name){case "list-components":{let o=r.params.arguments,n=await Ta(o);return {content:[{type:"text",text:`Available components:
96
+ `,t}var Ca=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(Hr),paths:k.optional(k.record(k.string(),k.string())),configFiles:k.optional(k.record(k.string(),k.string())),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),buildScript:k.string(),publishScript:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),po=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").option("--docs","Will include docs with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).addOption(new Option("--paths <category=path>,<category=path>","The paths to install the blocks to.").argParser(ir).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(ir).default({})).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").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("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Ca,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(A.red(`You cannot provide both ${A.bold("--project")} and ${A.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${A.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${A.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await Ra(e,r):await ja(r),outro(A.green("All done!"));}),Ra=async(e,t)=>{let r=be(t.cwd),o=spinner(),n,i={},s=At(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(A.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let C=await text({message:"Please enter a default path to install the blocks",validate(p){if(p.trim()==="")return "Please provide a value";if(!p.startsWith("./")){let w="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return w;let x=createPathsMatcher(s);if(x&&x(p).length===0)return w}},placeholder:"./src/blocks",initialValue:a});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),a=C;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";fe.existsSync(oe.join(t.cwd,".prettierrc"))&&(C="prettier"),fe.existsSync(oe.join(t.cwd,"biome.json"))&&(C="biome");let p=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(w=>({value:w.toLowerCase(),label:w})),initialValue:C});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p!=="none"&&(t.formatter=p);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,f=new Set,h=async C=>{let p=await Sa({url:C,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let w of p.dependencies)l.add(w);for(let w of p.devDependencies)f.add(w);n=p.paths,i=p.configFiles;};if(c.length>0)for(let C of c){if(!e.find(p=>p===C)&&r.isOk()&&r.unwrap().repos.find(p=>p===C)){let p=await confirm({message:`Initialize ${C}?`,initialValue:t.yes});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)continue}log.info(`Initializing ${A.cyan(C)}`),await h(C);}for(;!t.yes;){{let p=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)break}let C=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:p=>{if(p.trim().length===0)return "Please provide a value";if(!z$1(p))return `Invalid provider! Valid providers (${y.map(w=>w.name).join(", ")})`}});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),await h(C),c.push(C);}let m={$schema:`https://unpkg.com/jsrepo@${Fe.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,includeDocs:r.isOk()&&t.docs===void 0?r.unwrap().includeDocs:t.docs??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${yt}\``);let{prettierOptions:b,biomeOptions:d}=await Ct({formatter:m.formatter,cwd:t.cwd}),g=oe.join(t.cwd,yt),y$1=await kr.format(JSON.stringify(m,null," "),{biomeOptions:d,prettierOptions:b,filePath:g,formatter:m.formatter});fe.existsSync(t.cwd)||fe.mkdirSync(t.cwd,{recursive:true}),fe.writeFileSync(g,y$1),o.stop(`Wrote config to \`${yt}\`.`);let u=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await et(l,f,{yes:t.yes,cwd:t.cwd,pm:u});if(S.dependencies.size>0||S.devDependencies.size>0){let C=[];if(!S.installed){if(l.size>0){let w=resolveCommand$1(u,"add",[...l]);C.push(`Install dependencies \`${A.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(f.size>0){let w=resolveCommand$1(u,"add",[...f,"-D"]);C.push(`Install dev dependencies \`${A.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}C=C.map((w,x)=>`${x+1}. ${w}`),S.installed||C.push(""),C.push(`Add blocks with ${A.cyan("jsrepo add")}!`);let p=ft(C);process.stdout.write(p);}};async function Sa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new pe,a=z$1(e);a||program.error(A.red(`Invalid provider! Valid providers (${y.map(d=>d.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let d=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(d.url).origin}`;}if(!s.get(c$1)&&!n.yes){let d=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d){let g=await password({message:"Paste your token",validate(y){if(y.trim()==="")return "Please provide a value"}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,g);}}i.start(`Fetching manifest from ${A.cyan(e)}`);let f=(await lt(e,{noCache:!n.cache})).match(d=>d,d=>program.error(A.red(d))),h=(await Lt(f)).match(d=>d,d=>program.error(A.red(d)));i.stop(`Fetched manifest from ${A.cyan(e)}`),Wt(f,h,n.cwd);let m=[],b=[];if(h.configFiles){let{prettierOptions:d,biomeOptions:g}=await Ct({formatter:o,cwd:n.cwd});for(let y of h.configFiles){if(y.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${y.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(m.push(...y.dependencies??[]),b.push(...y.devDependencies??[]),!r[y.name])if(n.configFiles?.[y.name])r[y.name]=n.configFiles[y.name];else if(n.yes)y.expectedPath||program.error(A.red(`You must provide a path for ${y.name} when using --yes!`)),r[y.name]=y.expectedPath;else {let x=await text({message:`Where is your ${y.name} file?`,defaultValue:y.expectedPath,initialValue:y.expectedPath,placeholder:y.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[y.name]=x;}let u=oe.join(n.cwd,r[y.name]),S;if(fe.existsSync(u))S=fe.readFileSync(u).toString();else {let x=oe.dirname(u);if(fe.existsSync(x)){let R=rn(u);if(R){S=fe.readFileSync(R).toString();let P=oe.relative(n.cwd,R);log.warn(`Located ${A.bold(r[y.name])} at ${A.bold(P)}`),r[y.name]=P,u=oe.join(n.cwd,P);}}}i.start(`Fetching the ${A.cyan(y.name)} from ${A.cyan(e)}`);let C=(await Ge(f,y.path)).match(x=>x,x=>program.error(A.red(x))),p=await vr({file:{content:C,destPath:u},biomeOptions:g,prettierOptions:d,formatter:o});i.stop(`Fetched the ${A.cyan(y.name)} from ${A.cyan(e)}`);let w=n.yes||S===void 0;if(S){if(!n.yes){let x=c(f.url,y.name),R=await Nt({config:{biomeOptions:g,prettierOptions:d,formatter:o},current:{content:S,path:u},incoming:{content:p,path:x},options:{...n,loading:i,no:false}});R.applyChanges&&(w=true,S=R.updatedContent);}}else {let x=oe.dirname(u);fe.existsSync(x)||fe.mkdirSync(x,{recursive:true}),S=p;}w&&S&&(i.start(`Writing ${A.cyan(y.name)} to ${A.cyan(u)}`),fe.writeFileSync(u,S),i.stop(`Wrote ${A.cyan(y.name)} to ${A.cyan(u)}`));}}if(!n.yes){let d=await multiselect({message:"Which category paths would you like to configure?",options:h.categories.map(g=>({label:g.name,value:g.name,hint:h.defaultPaths?.[g.name]?`Default: ${h.defaultPaths?.[g.name]}`:void 0})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let g of d){let y=t[g]??h.defaultPaths?.[g],u=await text({message:`Where should ${g} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:y||`./src/${g}`,defaultValue:y,initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),t[g]=u;}}for(let d of h.categories){if(t[d.name]!==void 0)continue;let g=h.defaultPaths?.[d.name];g&&(t[d.name]=g);}return {paths:t,configFiles:r,dependencies:m,devDependencies:b}}var ja=async e=>{let t=spinner(),r=oe.join(e.cwd,"package.json");fe.existsSync(r)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let o=Ft(e.cwd).match(d=>d,d=>program.error(A.red(d)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false,includeDocs:false}),o.$schema=`https://unpkg.com/jsrepo@${Fe.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let g=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),!g)break}let d=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:g=>{if(g.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(d);}let n=JSON.parse(fe.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let d=await confirm({message:`Configure to publish to ${We}?`,initialValue:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),i=d;}if(i){if(!o.name){let d=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:g=>{if(g.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.name=d;}o.version||(o.version="0.0.1"),e.publishScript=await ei(e.publishScript,n,e,"release:registry");}else e.buildScript=await ei(e.buildScript,n,e,"build:registry");let s=n.devDependencies&&n.devDependencies.jsrepo!==void 0,a=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="jsrepo build",l="jsrepo publish";n.scripts===void 0&&(n.scripts={}),i?n.scripts[e.publishScript]=l:n.scripts[e.buildScript]=c;let f=[];f.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{fe.writeFileSync(r,JSON.stringify(n,null," "));}catch(d){program.error(A.red(`Error writing to \`${A.bold(r)}\`. Error: ${d}`));}}}),f.push({loadingMessage:`Writing config to \`${A.cyan(vt)}\``,completedMessage:`Wrote config to \`${A.cyan(vt)}\``,run:async()=>{let d=oe.join(e.cwd,vt);try{fe.writeFileSync(oe.join(d),JSON.stringify(o,null," "));}catch(g){program.error(A.red(`Error writing to \`${A.bold(d)}\`. Error: ${g}`));}}}),await Ko(f,{loading:t});let h=s;s||(h=(await et(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let m=[];if(!h){let d=resolveCommand$1(a,"add",["jsrepo","-D"]);m.push(`Install ${Xe} as a dev dependency \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\``);}if(m.push(`Add categories to \`${A.cyan(o.dirs.join(", "))}\`.`),i){let d=resolveCommand$1(a,"run",[e.publishScript]);m.push(`Run \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to publish the registry.`);}else {let d=resolveCommand$1(a,"run",[e.buildScript]);m.push(`Run \`${A.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to build the registry.`);}m=m.map((d,g)=>`${g+1}. ${d}`);let b=ft(m);process.stdout.write(b);};async function ei(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${A.cyan(n)}\` already exists overwrite?`,initialValue:false});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),i)break;{let s=await text({message:"What would you like to call the script?",placeholder:o,validate:a=>{if(a.trim().length===0)return "Please provide a value!"}});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),n=s;}}return n}var Da={name:"list-components",description:"Lists all available components/utilities for the provided registries. If registries are not provided tries to use the registries in the users jsrepo.json file.",inputSchema:{type:"object",properties:{registries:{type:"array",description:"Registries to list components from. If not provided will use the registries in the users jsrepo.json file.",items:{type:"string"}},cwd:{type:"string",description:"The current working directory of the users project."}},required:["cwd"]}};async function Ta({registries:e,cwd:t}){if(!e){let n=be(t).match(i=>i,()=>{throw new Error("Could not find your configuration file! Please provide `registries`.")});if(n.repos.length===0)throw new Error("No registries (repos) in your configuration file! Please provide `registries`.");e=n.repos;}let r=(await qe(e)).match(n=>n,n=>{throw new Error(`Error getting registry state for ${n.repo}: ${n.message}`)}),o=(await bt(r)).match(n=>n,n=>{throw new Error(`Error getting components for ${n.repo}: ${n.message}`)});return {components:mr(o,(n,i)=>i).map(n=>c(n.sourceRepo.url,`${n.category}/${n.name}`))}}var Na={name:"get-component-code",description:"Returns the associated code files for the provided component.",inputSchema:{type:"object",properties:{component:{type:"string",description:"The component to get the code for. Format: <registry>/<category>/<block>"},includeTests:{type:"boolean",description:"Should tests be included with the component code.",default:false},includeDocs:{type:"boolean",description:"Should docs be included with the component code.",default:false}},required:["component"]}};async function Aa({component:e,includeTests:t=false,includeDocs:r=false}){let o=z$1(e);if(!o)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let{url:n,specifier:i}=o.parse(e,{fullyQualified:true});if(!i)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let s=(await lt(n)).match(m=>m,m=>{throw new Error(`Error getting state for ${n}: ${m}`)}),a=(await _t([s])).match(m=>m,m=>{throw new Error(`Error getting manifest for ${n}: ${m}`)}),l=Bt(a).get(c(n,i));if(!l)throw new Error(`${i} does not exist in ${n}`);let f=Mt([l],{includeTests:t,includeDocs:r}),h=(await Promise.all(f.map(m=>m.files))).flatMap(m=>[...m.map(b=>({name:b.name,content:b.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:n,component:i,files:h,commands:{add:`jsrepo add ${e} -y -A`,addMultiple:`jsrepo add ${e} ... -y -A`,update:`jsrepo update ${e} -y -A`}}}var Fa={name:"get-config-files",description:"Lists the config files for this registry. These are files that are either necessary for the registry to work or optional as marked by the `optional` boolean on each file.",inputSchema:{type:"object",properties:{registry:{type:"string",description:"Registry to list config files from.",examples:["@ieedan/std","github/ieedan/std","gitlab/ieedan/std","bitbucket/ieedan/std","azure/ieedan/std/std","https://example.com/r"]},requiredOnly:{type:"boolean",description:"When true only returns the config files required for the registry to work properly."}},required:["registry"]}};async function La({registry:e,requiredOnly:t=false}){let r=(await lt(e)).match(i=>i,i=>{throw new Error(`Error getting state for ${e}: ${i}`)}),o=(await Lt(r)).match(i=>i,i=>{throw new Error(`Error getting manifest for ${e}: ${i}`)});return !o.configFiles||o.configFiles.length===0?[]:{configFiles:await Promise.all(o.configFiles.filter(i=>!t||!i.optional).map(async i=>{let s=(await Ge(r,i.path)).unwrapOr("<FETCH ERROR>");return {...i,content:s}}))}}var Ba={name:"search-registries",description:"Search jsrepo.com for registries that could include components the user needs in their project.",inputSchema:{type:"object",properties:{query:{description:"A term to search for the registries by.",type:"string"}},required:["query"]}};async function _a({query:e}){let t=await Re(`${w}/api/registries?order_by=most_popular&q=${e}`);if(!t.ok)return [];let{data:r}=await t.json();return {registries:r.map(o=>{let n=`@${o.scope.name}/${o.name}`;return {name:n,description:o.metaDescription,repository:o.metaRepository,keywords:o.metaTags,homepage:o.metaHomepage,rating:o.rating,primaryLanguage:o.metaPrimaryLanguage,monthlyDownloads:o.monthlyFetches,latestVersion:o.latestVersion,access:o.access,commands:{init:`jsrepo init ${n}`}}})}}var Ma={name:"cli-reference",description:"A reference for the usage of the jsrepo CLI.",inputSchema:{type:"object"}};function Wa(){return {name:Et.name(),description:Et.description(),version:Et.version(),commands:Et.commands.map(e=>({name:e.name(),description:e.description(),usage:e.usage(),options:e.options.map(t=>({flags:t.flags,description:t.description,defaultValue:t.defaultValue}))}))}}async function oi(){let e=new Server({name:"jsrepo",version:Fe.version},{capabilities:{tools:{}}});e.setRequestHandler(CallToolRequestSchema,async r=>{console.error(`Received CallToolRequest calling: ${A.bold(r.params.name)}`);try{switch(r.params.name){case "list-components":{let o=r.params.arguments,n=await Ta(o);return {content:[{type:"text",text:`Available components:
97
97
  ${JSON.stringify(n.components)}
98
98
  Add a component to your project with:
99
99
  jsrepo add ${n.components[0]} -y -A
@@ -102,10 +102,10 @@ jsrepo add ${n.components[0]} ${n.components[1]??n.components[0]} ... -y -A
102
102
  Update existing components with:
103
103
  jsrepo update ${n.components[0]} -y -A
104
104
  Update multiple components with:
105
- jsrepo update ${n.components[0]} ${n.components[1]??n.components[0]} ... -y -A`}]}}case "get-component-code":{let o=r.params.arguments,n=await Aa(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "get-config-files":{let o=r.params.arguments,n=await La(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "search-registries":{let o=r.params.arguments,n=await _a(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "cli-reference":{let o=Wa();return {content:[{type:"text",text:JSON.stringify(o)}]}}}throw new Error(`Invalid tool ${r.params.name}`)}catch(o){return console.error(A.red(`Error executing tool ${A.bold(r.params.name)}: ${o}`)),{content:[{type:"text",text:JSON.stringify({error:o instanceof Error?o.message:String(o)})}]}}}),e.setRequestHandler(ListToolsRequestSchema,async()=>(console.error("Received ListToolsRequest"),{tools:[Da,Na,Fa,Ba,Ma]}));let t=new StdioServerTransport;console.error("Connecting server to transport..."),await e.connect(t),console.error("Server connected");}var mo=new Command("mcp").description("Interact with jsrepo through an MCP server.").option("--cwd <path>","The current working directory.",process.cwd()).action(async()=>{await ni().catch(e=>{console.error(e),process.exit(1);});});var za=k.object({private:k.boolean(),dryRun:k.boolean(),name:k.optional(k.string()),ver:k.optional(k.string()),dirs:k.optional(k.array(k.string())),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),verbose:k.boolean(),cwd:k.string()}),uo=new Command("publish").description("Publish a registry to jsrepo.com.").option("--private","When publishing the first version of the registry make it private.",false).option("--dry-run","Test the publish but don't list on jsrepo.com.",false).option("--name <name>","The name of the registry. i.e. @ieedan/std").option("--ver <version>","The version of the registry. i.e. 0.0.1").option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--include-docs","Include documentation files (*.md, *.mdx) in the registry.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(za,e);await ie(),await Ha(t),outro(A.green("All done!"));});async function Ha(e){let t=p=>{e.verbose&&console.info(`${Ee} ${p}`);},r=ve({verbose:e.verbose?t:void 0}),o=Ft(e.cwd).match(p=>{if(p===null)return {$schema:"",access:"public",readme:"README.md",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,includeDocs:e.includeDocs??false};let w=p;return e.private&&(w.access="private"),e.name&&(w.name=e.name),e.ver&&(w.version=e.ver),e.dirs&&(w.dirs=e.dirs),e.doNotListBlocks&&(w.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(w.doNotListCategories=e.doNotListCategories),e.listBlocks&&(w.listBlocks=e.listBlocks),e.listCategories&&(w.listCategories=e.listCategories),e.includeBlocks&&(w.includeBlocks=e.includeBlocks),e.includeCategories&&(w.includeCategories=e.includeCategories),e.excludeBlocks&&(w.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(w.excludeCategories=e.excludeCategories),e.excludeDeps&&(w.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(w.allowSubdirectories=e.allowSubdirectories),e.includeDocs!==void 0&&(w.includeDocs=e.includeDocs),w.rules={...er,...w.rules},w},p=>program.error(A.red(p)));if(e.dryRun&&log.warn(A.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[p,w,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!p.startsWith("@"))throw new Error;if(!p.slice(1).match(v))throw new Error;if(!w.match(v))throw new Error}catch{program.error(A.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`name\` field in the \`jsrepo-build-config.json\``));if(o.version!==void 0){if(o.version==="package"){let w=te.join(e.cwd,"package.json");fe.existsSync(w)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let{version:x}=JSON.parse(fe.readFileSync(w).toString());o.version=x;}Jo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`version\` field in the \`jsrepo-build-config.json\``));let n=new pe().get("jsrepo");n===void 0&&program.error(A.red(`Please authenticate with ${A.cyan("jsrepo auth")} to publish to ${We}.`));let i=[],s=oa();try{let p=fe.readFileSync(te.join(e.cwd,".gitignore")).toString();s.add(p);}catch{}s.add(Or);for(let p of o.dirs){let w=te.join(e.cwd,p);r.start(`Building ${A.cyan(w)}`);let x=Sr(w,{cwd:e.cwd,ignore:s,config:o});for(let R of x){if(i.find(E=>E.name===R.name)!==void 0){console.warn(`${T} ${ce} Skipped adding \`${A.cyan(`${p}/${R.name}`)}\` because a category with the same name already exists!`);continue}i.push(R);}r.stop(`Built ${A.cyan(w)}`);}let a=jr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:f}=Cr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||f.length>0)&&console.log(T);for(let p of l)console.log(p);if(f.length>0){for(let p of f)console.log(p);program.error(A.red(`Completed checking manifest with ${A.bold(`${f.length} error(s)`)} and ${A.bold(`${l.length} warning(s)`)}`));}let[g,m]=Pr(c.categories);c.categories=g,m>0&&log.step(`Removed ${m} unused block${m>1?"s":""}.`),r.start(`Packaging ${A.cyan(c.name)}...`);let b=te.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${b}`),fe.mkdirSync(b,{recursive:true}),t("Writing manifest to temp dir"),fe.writeFileSync(te.resolve(b,"jsrepo-manifest.json"),JSON.stringify(c));let d=te.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),fe.copyFileSync(d,te.join(b,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let p of c.configFiles){let w=te.join(e.cwd,p.path),x=te.join(b,p.path),R=te.join(x,"../");fe.existsSync(R)||fe.mkdirSync(R,{recursive:true}),fe.copyFileSync(w,x);}t("Copied config files");}t("Copying registry files");for(let p of c.categories)for(let w of p.blocks){let x=te.join(e.cwd,w.directory),R=te.join(b,w.directory);for(let E of w.files){let K=te.join(R,E,"../");fe.existsSync(K)||fe.mkdirSync(K,{recursive:true}),fe.copyFileSync(te.join(x,E),te.join(R,E));}}t("Copied registry files");let h=te.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),y=fe.readdirSync(b);t("Creating archive file"),await ii.create({z:true,cwd:b,file:h},y),t("Created archive file"),t("Removing temp directory"),fe.rmSync(b,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${A.cyan(h)}...`);let u=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${A.cyan(u)}`),r.start(`Publishing ${A.bold(c.name)} to ${We}...`);let S=fe.readFileSync(h);t("Removing archive file"),fe.rmSync(h,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let C=await Re(`${w}/api/publish`,{body:S,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":u},method:"POST"});if(r.stop(`Got response from ${We}.`),C.ok){let p=await C.json();p.status==="dry-run"?log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} published ${A.greenBright(`@${p.scope}`)}/${p.registry}${A.greenBright(`@${p.version}`)}!`);}else {let p=await C.json();C.status===500&&program.error(`${A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${p.message}`)}
106
- Please try again. If this persists please contact support at ${A.cyan("https://www.jsrepo.com/help")}`),program.error(A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${p.message}`));}}var sc=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),go=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(sc,t);await ie(),await ac(e,r),outro(A.green("All done!"));});async function ac(e,t){let r=u=>{t.verbose&&console.info(`${Ee} ${u}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=be(t.cwd).match(u=>u,u=>program.error(A.red(u))),n=ve({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let u=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(u)||!u)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(u=>u,({repo:u,message:S})=>{n.stop(`Failed to get info for ${A.cyan(u)}`),program.error(A.red(S));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await bt(s,{verbose:t.verbose?r:void 0})).match(u=>u,({repo:u,message:S})=>{n.stop(`Failed fetching blocks from ${A.cyan(u)}`),program.error(A.red(S));});r(`Retrieved blocks from ${A.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`);let c$1=te.resolve(te.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${A.bold(c$1)}.`),fe.mkdirSync(c$1,{recursive:true});let l=()=>{fe.rmSync(c$1,{recursive:true,force:true});},f=xt(a,o,t.cwd).map(u=>u.specifier),g=e;e.length===0&&(g=f),g.length===0&&(l(),program.error(A.red("There were no blocks found in your project!")));let m=[];for(let u of g){let S,C=z$1(u);if(C){let{url:p}=C.parse(u,{fullyQualified:true}),w=(await lt(p)).match(R=>R,R=>program.error(A.red(R))),x=(await bt([w])).match(R=>R,R=>program.error(A.red(R)));for(let[R,E]of x)a.set(R,E);S=a.get(u);}else for(let p of i){let w=z$1(p);if(!w)continue;let{url:x,specifier:R}=w.parse(c(p,u),{fullyQualified:true}),E=a.get(c(x,R));if(E!==void 0){S=E;break}}S||program.error(A.red(`Invalid block! ${A.bold(u)} does not exist!`)),m.push({name:u,block:S});}let b=Ue(o.paths,t.cwd).match(u=>u,u=>program.error(A.red(u)));for(let{block:u}of m){let S=u.sourceRepo,C=c(u.sourceRepo.url,u.category,u.name);if(t.verbose||n.start(`Setting up test file for ${A.cyan(C)}`),!u.tests){n.stop(`No tests found for ${A.cyan(C)}`);continue}let p=rr(u,b,t.cwd);p=te.relative(c$1,p);let w=async R=>{let E=await Ge(S,R);return E.isErr()&&(n.stop(A.red(`Error fetching ${A.bold(R)}`)),program.error(A.red(`There was an error trying to get ${C}`))),E.unwrap()};r(`Downloading and copying test files for ${C}`);let x=[];for(let R of u.files.filter(E=>ct(E))){let E=await w(te.join(u.directory,R)),K=te.join(c$1,R);fe.writeFileSync(K,E),x.push(K);}for(let R of x){r(`Opening test file ${R}`);let E=fe.readFileSync(R).toString(),K=ps.parseSync(R,E);for(let J of K.module.staticImports){let X=J.moduleRequest.value,$;if(X.startsWith(".")&&(u.subdirectory?$=te.join(p,u.name,X):$=te.join(p,X)),$){let N=new RegExp(`(['"])${os(X)}\\1`,"g");E=E.replaceAll(N,`$1${$}$1`);}}fe.writeFileSync(R,E);}r(`Completed ${A.cyan.bold(C)} test file`),t.verbose||n.stop(`Completed setup for ${A.bold(C)}`);}r("Beginning testing");let d=await detect({cwd:t.cwd});d==null&&program.error(A.red("Could not detect package manager"));let h=resolveCommand(d.agent,"execute",["vitest","run",c$1]);h==null&&program.error(A.red(`Could not resolve add command for '${d.agent}'.`));let y=`${h.command} ${h.args.join(" ")}`;r(`Running ${A.cyan(y)} on ${A.cyan(t.cwd)}`);try{let u=x(h.command,h.args,{nodeOptions:{cwd:t.cwd}});for await(let S of u)process.stdout.write(`${S}
105
+ jsrepo update ${n.components[0]} ${n.components[1]??n.components[0]} ... -y -A`}]}}case "get-component-code":{let o=r.params.arguments,n=await Aa(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "get-config-files":{let o=r.params.arguments,n=await La(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "search-registries":{let o=r.params.arguments,n=await _a(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "cli-reference":{let o=Wa();return {content:[{type:"text",text:JSON.stringify(o)}]}}}throw new Error(`Invalid tool ${r.params.name}`)}catch(o){return console.error(A.red(`Error executing tool ${A.bold(r.params.name)}: ${o}`)),{content:[{type:"text",text:JSON.stringify({error:o instanceof Error?o.message:String(o)})}]}}}),e.setRequestHandler(ListToolsRequestSchema,async()=>(console.error("Received ListToolsRequest"),{tools:[Da,Na,Fa,Ba,Ma]}));let t=new StdioServerTransport;console.error("Connecting server to transport..."),await e.connect(t),console.error("Server connected");}var mo=new Command("mcp").description("Interact with jsrepo through an MCP server.").option("--cwd <path>","The current working directory.",process.cwd()).action(async()=>{await oi().catch(e=>{console.error(e),process.exit(1);});});var za=k.object({private:k.boolean(),dryRun:k.boolean(),name:k.optional(k.string()),ver:k.optional(k.string()),dirs:k.optional(k.array(k.string())),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),verbose:k.boolean(),cwd:k.string()}),uo=new Command("publish").description("Publish a registry to jsrepo.com.").option("--private","When publishing the first version of the registry make it private.",false).option("--dry-run","Test the publish but don't list on jsrepo.com.",false).option("--name <name>","The name of the registry. i.e. @ieedan/std").option("--ver <version>","The version of the registry. i.e. 0.0.1").option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--include-docs","Include documentation files (*.md, *.mdx) in the registry.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(za,e);await ie(),await Ha(t),outro(A.green("All done!"));});async function Ha(e){let t=p=>{e.verbose&&console.info(`${Ee} ${p}`);},r=ve({verbose:e.verbose?t:void 0}),o=Ft(e.cwd).match(p=>{if(p===null)return {$schema:"",access:"public",readme:"README.md",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,includeDocs:e.includeDocs??false};let w=p;return e.private&&(w.access="private"),e.name&&(w.name=e.name),e.ver&&(w.version=e.ver),e.dirs&&(w.dirs=e.dirs),e.doNotListBlocks&&(w.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(w.doNotListCategories=e.doNotListCategories),e.listBlocks&&(w.listBlocks=e.listBlocks),e.listCategories&&(w.listCategories=e.listCategories),e.includeBlocks&&(w.includeBlocks=e.includeBlocks),e.includeCategories&&(w.includeCategories=e.includeCategories),e.excludeBlocks&&(w.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(w.excludeCategories=e.excludeCategories),e.excludeDeps&&(w.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(w.allowSubdirectories=e.allowSubdirectories),e.includeDocs!==void 0&&(w.includeDocs=e.includeDocs),w.rules={...er,...w.rules},w},p=>program.error(A.red(p)));if(e.dryRun&&log.warn(A.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[p,w,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!p.startsWith("@"))throw new Error;if(!p.slice(1).match(v))throw new Error;if(!w.match(v))throw new Error}catch{program.error(A.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`name\` field in the \`jsrepo-build-config.json\``));if(o.version!==void 0){if(o.version==="package"){let w=oe.join(e.cwd,"package.json");fe.existsSync(w)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let{version:x}=JSON.parse(fe.readFileSync(w).toString());o.version=x;}Jo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`version\` field in the \`jsrepo-build-config.json\``));let n=new pe().get("jsrepo");n===void 0&&program.error(A.red(`Please authenticate with ${A.cyan("jsrepo auth")} to publish to ${We}.`));let i=[],s=oa();try{let p=fe.readFileSync(oe.join(e.cwd,".gitignore")).toString();s.add(p);}catch{}s.add(Or);for(let p of o.dirs){let w=oe.join(e.cwd,p);r.start(`Building ${A.cyan(w)}`);let x=Sr(w,{cwd:e.cwd,ignore:s,config:o});for(let R of x){if(i.find(P=>P.name===R.name)!==void 0){console.warn(`${T} ${ce} Skipped adding \`${A.cyan(`${p}/${R.name}`)}\` because a category with the same name already exists!`);continue}i.push(R);}r.stop(`Built ${A.cyan(w)}`);}let a=jr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:f}=Cr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||f.length>0)&&console.log(T);for(let p of l)console.log(p);if(f.length>0){for(let p of f)console.log(p);program.error(A.red(`Completed checking manifest with ${A.bold(`${f.length} error(s)`)} and ${A.bold(`${l.length} warning(s)`)}`));}let[h,m]=Pr(c.categories);c.categories=h,m>0&&log.step(`Removed ${m} unused block${m>1?"s":""}.`),r.start(`Packaging ${A.cyan(c.name)}...`);let b=oe.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${b}`),fe.mkdirSync(b,{recursive:true}),t("Writing manifest to temp dir"),fe.writeFileSync(oe.resolve(b,"jsrepo-manifest.json"),JSON.stringify(c));let d=oe.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),fe.copyFileSync(d,oe.join(b,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let p of c.configFiles){let w=oe.join(e.cwd,p.path),x=oe.join(b,p.path),R=oe.join(x,"../");fe.existsSync(R)||fe.mkdirSync(R,{recursive:true}),fe.copyFileSync(w,x);}t("Copied config files");}t("Copying registry files");for(let p of c.categories)for(let w of p.blocks){let x=oe.join(e.cwd,w.directory),R=oe.join(b,w.directory);for(let P of w.files){let K=oe.join(R,P,"../");fe.existsSync(K)||fe.mkdirSync(K,{recursive:true}),fe.copyFileSync(oe.join(x,P),oe.join(R,P));}}t("Copied registry files");let g=oe.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),y=fe.readdirSync(b);t("Creating archive file"),await ni.create({z:true,cwd:b,file:g},y),t("Created archive file"),t("Removing temp directory"),fe.rmSync(b,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${A.cyan(g)}...`);let u=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${A.cyan(u)}`),r.start(`Publishing ${A.bold(c.name)} to ${We}...`);let S=fe.readFileSync(g);t("Removing archive file"),fe.rmSync(g,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let C=await Re(`${w}/api/publish`,{body:S,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":u},method:"POST"});if(r.stop(`Got response from ${We}.`),C.ok){let p=await C.json();p.status==="dry-run"?log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} published ${A.greenBright(`@${p.scope}`)}/${p.registry}${A.greenBright(`@${p.version}`)}!`);}else {let p=await C.json();C.status===500&&program.error(`${A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${p.message}`)}
106
+ Please try again. If this persists please contact support at ${A.cyan("https://www.jsrepo.com/help")}`),program.error(A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${p.message}`));}}var sc=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),go=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(sc,t);await ie(),await ac(e,r),outro(A.green("All done!"));});async function ac(e,t){let r=u=>{t.verbose&&console.info(`${Ee} ${u}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=be(t.cwd).match(u=>u,u=>program.error(A.red(u))),n=ve({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let u=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(u)||!u)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(u=>u,({repo:u,message:S})=>{n.stop(`Failed to get info for ${A.cyan(u)}`),program.error(A.red(S));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await bt(s,{verbose:t.verbose?r:void 0})).match(u=>u,({repo:u,message:S})=>{n.stop(`Failed fetching blocks from ${A.cyan(u)}`),program.error(A.red(S));});r(`Retrieved blocks from ${A.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`);let c$1=oe.resolve(oe.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${A.bold(c$1)}.`),fe.mkdirSync(c$1,{recursive:true});let l=()=>{fe.rmSync(c$1,{recursive:true,force:true});},f=xt(a,o,t.cwd).map(u=>u.specifier),h=e;e.length===0&&(h=f),h.length===0&&(l(),program.error(A.red("There were no blocks found in your project!")));let m=[];for(let u of h){let S,C=z$1(u);if(C){let{url:p}=C.parse(u,{fullyQualified:true}),w=(await lt(p)).match(R=>R,R=>program.error(A.red(R))),x=(await bt([w])).match(R=>R,R=>program.error(A.red(R)));for(let[R,P]of x)a.set(R,P);S=a.get(u);}else for(let p of i){let w=z$1(p);if(!w)continue;let{url:x,specifier:R}=w.parse(c(p,u),{fullyQualified:true}),P=a.get(c(x,R));if(P!==void 0){S=P;break}}S||program.error(A.red(`Invalid block! ${A.bold(u)} does not exist!`)),m.push({name:u,block:S});}let b=Ue(o.paths,t.cwd).match(u=>u,u=>program.error(A.red(u)));for(let{block:u}of m){let S=u.sourceRepo,C=c(u.sourceRepo.url,u.category,u.name);if(t.verbose||n.start(`Setting up test file for ${A.cyan(C)}`),!u.tests){n.stop(`No tests found for ${A.cyan(C)}`);continue}let p=rr(u,b,t.cwd);p=oe.relative(c$1,p);let w=async R=>{let P=await Ge(S,R);return P.isErr()&&(n.stop(A.red(`Error fetching ${A.bold(R)}`)),program.error(A.red(`There was an error trying to get ${C}`))),P.unwrap()};r(`Downloading and copying test files for ${C}`);let x=[];for(let R of u.files.filter(P=>ct(P))){let P=await w(oe.join(u.directory,R)),K=oe.join(c$1,R);fe.writeFileSync(K,P),x.push(K);}for(let R of x){r(`Opening test file ${R}`);let P=fe.readFileSync(R).toString(),K=ds.parseSync(R,P);for(let J of K.module.staticImports){let X=J.moduleRequest.value,$;if(X.startsWith(".")&&(u.subdirectory?$=oe.join(p,u.name,X):$=oe.join(p,X)),$){let N=new RegExp(`(['"])${rs(X)}\\1`,"g");P=P.replaceAll(N,`$1${$}$1`);}}fe.writeFileSync(R,P);}r(`Completed ${A.cyan.bold(C)} test file`),t.verbose||n.stop(`Completed setup for ${A.bold(C)}`);}r("Beginning testing");let d=await detect({cwd:t.cwd});d==null&&program.error(A.red("Could not detect package manager"));let g=resolveCommand(d.agent,"execute",["vitest","run",c$1]);g==null&&program.error(A.red(`Could not resolve add command for '${d.agent}'.`));let y=`${g.command} ${g.args.join(" ")}`;r(`Running ${A.cyan(y)} on ${A.cyan(t.cwd)}`);try{let u=x(g.command,g.args,{nodeOptions:{cwd:t.cwd}});for await(let S of u)process.stdout.write(`${S}
107
107
  `);l();}catch(u){t.debug?console.info(`${A.bold("--debug")} flag provided. Skipping cleanup. Run '${A.bold(y)}' to retry tests.
108
- `):l(),program.error(A.red(`Tests failed! Error ${u}`));}}var mc=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),qt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),ho=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(qt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(mc,t);await ie(),await uc(e,r),outro(A.green("All done!"));});async function uc(e,t){let r=be(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=qt.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new pe;if(t.logout){if(o!==void 0){if(o==="http"){await ai(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of qt){if(s==="http"){await ai(n);continue}if(n.get(s)===void 0){log.step(A.gray(`Already logged out of ${A.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${A.bold(s)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(s);}return}if(o===void 0){let s=await select({message:"Which service do you want to authenticate to?",options:qt.map(a=>({label:a,value:a})),initialValue:qt[0]});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),o=s,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:qt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let i=o;if(i.startsWith("http")&&(i=i.slice(5)),t.token===void 0){let s=await password({message:`Paste your token for ${A.bold(i)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(s)||!s)&&(cancel("Canceled!"),process.exit(0)),t.token=s;}n.set(o,t.token),log.success(`Logged into ${A.bold(i)}.`);}async function ai(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(A.gray(`Already logged out of ${A.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${A.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var bc=k.object({all:k.boolean(),expand:k.boolean(),maxUnchanged:k.number(),no:k.boolean(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),vo=new Command("update").description("Update blocks to the code in the remote repository.").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",false).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("-n, --no","Do update any blocks.",false).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(bc,t);await ie(),await kc(e,r),outro(A.green("All done!"));});async function kc(e,t){let r=p=>{t.verbose&&console.info(`${Ee} ${p}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=ve({verbose:t.verbose?r:void 0}),n=be(t.cwd).match(p=>p,p=>program.error(A.red(p))),i=n.repos;t.repo&&(i=[t.repo]);for(let p of e)y.find(w=>p.startsWith(w.name))&&program.error(A.red(`Invalid value provided for block names \`${A.bold(p)}\`. Block names are expected to be provided in the format of \`${A.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${A.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(p=>p,({repo:p,message:w})=>{o.stop(`Failed to get info for ${A.cyan(p)}`),program.error(A.red(w));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await _t(s)).match(p=>p,({repo:p,message:w})=>{o.stop(`Failed fetching blocks from ${A.cyan(p)}`),program.error(A.red(w));}),c$1=Bt(a);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`),r(`Retrieved blocks from ${A.cyan(i.join(", "))}`);for(let p of a)Wt(p.state,p.manifest,t.cwd);let l=xt(c$1,n,t.cwd);l.length===0&&program.error(A.red(`You haven't installed any blocks yet. Did you mean to \`${A.bold("add")}\`?`));let f=e;if(t.all&&(f=l.map(p=>p.specifier)),f.length===0){let p=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(w=>w.block.list).map(w=>({label:`${A.cyan(w.block.category)}/${w.block.name}`,value:w.specifier})),required:true});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),f=p;}r(`Preparing to update ${A.cyan(f.join(", "))}`);let g=(await $t(f,c$1,s)).match(p=>p,program.error),m=new Set,b=new Set,{prettierOptions:d,biomeOptions:h}=await Ct({formatter:n.formatter,cwd:t.cwd}),y$1=Ue(n.paths,t.cwd).match(p=>p,p=>program.error(A.red(p))),u=Mt(g,n);for(let p of u){let w=c(p.block.sourceRepo.url,p.block.category,p.block.name),x=sr(p.block.sourceRepo.url);r(`Attempting to update ${w}`),n.includeTests&&p.block.tests&&(r("Trying to include tests"),m.add("vitest"));for(let E of p.block.devDependencies)m.add(E);for(let E of p.block.dependencies)b.add(E);let R=await p.files;process.stdout.write(`${T}
108
+ `):l(),program.error(A.red(`Tests failed! Error ${u}`));}}var mc=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),qt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),ho=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(qt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(mc,t);await ie(),await uc(e,r),outro(A.green("All done!"));});async function uc(e,t){let r=be(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=qt.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new pe;if(t.logout){if(o!==void 0){if(o==="http"){await si(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of qt){if(s==="http"){await si(n);continue}if(n.get(s)===void 0){log.step(A.gray(`Already logged out of ${A.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${A.bold(s)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(s);}return}if(o===void 0){let s=await select({message:"Which service do you want to authenticate to?",options:qt.map(a=>({label:a,value:a})),initialValue:qt[0]});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),o=s,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:qt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let i=o;if(i.startsWith("http")&&(i=i.slice(5)),t.token===void 0){let s=await password({message:`Paste your token for ${A.bold(i)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(s)||!s)&&(cancel("Canceled!"),process.exit(0)),t.token=s;}n.set(o,t.token),log.success(`Logged into ${A.bold(i)}.`);}async function si(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(A.gray(`Already logged out of ${A.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${A.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var bc=k.object({all:k.boolean(),expand:k.boolean(),maxUnchanged:k.number(),no:k.boolean(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),vo=new Command("update").description("Update blocks to the code in the remote repository.").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",false).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("-n, --no","Do update any blocks.",false).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(bc,t);await ie(),await kc(e,r),outro(A.green("All done!"));});async function kc(e,t){let r=p=>{t.verbose&&console.info(`${Ee} ${p}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=ve({verbose:t.verbose?r:void 0}),n=be(t.cwd).match(p=>p,p=>program.error(A.red(p))),i=n.repos;t.repo&&(i=[t.repo]);for(let p of e)y.find(w=>p.startsWith(w.name))&&program.error(A.red(`Invalid value provided for block names \`${A.bold(p)}\`. Block names are expected to be provided in the format of \`${A.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${A.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(p=>p,({repo:p,message:w})=>{o.stop(`Failed to get info for ${A.cyan(p)}`),program.error(A.red(w));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await _t(s)).match(p=>p,({repo:p,message:w})=>{o.stop(`Failed fetching blocks from ${A.cyan(p)}`),program.error(A.red(w));}),c$1=Bt(a);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`),r(`Retrieved blocks from ${A.cyan(i.join(", "))}`);for(let p of a)Wt(p.state,p.manifest,t.cwd);let l=xt(c$1,n,t.cwd);l.length===0&&program.error(A.red(`You haven't installed any blocks yet. Did you mean to \`${A.bold("add")}\`?`));let f=e;if(t.all&&(f=l.map(p=>p.specifier)),f.length===0){let p=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(w=>w.block.list).map(w=>({label:`${A.cyan(w.block.category)}/${w.block.name}`,value:w.specifier})),required:true});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),f=p;}r(`Preparing to update ${A.cyan(f.join(", "))}`);let h=(await $t(f,c$1,s)).match(p=>p,program.error),m=new Set,b=new Set,{prettierOptions:d,biomeOptions:g}=await Ct({formatter:n.formatter,cwd:t.cwd}),y$1=Ue(n.paths,t.cwd).match(p=>p,p=>program.error(A.red(p))),u=Mt(h,n);for(let p of u){let w=c(p.block.sourceRepo.url,p.block.category,p.block.name),x=sr(p.block.sourceRepo.url);r(`Attempting to update ${w}`),n.includeTests&&p.block.tests&&(r("Trying to include tests"),m.add("vitest"));for(let P of p.block.devDependencies)m.add(P);for(let P of p.block.dependencies)b.add(P);let R=await p.files;process.stdout.write(`${T}
109
109
  `),process.stdout.write(`${T} ${w}
110
- `);for(let E of R){let K=E.content.match(v=>v,v=>program.error(A.red(v))),J=nr(E.name,p.block,y$1,t.cwd),X=(await Zt({file:{content:K,destPath:J},biomeOptions:h,prettierOptions:d,config:n,imports:p.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(v=>v,v=>program.error(A.red(v))),$="";fe.existsSync(J)&&($=fe.readFileSync(J).toString());let N=await Nt({config:{biomeOptions:h,prettierOptions:d,formatter:n.formatter},current:{path:J,content:$},incoming:{path:c(w,E.name),content:X},options:{...t,loading:o,verbose:t.verbose?r:void 0}});N.applyChanges&&(o.start(`Writing changes to ${A.cyan(J)}`),fe.writeFileSync(J,N.updatedContent),o.stop(`Wrote changes to ${A.cyan(J)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",C=await et(b,m,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(C.dependencies.size>0||C.devDependencies.size>0){let p=[];if(!C.installed){if(b.size>0){let x=resolveCommand(S,"add",[...b]);p.push(`Install dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(m.size>0){let x=resolveCommand(S,"add",[...m,"-D"]);p.push(`Install dev dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}p=p.map((x,R)=>`${R+1}. ${x}`),C.installed||p.push(""),p.push("Import and use the blocks!");let w=ft(p);process.stdout.write(w);}}var Et=program.name(Dt.name).description(Dt.description).version(Dt.version).addCommand(Xr).addCommand(to).addCommand(ro).addCommand(io).addCommand(so).addCommand(po).addCommand(mo).addCommand(uo).addCommand(go).addCommand(ho).addCommand(vo);Et.parse();//# sourceMappingURL=index.js.map
110
+ `);for(let P of R){let K=P.content.match(v=>v,v=>program.error(A.red(v))),J=nr(P.name,p.block,y$1,t.cwd),X=(await Zt({file:{content:K,destPath:J},biomeOptions:g,prettierOptions:d,config:n,imports:p.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(v=>v,v=>program.error(A.red(v))),$="";fe.existsSync(J)&&($=fe.readFileSync(J).toString());let N=await Nt({config:{biomeOptions:g,prettierOptions:d,formatter:n.formatter},current:{path:J,content:$},incoming:{path:c(w,P.name),content:X},options:{...t,loading:o,verbose:t.verbose?r:void 0}});N.applyChanges&&(o.start(`Writing changes to ${A.cyan(J)}`),fe.writeFileSync(J,N.updatedContent),o.stop(`Wrote changes to ${A.cyan(J)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",C=await et(b,m,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(C.dependencies.size>0||C.devDependencies.size>0){let p=[];if(!C.installed){if(b.size>0){let x=resolveCommand(S,"add",[...b]);p.push(`Install dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(m.size>0){let x=resolveCommand(S,"add",[...m,"-D"]);p.push(`Install dev dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}p=p.map((x,R)=>`${R+1}. ${x}`),C.installed||p.push(""),p.push("Import and use the blocks!");let w=ft(p);process.stdout.write(w);}}var Et=program.name(Dt.name).description(Dt.description).version(Dt.version).addCommand(Xr).addCommand(to).addCommand(ro).addCommand(io).addCommand(so).addCommand(po).addCommand(mo).addCommand(uo).addCommand(go).addCommand(ho).addCommand(vo);Et.parse();//# sourceMappingURL=index.js.map
111
111
  //# sourceMappingURL=index.js.map