jsrepo 2.3.0 → 2.3.2

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,B,A,l}from'./chunk-G2NW2AXL.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import de from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import N from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Z from'pathe';import*as $ from'valibot';import ui 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 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 ps from'oxc-parser';import {walk}from'estree-walker';import*as bn from'svelte/compiler';import*as Cn from'vue/compiler-sfc';import Qs from'node-machine-id';import ra 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 Ot={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.3.0"};var gi=ui(),le=(e,t)=>gi?e:t,So=le("\u25C6","*"),jo=le("\u25C6","*"),Po=le("\u25A0","x"),D=N.gray(le("\u2502","|")),qt=N.gray(le("\u2500","-")),Eo=N.gray(le("\u2510","+")),Io=N.gray(le("\u2518","+")),Ht=N.gray(le("\u251C","+")),Oo=N.gray(le("\u252C","+"));N.gray(le("\u250C","T"));var To=N.gray(le("\u2514","-")),ue=N.bgRgb(245,149,66).black(" WARN "),Pe=N.bgBlueBright.white(" INFO "),Kt=N.bgRedBright.white(" ERROR "),Qe=N.hex("#f7df1e")("jsrepo"),We=N.hex("#f7df1e").bold("jsrepo.com");function fr(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function Do(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 Yt(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 U(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)=>`${Yt(`${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"},Fr={bun:bi,npm:$i,pnpm:Lo,deno:ki,yarn:Bo,"yarn@berry":Bo,"pnpm@6":Lo};function Ve(){return new xi({projectName:"jsrepo"})}var Lr="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(Lr,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(Lr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Lr);return t||[]}};var Mr={"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=Br({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:_r(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=Br({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:_r(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=Br({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:_r(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 Ti({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 Br({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,c,w,m,o,p,x as x$1,y,a,v,u,b,B,A,l}from'./chunk-G2NW2AXL.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import de from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import N from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Z from'pathe';import*as $ from'valibot';import mi 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 yi from'os';import ts from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import zo from'boxen';import {diffLines,diffChars}from'diff';import Vo from'semver';import {cursor,erase}from'sisteransi';import xi from'@anthropic-ai/sdk';import Si from'ollama';import Pi from'openai';import $i from'conf';import Di from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as rn from'css-dependency';import*as on from'prettier';import*as sn from'parse5';import ls from'oxc-parser';import {walk}from'estree-walker';import*as wn from'svelte/compiler';import*as xn from'vue/compiler-sfc';import Ys from'node-machine-id';import ta 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 oi from'tar';var Ot={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.3.2"};var ui=mi(),le=(e,t)=>ui?e:t,Ro=le("\u25C6","*"),jo=le("\u25C6","*"),So=le("\u25A0","x"),D=N.gray(le("\u2502","|")),zt=N.gray(le("\u2500","-")),Po=N.gray(le("\u2510","+")),Eo=N.gray(le("\u2518","+")),Ht=N.gray(le("\u251C","+")),Io=N.gray(le("\u252C","+"));N.gray(le("\u250C","T"));var Oo=N.gray(le("\u2514","-")),ue=N.bgRgb(245,149,66).black(" WARN "),Ee=N.bgBlueBright.white(" INFO "),Kt=N.bgRedBright.white(" ERROR "),Qe=N.hex("#f7df1e")("jsrepo"),We=N.hex("#f7df1e").bold("jsrepo.com");function fr(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 Do(e){let t=0;for(let r of e){let o=stripVTControlCharacters(r);o.length>t&&(t=o.length);}return t}function Yt(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 Ao(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 vi=/\n|\r\n/g;function U(e){return e.split(vi)}function q(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Yt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(yi.EOL)}var wi={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},bi={"install-as-dev-dependency":"-D"},ki={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Fo={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Lo={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Ar={bun:wi,npm:ki,pnpm:Fo,deno:bi,yarn:Lo,"yarn@berry":Lo,"pnpm@6":Fo};function Ve(){return new $i({projectName:"jsrepo"})}var Fr="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(Fr,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(Fr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Fr);return t||[]}};var _r={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await Bo("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Lr({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 Ii({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:Br(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 Bo("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=Lr({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 Ei({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:Br(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=Lr({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 Oi({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Br(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function Ei({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new Pi({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 Ii({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new xi({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 Oi({prompt:e,messages:t,model:r}){return (await Si.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function Lr({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}
@@ -12,78 +12,78 @@ This is the file that has changes I want to update with ${t.path}:
12
12
  <code>
13
13
  ${t.content}
14
14
  </code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
15
- `}}function _r(e){let t=e.trim();if(t.startsWith("```")&&(t=U(t).slice(1).join(`
15
+ `}}function Br(e){let t=e.trim();if(t.startsWith("```")&&(t=U(t).slice(1).join(`
16
16
  `).trim()),t.endsWith("```")){let r=U(t);t=r.slice(0,r.length-1).join(`
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=Ot;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=N.redBright,colorAdded:s=N.greenBright,colorCharsRemoved:a=N.bgRedBright,colorCharsAdded:c=N.bgGreenBright,prefix:l,onUnchanged:f,intro:m}){let h="",b=Do(r,v=>v.count??0).toString().length+1,p=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:m});h+=m({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:m});let u=v=>N.gray(`${l?.()??""}${Yt(`${v+1+p} `,b)} `);for(let v=0;v<r.length;v++){let g=r[v],S=r[v-1]?.added||r[v-1]?.removed,R=r[v+1]?.added||r[v+1]?.removed;if(!g.added&&!g.removed){if(!o&&g.count!==void 0&&g.count>n){let x=p,C=U(Tt(g.value)),j=0;if(R&&(j+=n),S&&(j+=n),j>=C.length){h+=`${z(C,{prefix:u})}
19
- `,p+=C.length;continue}if(S&&(h+=`${z(C.slice(0,n),{prefix:u})}
20
- `),C.length>j){let X=C.length-j;h+=`${z(U(N.gray(`+ ${X} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Yt(" ",b)} `})}
21
- `;}R&&(p=p+C.length-n,h+=`${z(C.slice(C.length-n),{prefix:u})}
22
- `),p=x+g.count;continue}h+=`${z(U(Tt(g.value)),{prefix:u})}
23
- `,p+=g.count??0;continue}let d=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(g.removed&&g.count===1&&r[v+1]?.added&&r[v+1]?.count===1){let C=diffChars(g.value,r[v+1].value).map(j=>w(j)).join("");h+=`${u(0)}${C}`,p+=1,v++;}else Mo(g.value)?(h+=`${z(U(w(g)),{prefix:x=>`${u(x)}${w({removed:true,value:" ",added:false})}`})}
24
- `,g.removed||(p+=g.count??0)):(h+=`${z(U(d(g)),{prefix:u})}
17
+ `).trim();}return t}async function Bo(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=Ot;function _o(e){return /^\s+$/g.test(e)}function Tt(e){let t=e.length-1;for(;_o(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 Mo({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:i=N.redBright,colorAdded:s=N.greenBright,colorCharsRemoved:a=N.bgRedBright,colorCharsAdded:c=N.bgGreenBright,prefix:l,onUnchanged:f,intro:m}){let h="",b=To(r,v=>v.count??0).toString().length+1,p=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:m});h+=m({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:f,intro:m});let u=v=>N.gray(`${l?.()??""}${Yt(`${v+1+p} `,b)} `);for(let v=0;v<r.length;v++){let g=r[v],j=r[v-1]?.added||r[v-1]?.removed,R=r[v+1]?.added||r[v+1]?.removed;if(!g.added&&!g.removed){if(!o&&g.count!==void 0&&g.count>n){let x=p,C=U(Tt(g.value)),S=0;if(R&&(S+=n),j&&(S+=n),S>=C.length){h+=`${q(C,{prefix:u})}
19
+ `,p+=C.length;continue}if(j&&(h+=`${q(C.slice(0,n),{prefix:u})}
20
+ `),C.length>S){let X=C.length-S;h+=`${q(U(N.gray(`+ ${X} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Yt(" ",b)} `})}
21
+ `;}R&&(p=p+C.length-n,h+=`${q(C.slice(C.length-n),{prefix:u})}
22
+ `),p=x+g.count;continue}h+=`${q(U(Tt(g.value)),{prefix:u})}
23
+ `,p+=g.count??0;continue}let d=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(g.removed&&g.count===1&&r[v+1]?.added&&r[v+1]?.count===1){let C=diffChars(g.value,r[v+1].value).map(S=>w(S)).join("");h+=`${u(0)}${C}`,p+=1,v++;}else _o(g.value)?(h+=`${q(U(w(g)),{prefix:x=>`${u(x)}${w({removed:true,value:" ",added:false})}`})}
24
+ `,g.removed||(p+=g.count??0)):(h+=`${q(U(d(g)),{prefix:u})}
25
25
  `,g.removed||(p+=g.count??0));}return h.endsWith(`
26
26
  `)||(h=h+=`
27
- `),h}var ke=Ni.defaults({cachePath:Z.join(import.meta.dirname,"cache")});var Wr="latest-version",Fi=60*60*1e3;async function Vo({noCache:e=false}={}){try{let t=Ve(),r;if(!e){let i=t.get(Wr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Wr);}}let o=await ke("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(Wr,{expiration:Date.now()+Fi,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var Li=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Bi=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Xe(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 Jr(e,t){let r=Z.join(e,"package.json");if(de.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Jr(o.slice(0,o.length-1).join("/"),t)}function Ur(e){if(!de.existsSync(e))return b(`${e} doesn't exist`);let t=de.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function ur(e){return e[0]==="^"?e.slice(1):e}function Go(e,t,{cwd:r}){let o=e,n=t,i=Ur(Z.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=Xe(a).unwrap(),f=s.dependencies[c];if(l===void 0&&f){o.delete(a);continue}f&&Jo.satisfies(ur(f),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Xe(a).unwrap(),f=s.devDependencies[c];if(l===void 0&&f){n.delete(a);continue}f&&Jo.satisfies(ur(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 he({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
- `),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Ht),bottomLeft:stripVTControlCharacters(Ht),topRight:stripVTControlCharacters(Eo),top:stripVTControlCharacters(qt),bottom:stripVTControlCharacters(qt),bottomRight:stripVTControlCharacters(Io),left:stripVTControlCharacters(D),right:stripVTControlCharacters(D)}});return `${D}
27
+ `),h}var $e=Di.defaults({cachePath:Z.join(import.meta.dirname,"cache")});var Mr="latest-version",Ai=60*60*1e3;async function Wo({noCache:e=false}={}){try{let t=Ve(),r;if(!e){let i=t.get(Mr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Mr);}}let o=await $e("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(Mr,{expiration:Date.now()+Ai,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var Fi=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Li=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Xe(e){let t=Fi.exec(e)||Li.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Vr(e,t){let r=Z.join(e,"package.json");if(de.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Vr(o.slice(0,o.length-1).join("/"),t)}function Jr(e){if(!de.existsSync(e))return b(`${e} doesn't exist`);let t=de.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function ur(e){return e[0]==="^"?e.slice(1):e}function Uo(e,t,{cwd:r}){let o=e,n=t,i=Jr(Z.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=Xe(a).unwrap(),f=s.dependencies[c];if(l===void 0&&f){o.delete(a);continue}f&&Vo.satisfies(ur(f),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Xe(a).unwrap(),f=s.devDependencies[c];if(l===void 0&&f){n.delete(a);continue}f&&Vo.satisfies(ur(f),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function Ho(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 Ko({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 he({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=zo(e.join(`
28
+ `),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Ht),bottomLeft:stripVTControlCharacters(Ht),topRight:stripVTControlCharacters(Po),top:stripVTControlCharacters(zt),bottom:stripVTControlCharacters(zt),bottomRight:stripVTControlCharacters(Eo),left:stripVTControlCharacters(D),right:stripVTControlCharacters(D)}});return `${D}
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 Yi(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${N.redBright(t)} -> ${N.greenBright(r)}`,`${N.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${N.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${N.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(`${N.bgHex("#f7df1e").black(` ${Fe.name} `)}${N.gray(` v${Fe.version} `)}`);}var qo="model-preference";async function Dt({incoming:e,current:t,config:r,options:o}){let n=Ve();process.stdout.write(`${D}
32
- `);let i=false,s=e.content,a=n.get(qo,"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:()=>`${D} `,onUnchanged:({from:m,to:h,prefix:b})=>`${b?.()??""}${N.cyan(m)} \u2192 ${N.gray(h)} ${N.gray("(unchanged)")}
30
+ `}function Yo(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 Ki(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${N.redBright(t)} -> ${N.greenBright(r)}`,`${N.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${N.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${N.yellowBright("Star")} on GitHub for updates: https://github.com/jsrepojs/jsrepo`];return zo(i.join(`
31
+ `),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await Wo();e.isOk()&&Vo.lt(Fe.version,e.unwrap())&&console.info(await Ki(Fe.name,Fe.version,e.unwrap())),intro(`${N.bgHex("#f7df1e").black(` ${Fe.name} `)}${N.gray(` v${Fe.version} `)}`);}var qo="model-preference";async function Dt({incoming:e,current:t,config:r,options:o}){let n=Ve();process.stdout.write(`${D}
32
+ `);let i=false,s=e.content,a=n.get(qo,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),f=Mo({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${D} `,onUnchanged:({from:m,to:h,prefix:b})=>`${b?.()??""}${N.cyan(m)} \u2192 ${N.gray(h)} ${N.gray("(unchanged)")}
33
33
  `,intro:({from:m,to:h,changes:b,prefix:p})=>{let u=b.filter(v=>v.added||v.removed).length;return `${p?.()??""}${N.cyan(m)} \u2192 ${N.gray(h)} (${u} change${u===1?"":"s"})
34
34
  ${p?.()??""}
35
- `}});if(process.stdout.write(f),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:m});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let b=await select({message:"Select a model",options:Object.keys(Mr).map(u=>({label:u,value:u})),initialValue:a});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),b!==a&&n.set(qo,b),a=b;let p=await text({message:"Additional instructions:",defaultValue:"None",validate:u=>{if(c.length!==0&&u.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(p)&&(cancel("Canceled!"),process.exit(0));try{let{content:u,prompt:v}=await Mr[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?s:e.content,path:e.path},additionalInstructions:p!=="None"?p:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=u,c.push({role:"user",content:v}),c.push({role:"assistant",content:u});}catch(u){o.loading.stop(),log.error(N.red(`Error getting completions: ${u}`)),process.stdout.write(`${D}
35
+ `}});if(process.stdout.write(f),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:m});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let b=await select({message:"Select a model",options:Object.keys(_r).map(u=>({label:u,value:u})),initialValue:a});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),b!==a&&n.set(qo,b),a=b;let p=await text({message:"Additional instructions:",defaultValue:"None",validate:u=>{if(c.length!==0&&u.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(p)&&(cancel("Canceled!"),process.exit(0));try{let{content:u,prompt:v}=await _r[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?s:e.content,path:e.path},additionalInstructions:p!=="None"?p:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=u,c.push({role:"user",content:v}),c.push({role:"assistant",content:u});}catch(u){o.loading.stop(),log.error(N.red(`Error getting completions: ${u}`)),process.stdout.write(`${D}
36
36
  `);continue}s=await yr({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${D}
37
- `);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function Ze(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 m=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),f=m;}if(f)return a.size>0&&await Gr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Gr({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=N.dim(D),r=N.green(So),o=N.green(jo),n=N.red(Po);process.stdout.write(`${t}
37
+ `);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function Ze(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Uo(e,t,{cwd:n});if(a.size>0||c.size>0){let f=r;if(!r&&!o){let m=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),f=m;}if(f)return a.size>0&&await Ur({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Ur({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 Qo(e){let t=N.dim(D),r=N.green(Ro),o=N.green(jo),n=N.red(So);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,h=s.split(`
40
40
  `).reduce((b,p)=>b+Math.ceil(p.length/f),0)+(l?1:0);process.stdout.write(cursor.up(h)),process.stdout.write(erase.down());},c=(l=0)=>{let f=i.split(`
41
41
  `).slice(-l);s="";for(let m of f)s+=`${t} ${m}
42
42
  `;process.stdout.write(N.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
- `);}}}async function Gr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Fr[e]["install-as-dev-dependency"]);let s=Fr[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(N.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 ${N.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=Z.join(r,"../");return e.replace(es,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths[s],a)})}async function Xt({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)}
44
+ `);}}}async function Ur({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Ar[e]["install-as-dev-dependency"]);let s=Ar[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(N.red(`Could not resolve add command for '${e}'.`));let c=Qo(`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 ${N.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var Zi=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function Zo({template:e,config:t,destPath:r,cwd:o}){let n=Z.join(r,"../");return e.replace(Zi,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths[s],a)})}async function Xt({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 ${N.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 ${N.bold(e.destPath)} ${f}`)}}for(let[f,m]of Object.entries(r)){let h=en({template:m,config:t,destPath:e.destPath,cwd:s}),b=new RegExp(`(['"])${rs(f)}\\1`,"g");l=l.replaceAll(b,`$1${h}$1`);}return a(l)}async function yr({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=Z.dirname(e),o=de.readdirSync(r),n=Z.parse(e);for(let i of o)if(l(i,t)&&Z.parse(i).name===n.name)return Z.join(r,i)}function Nt(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 ${N.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=de.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=Oe({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=>Ie(f)).join(`
47
+ ${l}`),a$1?.(`Formatting ${N.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 ${N.bold(e.destPath)} ${f}`)}}for(let[f,m]of Object.entries(r)){let h=Zo({template:m,config:t,destPath:e.destPath,cwd:s}),b=new RegExp(`(['"])${ts(f)}\\1`,"g");l=l.replaceAll(b,`$1${h}$1`);}return a(l)}async function yr({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 tn(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=Z.dirname(e),o=de.readdirSync(r),n=Z.parse(e);for(let i of o)if(l(i,t)&&Z.parse(i).name===n.name)return Z.join(r,i)}function Nt(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 ${N.bold("tsconfig.json")}: ${r}`)}return a(t)}var nn={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=de.readFileSync(e).toString(),a$1=rn.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Te({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
- ${z(U(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=de.readFileSync(e).toString(),a$1=an.parse(s),c=[],l=(m,h)=>{if(m&&(h(m),m.childNodes&&m.childNodes.length>0))for(let b of m.childNodes)l(b,h);};for(let m of a$1.childNodes)l(m,h=>{if(h.tagName==="script")for(let b of h.attrs)b.name==="src"&&c.push(b.value);if(h.tagName==="link"&&h.attrs.find(b=>b.name==="rel"&&b.value==="stylesheet"))for(let b of h.attrs)b.name==="href"&&!b.value.startsWith("http")&&c.push(b.value);});let f=Oe({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(m=>Ie(m)).join(`
49
+ ${q(U(e),{prefix:()=>" "})}
50
+ */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await on.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 cn={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=de.readFileSync(e).toString(),a$1=sn.parse(s),c=[],l=(m,h)=>{if(m&&(h(m),m.childNodes&&m.childNodes.length>0))for(let b of m.childNodes)l(b,h);};for(let m of a$1.childNodes)l(m,h=>{if(h.tagName==="script")for(let b of h.attrs)b.name==="src"&&c.push(b.value);if(h.tagName==="link"&&h.attrs.find(b=>b.name==="rel"&&b.value==="stylesheet"))for(let b of h.attrs)b.name==="href"&&!b.value.startsWith("http")&&c.push(b.value);});let f=Te({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(m=>Oe(m)).join(`
51
51
  `)):a(f.unwrap())},comment:e=>`<!--
52
- ${z(U(e),{prefix:()=>" "})}
53
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"html",...r}):e};function wr(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 dn={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=de.readFileSync(e).toString(),a$1=wr(e,s),c=Oe({moduleSpecifiers:a$1,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return c.isErr()?b(c.unwrapErr().map(l=>Ie(l)).join(`
52
+ ${q(U(e),{prefix:()=>" "})}
53
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await on.format(e,{parser:"html",...r}):e};function wr(e,t){let r=ls.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=de.readFileSync(e).toString(),a$1=wr(e,s),c=Te({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
- ${z(U(e),{prefix:()=>" "})}
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},br={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=>`/*
57
- ${z(U(e),{prefix:()=>" "})}
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=de.readFileSync(e).toString(),a$1=on.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Oe({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=>Ie(f)).join(`
55
+ ${q(U(e),{prefix:()=>" "})}
56
+ */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await on.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 fn=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await on.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},br={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:fn},mn={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
57
+ ${q(U(e),{prefix:()=>" "})}
58
+ */`,format:fn};var hn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=de.readFileSync(e).toString(),a$1=rn.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Te({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
- ${z(U(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=de.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=m=>{(m.type==="ImportDeclaration"||m.type==="ExportAllDeclaration"||m.type==="ExportNamedDeclaration")&&typeof m.source?.value=="string"&&c.push(m.source.value),m.type==="ImportExpression"&&m.source.type==="Literal"&&typeof m.source.value=="string"&&c.push(m.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let f=Oe({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(m=>Ie(m)).join(`
60
+ ${q(U(e),{prefix:()=>" "})}
61
+ */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await on.format(e,{parser:"scss",...r}):e};var bn={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=de.readFileSync(e).toString(),a$1=wn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=m=>{(m.type==="ImportDeclaration"||m.type==="ExportAllDeclaration"||m.type==="ExportNamedDeclaration")&&typeof m.source?.value=="string"&&c.push(m.source.value),m.type==="ImportExpression"&&m.source.type==="Literal"&&typeof m.source.value=="string"&&c.push(m.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let f=Te({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return f.isErr()?b(f.unwrapErr().map(m=>Oe(m)).join(`
62
62
  `)):a(f.unwrap())},comment:e=>`<!--
63
- ${z(U(e),{prefix:()=>" "})}
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=>`<!--
65
- ${z(U(e),{prefix:()=>" "})}
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=de.readFileSync(e).toString(),a$1=Cn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let f=wr("noop.ts",a$1.descriptor.script.content);c.push(...f);}if(a$1.descriptor.scriptSetup?.content){let f=wr("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...f);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Oe({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(f=>Ie(f)).join(`
63
+ ${q(U(e),{prefix:()=>" "})}
64
+ -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await on.format(e,{filepath:r,...o}):e};var kn={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
65
+ ${q(U(e),{prefix:()=>" "})}
66
+ -->`,format:async e=>e};var Cn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=de.readFileSync(e).toString(),a$1=xn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let f=wr("noop.ts",a$1.descriptor.script.content);c.push(...f);}if(a$1.descriptor.scriptSetup?.content){let f=wr("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...f);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Te({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
- ${z(U(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(U(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await nn.format(e,{parser:"yaml",...r}):e};function Ie(e){return `${z(U(e),{prefix:t=>t===0?`${D} ${Kt} `:`${D} `})}`}function Oe({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 g=In(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(g.isErr()){a$1.push(g.unwrapErr());continue}let S=g.unwrap();S&&(l.add(S.dependency),f[b]=S.template);continue}let p=Xe(b);if(!p.isErr()){let g=p.unwrap();if(En(g.name).validForNewPackages){c.add(b);continue}}let u=vs(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(u.isErr()){a$1.push(u.unwrapErr());continue}let v=u.unwrap();v?(l.add(v.dependency),f[b]=v.template):console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:m,dependencies:h}=ks(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:m,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?Z.join(o,"../"):Z.join(r,"../"),l=Z.join(Z.join(r,"../"),e),f=Z.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(f))return a(Pn(l.slice(f.length),n));let m=Z.resolve(l),h=null;for(let b of s){let p=Z.resolve(Z.join(a$1,b));m.startsWith(p)&&(h===null||h.length<p.length)&&(h=p);}return h!==null?a(Pn(m.slice(h.length+1),n)):b(`${r}:
70
- ${i||e} references code not contained in ${N.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-Z.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=Z.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function vs(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Nt(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 m=bs(f);if(!m)continue;let h=Z.relative(Z.resolve(Z.join(r,"../")),m.prettyPath),b$1=ws(m.prettyPath,m.path,[".js",".ts"]),p=In(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:m.type==="file"});if(p.isErr())return b(p.unwrapErr());if(p.unwrap())return a(p.unwrap());break}}return a(void 0)}function ws(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=Z.parse(e),n=Z.parse(t),i=Z.join(o.dir,o.name),s=Z.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function bs(e){if(de.existsSync(e))return {path:e,prettyPath:e,type:de.statSync(e).isDirectory()?"directory":"file"};let t=Z.join(e,"../");if(!de.existsSync(t))return;let r=Z.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(de.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=de.readdirSync(t);for(let n of o){let i=Z.parse(n);if(i.name===r.base){let s=Z.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:de.statSync(s).isDirectory()?"directory":"file"}}}}function ks(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Jr(Z.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(de.readFileSync(n,"utf-8"));for(let l of e){let f=Xe(l);if(f.isErr()){console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let m=f.unwrap();if(!En(m.name).validForNewPackages){console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(m.name))continue;let h;if(c!==void 0&&(h=c[m.name]),h!==void 0){i.add(`${m.name}@${h}`);continue}if(a!==void 0&&(h=a[m.name]),h!==void 0){s.add(`${m.name}@${h}`);continue}i.add(m.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ut=[sn,ln,br,un,yn,kn,$n,dn,Rn,jn];var Tn=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=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),xs=$.union([$.literal("no-category-index-file-dependency"),$.literal("no-unpinned-dependency"),$.literal("require-local-dependency-exists"),$.literal("max-local-dependencies"),$.literal("no-circular-dependency"),$.literal("no-unused-block"),$.literal("no-framework-dependency"),$.literal("require-config-file-exists"),$.literal("no-config-file-framework-dependency"),$.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 ${N.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=`${N.bold(`${e.category}/${e.name}`)} depends on local dependency ${N.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(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.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(`${N.bold(`${e.category}/${e.name}`)} has too many local dependencies (${N.bold(e.localDependencies.length)}) limit (${N.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=$r(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${N.bold(o)}: ${N.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($r(r,n,t.categories))return;return [`${N.bold(r)} is unused and will be ${N.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=>Xe(o).unwrap().name).filter(o=>Tn.has(o));if(r.length>0)for(let o of r)t.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.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)de.existsSync(Z.join(t,o.path))||r.push(`The ${N.bold(o.name)} config file doesn't exist at ${N.bold(Z.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=>Xe(n).unwrap().name).filter(n=>Tn.has(n));if(o.length>0)for(let n of o)t.push(`${N.bold(r.name)} depends on ${N.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 ${N.bold(o)}`);return t.length>0?t:void 0}}}},An=$.record(xs,$.union([Dn,$.tupleWithRest([Dn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),Zt={"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 xr(e,t,r,o=Zt){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 m=a.check({manifest:e,options:f,cwd:r,config:t});if(m){if(l==="error"){i.push(...m.map(h=>`${D} ${Kt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...m.map(h=>`${D} ${ue} ${h} ${N.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],m,h=[];if(Array.isArray(f)?(m=f[0],h.push(...f.slice(1))):m=f,m==="off")continue;let b=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(b){if(m==="error"){i.push(...b.map(p=>`${D} ${Kt} ${N.red(p)} ${N.gray(c)}`));continue}n.push(...b.map(p=>`${D} ${ue} ${p} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function $r(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=$r(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($r(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"];function ct(e){return Mn.find(t=>e.endsWith(t))!==void 0}function Cr(e,{cwd:t,ignore:r,config:o}){let n;try{n=de.readdirSync(e);}catch{program.error(N.red(`Couldn't read the ${N.bold(e)} directory.`));}let i=[];for(let s of n){let a=Z.join(e,s);if(de.statSync(a).isFile())continue;let c=`${Z.relative(t,a)}/`;if(r.ignores(c))continue;let l=Z.basename(s);if(!Rs(l,o))continue;let f=Cs(l,o),m={name:l,blocks:[]},h=de.readdirSync(a);for(let b of h){let p=Z.join(a,b);if(de.statSync(p).isFile()){if(ct(b))continue;let u=Ss(b),v=Ln(u,o);if(!Bn(u,o))continue;let g=ut.find(j=>j.matches(b));if(!g){console.warn(`${D} ${ue} Skipped \`${N.bold(p)}\` \`*${N.bold(Z.parse(b).ext)}\` files are not currently supported!`);continue}let S=h.find(j=>Mn.find(X=>j===`${u}${X}`)),{dependencies:R,devDependencies:d,local:w,imports:x}=g.resolveDependencies({filePath:p,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(j=>j,j=>{program.error(N.red(j));}),C={name:u,directory:Z.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:f?v:false,files:[b],localDependencies:w,_imports_:x,dependencies:R,devDependencies:d};S!==void 0&&C.files.push(S),m.blocks.push(C);}else {let u=b,v=Ln(u,o);if(!Bn(u,o))continue;let g=new Set,S=new Set,R=new Set,d={},w=false,x=[],C=(X,oe)=>{for(let Y of oe){let k=Z.join(X,Y),A=k.slice(p.length+1);if(ct(Y)){w=true,x.push(A);continue}if(de.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${D} ${ue} Skipped \`${N.bold(Z.join(p,Y))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let J=de.readdirSync(k);C(k,J);continue}let y=ut.find(J=>J.matches(Y));if(!y){console.warn(`${D} ${ue} Skipped \`${k}\` \`*${N.bold(Z.parse(Y).ext)}\` files are not currently supported!`);continue}let{local:W,dependencies:P,devDependencies:V,imports:te}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:p,filePath:k,cwd:t}).match(J=>J,J=>{program.error(N.red(J));});for(let J of W)J!==`${l}/${u}`&&g.add(J);for(let J of P)S.add(J);for(let J of V)R.add(J);for(let[J,nt]of Object.entries(te))d[J]=nt;x.push(A);}};C(p,de.readdirSync(p));let j={name:u,directory:Z.relative(t,p),category:l,tests:w,subdirectory:true,list:f?v:false,files:x,localDependencies:Array.from(g.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(R.keys()),_imports_:d};m.blocks.push(j);}}i.push(m);}return i}function Rr(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:Z.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(N.red(c));});a.length>0&&program.error(N.red(`${N.bold(o.name)} ${N.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 Cs(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function Rs(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function Ss(e){return Z.parse(Z.basename(e)).name}function Sr(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 Er=[".git","node_modules"],yt="jsrepo.json",vt="jsrepo-build-config.json",qr=$.union([$.literal("prettier"),$.literal("biome")]),Ps=$.objectWithRest({"*":$.string()},$.string()),Hr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:Ps,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(qr)});function Te(e){if(!de.existsSync(Z.join(e,yt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(Hr,JSON.parse(de.readFileSync(Z.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}var Es=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),access:$.optional(j),meta:$.optional(f),defaultPaths:$.optional($.record($.string(),$.string())),peerDependencies:$.optional(g),configFiles:$.optional($.array(h)),dirs:$.array($.string()),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string()),[]),includeCategories:$.optional($.array($.string()),[]),excludeBlocks:$.optional($.array($.string()),[]),excludeCategories:$.optional($.array($.string()),[]),doNotListBlocks:$.optional($.array($.string()),[]),doNotListCategories:$.optional($.array($.string()),[]),listBlocks:$.optional($.array($.string()),[]),listCategories:$.optional($.array($.string()),[]),excludeDeps:$.optional($.array($.string()),[]),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),rules:$.optional(An)});function At(e){if(!de.existsSync(Z.join(e,vt)))return a(null);let t=$.safeParse(Es,JSON.parse(de.readFileSync(Z.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=Nt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=Z.relative(t,Z.join(Z.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${N.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 ${N.bold("`./`")}.`);let a=Is(s,o,t);if(!a)return b(`Cannot resolve ${N.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 ${N.bold("`./`")}.`);n[i]=a;}return a(n)}function Is(e,t,r){let o=t(e);return o.length>0?Z.relative(r,o[0]):void 0}function tr(e,t,r){let o;return t[e.category]!==void 0?o=Z.join(r,t[e.category]):o=Z.join(r,t["*"],e.category),o}async function Ge(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:ke,token:Kr(e.provider,e.url)})}async function Ft(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:ke,token:Kr(e.provider,e.url)})}function Kr(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:Kr(r,n.url),fetch:ke});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 ":""}${N.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function ze(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 Ft(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 Lt(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 Bt(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Ft(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(N.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${N.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:f,specifier:m}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(f,m));if(h!==void 0){s=h;break}}}if(!s)return b(`Invalid block! ${N.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(fr(n,(i,s)=>s))}function xt(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=tr(s,n,r),c=Z.join(a,s.files[0]);s.subdirectory&&(c=Z.join(a,s.name)),de.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function _t(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>ct(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await Ge(o.sourceRepo,Z.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function or(e,t,r,o){let n=tr(t,r,o);return t.subdirectory?Z.join(n,t.name,e):Z.join(n,e)}function nr(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(Z.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Z.join(t,"biome.json");de.existsSync(n)&&(o=JSON.parse(de.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function ir(e){return `Installed from ${e}`}function Mt(e,t,r){if(!t.peerDependencies)return;let o=Ur(Z.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${N.bold("package.json")}. Please create one.`),program.error(N.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(ur(f),c)||i.push({name:s,expected:c,message:l,version:f,exists:true});}if(i.length>0){process.stdout.write(`${D}
71
- ${N.yellow("\u25B2")} ${Oo} Issues with ${N.bold(e.url)} peer dependencies
72
- `);let s=i.map((a,c)=>{let l=i.length-1===c,f;a.exists?f=`${N.yellowBright("x unmet peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)} >> found ${N.yellowBright.bold(a.version)}`:f=`${N.red("x missing peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)}`;let m=`${D} ${l?To:Ht}${qt} ${f}`;return a.message?`${m}
68
+ ${q(U(e),{prefix:()=>" "})}
69
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await on.format(e,{parser:"vue",...r}):e};var jn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>q(U(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await on.format(e,{parser:"yaml",...r}):e};function Oe(e){return `${q(U(e),{prefix:t=>t===0?`${D} ${Kt} `:`${D} `})}`}function Te({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 g=En(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(g.isErr()){a$1.push(g.unwrapErr());continue}let j=g.unwrap();j&&(l.add(j.dependency),f[b]=j.template);continue}let p=Xe(b);if(!p.isErr()){let g=p.unwrap();if(Pn(g.name).validForNewPackages){c.add(b);continue}}let u=ys(b,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(u.isErr()){a$1.push(u.unwrapErr());continue}let v=u.unwrap();v?(l.add(v.dependency),f[b]=v.template):console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(b)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:m,dependencies:h}=bs(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:m,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=t?Z.join(o,"../"):Z.join(r,"../"),l=Z.join(Z.join(r,"../"),e),f=Z.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(f))return a(Sn(l.slice(f.length),n));let m=Z.resolve(l),h=null;for(let b of s){let p=Z.resolve(Z.join(a$1,b));m.startsWith(p)&&(h===null||h.length<p.length)&&(h=p);}return h!==null?a(Sn(m.slice(h.length+1),n)):b(`${r}:
70
+ ${i||e} references code not contained in ${N.bold(s.join(", "))} and cannot be resolved.`)}function Sn(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-Z.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=Z.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function ys(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Nt(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 m=ws(f);if(!m)continue;let h=Z.relative(Z.resolve(Z.join(r,"../")),m.prettyPath),b$1=vs(m.prettyPath,m.path,[".js",".ts"]),p=En(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:b$1,dirs:o,cwd:n,modIsFile:m.type==="file"});if(p.isErr())return b(p.unwrapErr());if(p.unwrap())return a(p.unwrap());break}}return a(void 0)}function vs(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=Z.parse(e),n=Z.parse(t),i=Z.join(o.dir,o.name),s=Z.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function ws(e){if(de.existsSync(e))return {path:e,prettyPath:e,type:de.statSync(e).isDirectory()?"directory":"file"};let t=Z.join(e,"../");if(!de.existsSync(t))return;let r=Z.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(de.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=de.readdirSync(t);for(let n of o){let i=Z.parse(n);if(i.name===r.base){let s=Z.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:de.statSync(s).isDirectory()?"directory":"file"}}}}function bs(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Vr(Z.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(de.readFileSync(n,"utf-8"));for(let l of e){let f=Xe(l);if(f.isErr()){console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let m=f.unwrap();if(!Pn(m.name).validForNewPackages){console.warn(`${D} ${ue} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(m.name))continue;let h;if(c!==void 0&&(h=c[m.name]),h!==void 0){i.add(`${m.name}@${h}`);continue}if(a!==void 0&&(h=a[m.name]),h!==void 0){s.add(`${m.name}@${h}`);continue}i.add(m.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ut=[nn,cn,br,mn,hn,bn,kn,pn,Cn,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"]),Tn=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),$s=$.union([$.literal("no-category-index-file-dependency"),$.literal("no-unpinned-dependency"),$.literal("require-local-dependency-exists"),$.literal("max-local-dependencies"),$.literal("no-circular-dependency"),$.literal("no-unused-block"),$.literal("no-framework-dependency"),$.literal("require-config-file-exists"),$.literal("no-config-file-framework-dependency"),$.literal("no-config-file-unpinned-dependency")]),Dn={"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 ${N.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=`${N.bold(`${e.category}/${e.name}`)} depends on local dependency ${N.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(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.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(`${N.bold(`${e.category}/${e.name}`)} has too many local dependencies (${N.bold(e.localDependencies.length)}) limit (${N.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=$r(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${N.bold(o)}: ${N.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($r(r,n,t.categories))return;return [`${N.bold(r)} is unused and will be ${N.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=>Xe(o).unwrap().name).filter(o=>On.has(o));if(r.length>0)for(let o of r)t.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.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)de.existsSync(Z.join(t,o.path))||r.push(`The ${N.bold(o.name)} config file doesn't exist at ${N.bold(Z.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=>Xe(n).unwrap().name).filter(n=>On.has(n));if(o.length>0)for(let n of o)t.push(`${N.bold(r.name)} depends on ${N.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 ${N.bold(o)}`);return t.length>0?t:void 0}}}},Nn=$.record($s,$.union([Tn,$.tupleWithRest([Tn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),Zt={"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 xr(e,t,r,o=Zt){let n=[],i=[];for(let[s,a]of Object.entries(Dn)){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 m=a.check({manifest:e,options:f,cwd:r,config:t});if(m){if(l==="error"){i.push(...m.map(h=>`${D} ${Kt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...m.map(h=>`${D} ${ue} ${h} ${N.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(Dn)){if(l.scope==="global")continue;let f=o[c],m,h=[];if(Array.isArray(f)?(m=f[0],h.push(...f.slice(1))):m=f,m==="off")continue;let b=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(b){if(m==="error"){i.push(...b.map(p=>`${D} ${Kt} ${N.red(p)} ${N.gray(c)}`));continue}n.push(...b.map(p=>`${D} ${ue} ${p} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function $r(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=$r(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($r(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"];function ct(e){return _n.find(t=>e.endsWith(t))!==void 0}function Cr(e,{cwd:t,ignore:r,config:o}){let n;try{n=de.readdirSync(e);}catch{program.error(N.red(`Couldn't read the ${N.bold(e)} directory.`));}let i=[];for(let s of n){let a=Z.join(e,s);if(de.statSync(a).isFile())continue;let c=`${Z.relative(t,a)}/`;if(r.ignores(c))continue;let l=Z.basename(s);if(!Cs(l,o))continue;let f=xs(l,o),m={name:l,blocks:[]},h=de.readdirSync(a);for(let b of h){let p=Z.join(a,b);if(de.statSync(p).isFile()){if(ct(b))continue;let u=Rs(b),v=Fn(u,o);if(!Ln(u,o))continue;let g=ut.find(S=>S.matches(b));if(!g){console.warn(`${D} ${ue} Skipped \`${N.bold(p)}\` \`*${N.bold(Z.parse(b).ext)}\` files are not currently supported!`);continue}let j=h.find(S=>_n.find(X=>S===`${u}${X}`)),{dependencies:R,devDependencies:d,local:w,imports:x}=g.resolveDependencies({filePath:p,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(S=>S,S=>{program.error(N.red(S));}),C={name:u,directory:Z.relative(t,a),category:l,tests:j!==void 0,subdirectory:false,list:f?v:false,files:[b],localDependencies:w,_imports_:x,dependencies:R,devDependencies:d};j!==void 0&&C.files.push(j),m.blocks.push(C);}else {let u=b,v=Fn(u,o);if(!Ln(u,o))continue;let g=new Set,j=new Set,R=new Set,d={},w=false,x=[],C=(X,oe)=>{for(let Y of oe){let k=Z.join(X,Y),A=k.slice(p.length+1);if(ct(Y)){w=true,x.push(A);continue}if(de.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${D} ${ue} Skipped \`${N.bold(Z.join(p,Y))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let J=de.readdirSync(k);C(k,J);continue}let y=ut.find(J=>J.matches(Y));if(!y){console.warn(`${D} ${ue} Skipped \`${k}\` \`*${N.bold(Z.parse(Y).ext)}\` files are not currently supported!`);continue}let{local:W,dependencies:P,devDependencies:V,imports:te}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:p,filePath:k,cwd:t}).match(J=>J,J=>{program.error(N.red(J));});for(let J of W)J!==`${l}/${u}`&&g.add(J);for(let J of P)j.add(J);for(let J of V)R.add(J);for(let[J,nt]of Object.entries(te))d[J]=nt;x.push(A);}};C(p,de.readdirSync(p));let S={name:u,directory:Z.relative(t,p),category:l,tests:w,subdirectory:true,list:f?v:false,files:x,localDependencies:Array.from(g.keys()),dependencies:Array.from(j.keys()),devDependencies:Array.from(R.keys()),_imports_:d};m.blocks.push(S);}}i.push(m);}return i}function Rr(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:Z.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(N.red(c));});a.length>0&&program.error(N.red(`${N.bold(o.name)} ${N.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 xs(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function Cs(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function Rs(e){return Z.parse(Z.basename(e)).name}function jr(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 Er=[".git","node_modules"],yt="jsrepo.json",vt="jsrepo-build-config.json",qr=$.union([$.literal("prettier"),$.literal("biome")]),Ss=$.objectWithRest({"*":$.string()},$.string()),zr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:Ss,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(qr)});function ye(e){if(!de.existsSync(Z.join(e,yt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(zr,JSON.parse(de.readFileSync(Z.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}var Ps=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),access:$.optional(j),meta:$.optional(f),defaultPaths:$.optional($.record($.string(),$.string())),peerDependencies:$.optional(g),configFiles:$.optional($.array(h)),dirs:$.array($.string()),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string()),[]),includeCategories:$.optional($.array($.string()),[]),excludeBlocks:$.optional($.array($.string()),[]),excludeCategories:$.optional($.array($.string()),[]),doNotListBlocks:$.optional($.array($.string()),[]),doNotListCategories:$.optional($.array($.string()),[]),listBlocks:$.optional($.array($.string()),[]),listCategories:$.optional($.array($.string()),[]),excludeDeps:$.optional($.array($.string()),[]),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),rules:$.optional(Nn)});function At(e){if(!de.existsSync(Z.join(e,vt)))return a(null);let t=$.safeParse(Ps,JSON.parse(de.readFileSync(Z.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=Nt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=Z.relative(t,Z.join(Z.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${N.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 ${N.bold("`./`")}.`);let a=Es(s,o,t);if(!a)return b(`Cannot resolve ${N.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 ${N.bold("`./`")}.`);n[i]=a;}return a(n)}function Es(e,t,r){let o=t(e);return o.length>0?Z.relative(r,o[0]):void 0}function tr(e,t,r){let o;return t[e.category]!==void 0?o=Z.join(r,t[e.category]):o=Z.join(r,t["*"],e.category),o}async function Ge(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:$e,token:Hr(e.provider,e.url)})}async function Ft(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:$e,token:Hr(e.provider,e.url)})}function Hr(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(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:Hr(r,n.url),fetch:$e});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 ":""}${N.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 Ft(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 Lt(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 Bt(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Ft(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(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(N.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${N.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:f,specifier:m}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(f,m));if(h!==void 0){s=h;break}}}if(!s)return b(`Invalid block! ${N.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(fr(n,(i,s)=>s))}function xt(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=tr(s,n,r),c=Z.join(a,s.files[0]);s.subdirectory&&(c=Z.join(a,s.name)),de.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function _t(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>ct(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await Ge(o.sourceRepo,Z.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function or(e,t,r,o){let n=tr(t,r,o);return t.subdirectory?Z.join(n,t.name,e):Z.join(n,e)}function nr(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 Mn(e){return new Promise(t=>t(e))}async function Ct({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await on.resolveConfig(Z.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Z.join(t,"biome.json");de.existsSync(n)&&(o=JSON.parse(de.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function ir(e){return `Installed from ${e}`}function Mt(e,t,r){if(!t.peerDependencies)return;let o=Jr(Z.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${N.bold("package.json")}. Please create one.`),program.error(N.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}Vo.satisfies(ur(f),c)||i.push({name:s,expected:c,message:l,version:f,exists:true});}if(i.length>0){process.stdout.write(`${D}
71
+ ${N.yellow("\u25B2")} ${Io} Issues with ${N.bold(e.url)} peer dependencies
72
+ `);let s=i.map((a,c)=>{let l=i.length-1===c,f;a.exists?f=`${N.yellowBright("x unmet peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)} >> found ${N.yellowBright.bold(a.version)}`:f=`${N.red("x missing peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)}`;let m=`${D} ${l?Oo:Ht}${zt} ${f}`;return a.message?`${m}
73
73
  ${D} ${l?"":D} ${N.gray(a.message)}`:m}).join(`
74
74
  `);process.stdout.write(`${s}
75
- `);}}var Us=$.object({watermark:$.optional($.boolean()),tests:$.optional($.boolean()),formatter:$.optional($.union([$.literal("prettier"),$.literal("biome"),$.literal("none")])),paths:$.optional($.record($.string(),$.string())),expand:$.boolean(),maxUnchanged:$.number(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.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")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",nr,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=$.parse(Us,t);await ie(),await Gs(e,r),outro(N.green("All done!"));});async function Gs(e,t){let r=k=>{t.verbose&&console.info(`${Pe} ${k}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Te(t.cwd),i=n.isErr(),s;if(n.isErr()){let k=t.yes;if(!t.yes){let A=await confirm({message:`You don't have ${Qe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),k=A;}k||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests: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.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 k of e){let A=z$1(k);if(!A){l=true;continue}let{url:y}=A.parse(k,{fullyQualified:true});if(!(!s.repos.find(P=>P===y)&&!c$1.has(y))){if(!t.allow){let P=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(P)||!P)&&(cancel("Canceled!"),process.exit(0));}a.push(y);}c$1.add(y);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let k=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(k)||!k)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(N.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${N.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(a.join(", "))}`);let f=(await ze(a,{noCache:!t.cache})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed to get info for ${N.cyan(k)}`),program.error(N.red(A));});r(`Resolved ${N.cyan(a.join(", "))}`),r(`Fetching blocks from ${N.cyan(a.join(", "))}`);let m=(await Bt(f,{verbose:t.verbose?r:void 0})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed fetching blocks from ${N.cyan(k)}`),program.error(N.red(A));}),h=Lt(m);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(a.join(", "))}`),r(`Retrieved blocks from ${N.cyan(a.join(", "))}`);for(let k of m)Mt(k.state,k.manifest,t.cwd);let b=xt(h,s,t.cwd).map(k=>k.specifier),p=e;if(p.length===0){let k=await multiselect({message:"Select which blocks to add.",options:Array.from(h.entries()).filter(([A,y])=>y.list).map(([A,y])=>{let W=`${y.category}/${y.name}`,P=b.findIndex(te=>te===W)!==-1,V;return a.length>1?V=`${N.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:V=`${N.cyan(y.category)}/${y.name}`,{label:P?N.gray(V):V,value:A,hint:P?"Installed":void 0}}),required:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),p=k;}r(`Installing blocks ${N.cyan(p.join(", "))}`);let u=(await $t(p,h,f)).match(k=>k,k=>program.error(k)),v=new Set,g=new Set,S=Ve();if(i){let k=`${t.cwd}-zero-config`,A=$.safeParse(Hr,S.get(k)),y=A.success?A.output:s,W=Array.from(new Set(u.map(P=>P.category)));if(t.paths===void 0)for(let P of W){let V=await text({message:`Where would you like to add ${N.cyan(P)}?`,placeholder:y?y.paths[P]:`./src/${P}`,initialValue:y?y.paths[P]:`./src/${P}`,defaultValue:y?y.paths[P]:`./src/${P}`,validate(te){if(te.trim()==="")return "Please provide a value"}});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),s.paths[P]=V;}if(!t.yes&&t.tests===void 0){let P=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=P;}if(!t.yes&&t.watermark===void 0){let P=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.watermark=P;}if(t.formatter===void 0){let P="none";de.existsSync(Z.join(t.cwd,".prettierrc"))&&(P="prettier"),de.existsSync(Z.join(t.cwd,"biome.json"))&&(P="biome");let V=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(te=>({value:te.toLowerCase(),label:te})),initialValue:P==="none"?y.formatter?y.formatter:"none":P});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),V!=="none"&&(s.formatter=V);}S.set(k,s),b=xt(h,s,t.cwd).map(P=>P.specifier);}let{prettierOptions:R,biomeOptions:d}=await Ct({formatter:s.formatter,cwd:t.cwd}),w=Ue(s.paths,t.cwd).match(k=>k,k=>program.error(N.red(k))),x=new Set,C,j=_t(u,s),X=[];for(let k of j){let A=c(k.block.sourceRepo.url,k.block.category,k.block.name),y=`${k.block.category}/${k.block.name}`;r(`Setting up ${A}`);let W=b.find(P=>y===P);s.includeTests&&k.block.tests&&(r("Trying to include tests"),v.add("vitest"));for(let P of k.block.devDependencies)v.add(P);for(let P of k.block.dependencies)g.add(P);if(W&&!t.yes&&!C){if(C===void 0){let P=u.map(te=>`${te.category}/${te.name}`).filter(te=>b.find(J=>J===te));log.warn(`The following components ${N.bold.yellow("already exist")}: ${N.cyan(Qo(P))}`);let V=await confirm({message:`Would you like to ${N.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),C=V;}if(!C){let P=await k.files;process.stdout.write(`${D}
75
+ `);}}var Js=$.object({watermark:$.optional($.boolean()),tests:$.optional($.boolean()),formatter:$.optional($.union([$.literal("prettier"),$.literal("biome"),$.literal("none")])),paths:$.optional($.record($.string(),$.string())),expand:$.boolean(),maxUnchanged:$.number(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Qr=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")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",nr,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=$.parse(Js,t);await ie(),await Us(e,r),outro(N.green("All done!"));});async function Us(e,t){let r=k=>{t.verbose&&console.info(`${Ee} ${k}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=ye(t.cwd),i=n.isErr(),s;if(n.isErr()){let k=t.yes;if(!t.yes){let A=await confirm({message:`You don't have ${Qe} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),k=A;}k||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests: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.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 k of e){let A=z(k);if(!A){l=true;continue}let{url:y}=A.parse(k,{fullyQualified:true});if(!(!s.repos.find(P=>P===y)&&!c$1.has(y))){if(!t.allow){let P=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(P)||!P)&&(cancel("Canceled!"),process.exit(0));}a.push(y);}c$1.add(y);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let k=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(k)||!k)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(N.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${N.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(a.join(", "))}`);let f=(await qe(a,{noCache:!t.cache})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed to get info for ${N.cyan(k)}`),program.error(N.red(A));});r(`Resolved ${N.cyan(a.join(", "))}`),r(`Fetching blocks from ${N.cyan(a.join(", "))}`);let m=(await Bt(f,{verbose:t.verbose?r:void 0})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed fetching blocks from ${N.cyan(k)}`),program.error(N.red(A));}),h=Lt(m);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(a.join(", "))}`),r(`Retrieved blocks from ${N.cyan(a.join(", "))}`);for(let k of m)Mt(k.state,k.manifest,t.cwd);let b=xt(h,s,t.cwd).map(k=>k.specifier),p=e;if(p.length===0){let k=await multiselect({message:"Select which blocks to add.",options:Array.from(h.entries()).filter(([A,y])=>y.list).map(([A,y])=>{let W=`${y.category}/${y.name}`,P=b.findIndex(te=>te===W)!==-1,V;return a.length>1?V=`${N.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:V=`${N.cyan(y.category)}/${y.name}`,{label:P?N.gray(V):V,value:A,hint:P?"Installed":void 0}}),required:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),p=k;}r(`Installing blocks ${N.cyan(p.join(", "))}`);let u=(await $t(p,h,f)).match(k=>k,k=>program.error(k)),v=new Set,g=new Set,j=Ve();if(i){let k=`${t.cwd}-zero-config`,A=$.safeParse(zr,j.get(k)),y=A.success?A.output:s,W=Array.from(new Set(u.map(P=>P.category)));if(t.paths===void 0)for(let P of W){let V=await text({message:`Where would you like to add ${N.cyan(P)}?`,placeholder:y?y.paths[P]:`./src/${P}`,initialValue:y?y.paths[P]:`./src/${P}`,defaultValue:y?y.paths[P]:`./src/${P}`,validate(te){if(te.trim()==="")return "Please provide a value"}});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),s.paths[P]=V;}if(!t.yes&&t.tests===void 0){let P=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=P;}if(!t.yes&&t.watermark===void 0){let P=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.watermark=P;}if(t.formatter===void 0){let P="none";de.existsSync(Z.join(t.cwd,".prettierrc"))&&(P="prettier"),de.existsSync(Z.join(t.cwd,"biome.json"))&&(P="biome");let V=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(te=>({value:te.toLowerCase(),label:te})),initialValue:P==="none"?y.formatter?y.formatter:"none":P});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),V!=="none"&&(s.formatter=V);}j.set(k,s),b=xt(h,s,t.cwd).map(P=>P.specifier);}let{prettierOptions:R,biomeOptions:d}=await Ct({formatter:s.formatter,cwd:t.cwd}),w=Ue(s.paths,t.cwd).match(k=>k,k=>program.error(N.red(k))),x=new Set,C,S=_t(u,s),X=[];for(let k of S){let A=c(k.block.sourceRepo.url,k.block.category,k.block.name),y=`${k.block.category}/${k.block.name}`;r(`Setting up ${A}`);let W=b.find(P=>y===P);s.includeTests&&k.block.tests&&(r("Trying to include tests"),v.add("vitest"));for(let P of k.block.devDependencies)v.add(P);for(let P of k.block.dependencies)g.add(P);if(W&&!t.yes&&!C){if(C===void 0){let P=u.map(te=>`${te.category}/${te.name}`).filter(te=>b.find(J=>J===te));log.warn(`The following components ${N.bold.yellow("already exist")}: ${N.cyan(Yo(P))}`);let V=await confirm({message:`Would you like to ${N.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(V)&&(cancel("Canceled!"),process.exit(0)),C=V;}if(!C){let P=await k.files;process.stdout.write(`${D}
76
76
  `),process.stdout.write(`${D} ${A}
77
- `);for(let V of P){let te=V.content.match(je=>je,je=>program.error(N.red(je))),J=or(V.name,k.block,w,t.cwd),nt=(await Xt({file:{content:te,destPath:J},biomeOptions:d,prettierOptions:R,config:s,imports:k.block._imports_,watermark:ir(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(je=>je,je=>program.error(N.red(je))),Se="";de.existsSync(J)&&(Se=de.readFileSync(J).toString());let re=await Dt({config:{biomeOptions:d,prettierOptions:R,formatter:s.formatter},current:{path:J,content:Se},incoming:{path:c(A,V.name),content:nt},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});re.applyChanges&&(X.push(Wn({destination:J,content:re.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(P=>{P.map(async V=>{let te=V.content.match(Se=>Se,Se=>program.error(N.red(Se))),J=or(V.name,k.block,w,t.cwd),nt=Xt({file:{content:te,destPath:J},biomeOptions:d,prettierOptions:R,config:s,imports:k.block._imports_,watermark:ir(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Se=>(Se.isErr()&&program.error(N.red(Se.unwrapErr())),{destination:J,content:Se.unwrap(),block:k.block}));X.push(nt);});}),x.add(y);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(j.map(k=>k.files)),await Promise.all(X.map(async k=>{let A=await k,y=Z.dirname(A.destination);de.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),de.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),de.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",Y=await Ze(g,v,{yes:t.yes,cwd:t.cwd,pm:oe});if(Y.dependencies.size>0||Y.devDependencies.size>0){let k=[];if(!Y.installed){if(g.size>0){let y=resolveCommand(oe,"add",[...g]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(v.size>0){let y=resolveCommand(oe,"add",[...v,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,W)=>`${W+1}. ${y}`),Y.installed||k.push(""),k.push("Import and use the blocks!");let A=ft(k);process.stdout.write(A);}}function Hn(e){return new Promise(t=>setTimeout(t,e))}var Xs=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.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=$.parse(Xs,e);await ie(),await Zs(t),outro(N.green("All done!"));});async function Zs(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=Qs.machineIdSync(true),o;try{let a=await ke(`${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(N.red(a));}log.step(`Sign in at ${N.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=he(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(N.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 ke(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 oa=$.object({dirs:$.optional($.array($.string())),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),output:$.boolean(),verbose:$.boolean(),cwd:$.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("--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=$.parse(oa,e);await ie(),await na(t),outro(N.green("All done!"));});async function na(e){let t=p=>{e.verbose&&console.info(`${Pe} ${p}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n=At(e.cwd).match(p=>{if(p===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};let u=p;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(u.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(u.preview=e.preview),u.rules={...Zt,...u.rules},u},p=>program.error(N.red(p))),i;n.outputDir?i=Z.join(e.cwd,n.outputDir):i=e.cwd;let s=Z.join(i,m);if(e.output&&de.existsSync(s)){if(n.outputDir){let p=o(de.readFileSync(s).toString());if(p.isOk())for(let u of p.unwrap().categories)for(let v of u.blocks){let g=Z.join(i,v.directory);de.existsSync(g)&&de.rmSync(g,{recursive:true});}}de.rmSync(s);}let a=ra();try{let p=de.readFileSync(Z.join(e.cwd,".gitignore")).toString();a.add(p);}catch{}a.add(Er);for(let p of n.dirs){let u=Z.join(e.cwd,p);r.start(`Building ${N.cyan(u)}`);let v=Cr(u,{cwd:e.cwd,ignore:a,config:n});for(let g of v){if(o$1.find(S=>S.name===g.name)!==void 0){console.warn(`${D} ${ue} Skipped adding \`${N.cyan(`${p}/${g.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(g);}r.stop(`Built ${N.cyan(u)}`);}let c=Rr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:f,errors:m$1}=xr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(f.length>0||m$1.length>0)&&console.log(D);for(let p of f)console.log(p);if(m$1.length>0){for(let p of m$1)console.log(p);program.error(N.red(`Completed checking manifest with ${N.bold(`${m$1.length} error(s)`)} and ${N.bold(`${f.length} warning(s)`)}`));}let[h,b]=Sr(l.categories);if(l.categories=h,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n.preview){let p=l.categories.flatMap(u=>u.blocks.filter(v=>v.list).map(v=>`${N.cyan(v.category)}/${v.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of p)console.log(`${D} \u25FB ${u}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l.configFiles)for(let p of l.configFiles){let u=Z.join(e.cwd,p.path),v=Z.join(i,p.path),g=Z.join(v,"../");de.existsSync(g)||de.mkdirSync(g,{recursive:true}),de.copyFileSync(u,v);}for(let p of l.categories)for(let u of p.blocks){let v=Z.join(e.cwd,u.directory),g=Z.join(i,u.directory);for(let S of u.files){let R=Z.join(g,S,"../");de.existsSync(R)||de.mkdirSync(R,{recursive:true}),de.copyFileSync(Z.join(v,S),Z.join(g,S));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),de.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var da=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.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=$.parse(da,t);await ie(),await fa(e,o,r);});async function fa(e,t,r){let o=y=>{t.verbose&&console.info(`${Pe} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=Te(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests: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:y}=f.parse(n,{fullyQualified:true});if(!l.find(W=>W===y)){if(!t.allow){let W=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(W)||!W)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(N.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${N.cyan(l.join(", "))}`);let m=(await ze(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:W})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(W));}),h=(await bt(m,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:W})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(W));});if(i.stop(`Retrieved scripts from ${N.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([W,P])=>P.list).map(([W,P])=>{let V;return l.length>1?V=`${N.cyan(c(P.sourceRepo.url,P.category))}/${P.name}`:V=`${N.cyan(P.category)}/${P.name}`,{label:V,value:W}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let b=(await $t([n],h,m)).match(y=>y,y=>program.error(y)),p="temp-jsrepo-exec",u=`./${p}/${encodeURIComponent(n)}`,v=Z.join(process.cwd(),u);c$1.paths["*"]=u,de.mkdirSync(v,{recursive:true});let g=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],R=new Set,d=new Set,w=Ue(c$1.paths,t.cwd);w.isErr()&&program.error(N.red(w.unwrapErr()));let x$1=w.unwrap(),C=[];for(let y of b){let W=`${y.sourceRepo.url}/${y.category}/${y.name}`,P=`${y.category}/${y.name}`,V=y.sourceRepo,te=Z.join(t.cwd,x$1["*"],y.category);C.push(P),S.push({run:async({message:J})=>{J(`Adding ${N.cyan(W)}`),de.mkdirSync(te,{recursive:true});let nt=[],Se=async re=>{let je=await Ge(V,re);return je.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(re)}`)),program.error(N.red(`There was an error trying to get ${W}`))),je.unwrap()};for(let re of y.files){if(!c$1.includeTests&&ct(re))continue;let je=Z.join(y.directory,re),zt;y.subdirectory?zt=Z.join(te,y.name,re):zt=Z.join(te,re);let di=await Se(je),fi=zt.slice(0,zt.length-re.length);de.mkdirSync(fi,{recursive:true}),nt.push({content:di,destPath:zt});}for(let re of nt)de.writeFileSync(re.destPath,re.content);if(c$1.includeTests&&y.tests){let{devDependencies:re}=JSON.parse(de.readFileSync(Z.join(t.cwd,"package.json")).toString());(re===void 0||re.vitest===void 0)&&R.add("vitest");}for(let re of y.devDependencies)R.add(re);for(let re of y.dependencies)d.add(re);}});}if(await Yo({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(C.join(", "))}`,loading:i,tasks:S}),d.size>0||R.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},W=Z.join(v,"package.json");de.writeFileSync(W,JSON.stringify(y,null," "));}await Ze(d,R,{yes:true,no:false,cwd:v,pm:g,ignoreWorkspace:true});let X=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];X!==-1&&(oe=r.parent.rawArgs.slice(X+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let Y=b[0],k;Y.subdirectory?k=Z.join(v,`${Y.category}/${Y.name}/index.js`):k=Z.join(v,`${Y.category}/${Y.name}.js`);let A=resolveCommand(g,"execute",["tsx",k,...oe]);A||program.error(N.red("Error resolving run command!"));try{let y=x(A.command,A.args,{nodeOptions:{cwd:process.cwd()}});for await(let W of y)process.stdout.write(`${W}
78
- `);}finally{de.rmSync(Z.join(process.cwd(),p),{recursive:true,force:true});}}var ga=$.object({json:$.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=$.parse(ga,t);await ha(e,r);});async function ha(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(N.red("Registry not found!")):program.error(N.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(ya(a));}function ya(e){let t=`${N.cyan(`${e.name}@${e.version}`)} | versions: ${N.cyan(e.versions.length.toString())}
77
+ `);for(let V of P){let te=V.content.match(Pe=>Pe,Pe=>program.error(N.red(Pe))),J=or(V.name,k.block,w,t.cwd),nt=(await Xt({file:{content:te,destPath:J},biomeOptions:d,prettierOptions:R,config:s,imports:k.block._imports_,watermark:ir(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Pe=>Pe,Pe=>program.error(N.red(Pe))),Se="";de.existsSync(J)&&(Se=de.readFileSync(J).toString());let re=await Dt({config:{biomeOptions:d,prettierOptions:R,formatter:s.formatter},current:{path:J,content:Se},incoming:{path:c(A,V.name),content:nt},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});re.applyChanges&&(X.push(Mn({destination:J,content:re.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(P=>{P.map(async V=>{let te=V.content.match(Se=>Se,Se=>program.error(N.red(Se))),J=or(V.name,k.block,w,t.cwd),nt=Xt({file:{content:te,destPath:J},biomeOptions:d,prettierOptions:R,config:s,imports:k.block._imports_,watermark:ir(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Se=>(Se.isErr()&&program.error(N.red(Se.unwrapErr())),{destination:J,content:Se.unwrap(),block:k.block}));X.push(nt);});}),x.add(y);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(S.map(k=>k.files)),await Promise.all(X.map(async k=>{let A=await k,y=Z.dirname(A.destination);de.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),de.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),de.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",Y=await Ze(g,v,{yes:t.yes,cwd:t.cwd,pm:oe});if(Y.dependencies.size>0||Y.devDependencies.size>0){let k=[];if(!Y.installed){if(g.size>0){let y=resolveCommand(oe,"add",[...g]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(v.size>0){let y=resolveCommand(oe,"add",[...v,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,W)=>`${W+1}. ${y}`),Y.installed||k.push(""),k.push("Import and use the blocks!");let A=ft(k);process.stdout.write(A);}}function zn(e){return new Promise(t=>setTimeout(t,e))}var Qs=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),eo=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=$.parse(Qs,e);await ie(),await Xs(t),outro(N.green("All done!"));});async function Xs(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=Ys.machineIdSync(true),o;try{let a=await $e(`${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(N.red(a));}log.step(`Sign in at ${N.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=he(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(N.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await zn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await $e(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 ra=$.object({dirs:$.optional($.array($.string())),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),output:$.boolean(),verbose:$.boolean(),cwd:$.string()}),to=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("--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=$.parse(ra,e);await ie(),await oa(t),outro(N.green("All done!"));});async function oa(e){let t=p=>{e.verbose&&console.info(`${Ee} ${p}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n=At(e.cwd).match(p=>{if(p===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};let u=p;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(u.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(u.preview=e.preview),u.rules={...Zt,...u.rules},u},p=>program.error(N.red(p))),i;n.outputDir?i=Z.join(e.cwd,n.outputDir):i=e.cwd;let s=Z.join(i,m);if(e.output&&de.existsSync(s)){if(n.outputDir){let p=o(de.readFileSync(s).toString());if(p.isOk())for(let u of p.unwrap().categories)for(let v of u.blocks){let g=Z.join(i,v.directory);de.existsSync(g)&&de.rmSync(g,{recursive:true});}}de.rmSync(s);}let a=ta();try{let p=de.readFileSync(Z.join(e.cwd,".gitignore")).toString();a.add(p);}catch{}a.add(Er);for(let p of n.dirs){let u=Z.join(e.cwd,p);r.start(`Building ${N.cyan(u)}`);let v=Cr(u,{cwd:e.cwd,ignore:a,config:n});for(let g of v){if(o$1.find(j=>j.name===g.name)!==void 0){console.warn(`${D} ${ue} Skipped adding \`${N.cyan(`${p}/${g.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(g);}r.stop(`Built ${N.cyan(u)}`);}let c=Rr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:f,errors:m$1}=xr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(f.length>0||m$1.length>0)&&console.log(D);for(let p of f)console.log(p);if(m$1.length>0){for(let p of m$1)console.log(p);program.error(N.red(`Completed checking manifest with ${N.bold(`${m$1.length} error(s)`)} and ${N.bold(`${f.length} warning(s)`)}`));}let[h,b]=jr(l.categories);if(l.categories=h,b>0&&log.step(`Removed ${b} unused block${b>1?"s":""}.`),n.preview){let p=l.categories.flatMap(u=>u.blocks.filter(v=>v.list).map(v=>`${N.cyan(v.category)}/${v.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of p)console.log(`${D} \u25FB ${u}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l.configFiles)for(let p of l.configFiles){let u=Z.join(e.cwd,p.path),v=Z.join(i,p.path),g=Z.join(v,"../");de.existsSync(g)||de.mkdirSync(g,{recursive:true}),de.copyFileSync(u,v);}for(let p of l.categories)for(let u of p.blocks){let v=Z.join(e.cwd,u.directory),g=Z.join(i,u.directory);for(let j of u.files){let R=Z.join(g,j,"../");de.existsSync(R)||de.mkdirSync(R,{recursive:true}),de.copyFileSync(Z.join(v,j),Z.join(g,j));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),de.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var pa=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),no=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=$.parse(pa,t);await ie(),await da(e,o,r);});async function da(e,t,r){let o=y=>{t.verbose&&console.info(`${Ee} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=ye(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let f=n?z(n):void 0;if(n&&f){let{url:y}=f.parse(n,{fullyQualified:true});if(!l.find(W=>W===y)){if(!t.allow){let W=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(W)||!W)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Qe} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(N.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${N.cyan(l.join(", "))}`);let m=(await qe(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:W})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(W));}),h=(await bt(m,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:W})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(W));});if(i.stop(`Retrieved scripts from ${N.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([W,P])=>P.list).map(([W,P])=>{let V;return l.length>1?V=`${N.cyan(c(P.sourceRepo.url,P.category))}/${P.name}`:V=`${N.cyan(P.category)}/${P.name}`,{label:V,value:W}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let b=(await $t([n],h,m)).match(y=>y,y=>program.error(y)),p="temp-jsrepo-exec",u=`./${p}/${encodeURIComponent(n)}`,v=Z.join(process.cwd(),u);c$1.paths["*"]=u,de.mkdirSync(v,{recursive:true});let g=(await detect({cwd:process.cwd()}))?.agent??"npm",j=[],R=new Set,d=new Set,w=Ue(c$1.paths,t.cwd);w.isErr()&&program.error(N.red(w.unwrapErr()));let x$1=w.unwrap(),C=[];for(let y of b){let W=`${y.sourceRepo.url}/${y.category}/${y.name}`,P=`${y.category}/${y.name}`,V=y.sourceRepo,te=Z.join(t.cwd,x$1["*"],y.category);C.push(P),j.push({run:async({message:J})=>{J(`Adding ${N.cyan(W)}`),de.mkdirSync(te,{recursive:true});let nt=[],Se=async re=>{let Pe=await Ge(V,re);return Pe.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(re)}`)),program.error(N.red(`There was an error trying to get ${W}`))),Pe.unwrap()};for(let re of y.files){if(!c$1.includeTests&&ct(re))continue;let Pe=Z.join(y.directory,re),qt;y.subdirectory?qt=Z.join(te,y.name,re):qt=Z.join(te,re);let pi=await Se(Pe),di=qt.slice(0,qt.length-re.length);de.mkdirSync(di,{recursive:true}),nt.push({content:pi,destPath:qt});}for(let re of nt)de.writeFileSync(re.destPath,re.content);if(c$1.includeTests&&y.tests){let{devDependencies:re}=JSON.parse(de.readFileSync(Z.join(t.cwd,"package.json")).toString());(re===void 0||re.vitest===void 0)&&R.add("vitest");}for(let re of y.devDependencies)R.add(re);for(let re of y.dependencies)d.add(re);}});}if(await Ko({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(C.join(", "))}`,loading:i,tasks:j}),d.size>0||R.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},W=Z.join(v,"package.json");de.writeFileSync(W,JSON.stringify(y,null," "));}await Ze(d,R,{yes:true,no:false,cwd:v,pm:g,ignoreWorkspace:true});let X=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];X!==-1&&(oe=r.parent.rawArgs.slice(X+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let Y=b[0],k;Y.subdirectory?k=Z.join(v,`${Y.category}/${Y.name}/index.js`):k=Z.join(v,`${Y.category}/${Y.name}.js`);let A=resolveCommand(g,"execute",["tsx",k,...oe]);A||program.error(N.red("Error resolving run command!"));try{let y=x(A.command,A.args,{nodeOptions:{cwd:process.cwd()}});for await(let W of y)process.stdout.write(`${W}
78
+ `);}finally{de.rmSync(Z.join(process.cwd(),p),{recursive:true,force:true});}}var ua=$.object({json:$.boolean()}),io=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=$.parse(ua,t);await ga(e,r);});async function ga(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 Di(i,{headers:n});s.ok||(s.status===404?program.error(N.red("Registry not found!")):program.error(N.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(ha(a));}function ha(e){let t=`${N.cyan(`${e.name}@${e.version}`)} | versions: ${N.cyan(e.versions.length.toString())}
79
79
  `;e.meta.description&&(t+=`${e.meta.description}
80
80
  `),e.meta.homepage&&(t+=`${N.blue(e.meta.homepage)}
81
81
  `),t+=`
82
82
  `,e.meta.tags&&(t+=`keywords: ${e.meta.tags.map(i=>N.cyan(i)).join(", ")}
83
83
 
84
- `);let r=i=>i%3===0,o=e.categories.flatMap(i=>i.blocks).map(i=>i.list?N.blue(`${i.category}/${i.name}`):N.dim(`${i.category}/${i.name}`)),n=No(o)+4;return t+=`blocks:
84
+ `);let r=i=>i%3===0,o=e.categories.flatMap(i=>i.blocks).map(i=>i.list?N.blue(`${i.category}/${i.name}`):N.dim(`${i.category}/${i.name}`)),n=Do(o)+4;return t+=`blocks:
85
85
  ${o.map((i,s)=>{let a=r(s+1),c=s+1>=o.length;return a?`${i}
86
- `:`${Fo(i,n," ")}${c?`
86
+ `:`${Ao(i,n," ")}${c?`
87
87
  `:""}`}).join("")}
88
88
  `,e.meta.authors&&(t+=`authors:
89
89
  ${e.meta.authors.map(i=>`- ${N.blue(i)}`).join(`
@@ -93,9 +93,18 @@ ${e.meta.authors.map(i=>`- ${N.blue(i)}`).join(`
93
93
  ${Object.entries(e.tags).map(([i,s])=>`${N.blue(i)}: ${s}`).join(`
94
94
  `)}
95
95
 
96
- `,t}var xa=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(qr),paths:$.optional($.record($.string(),$.string())),configFiles:$.optional($.record($.string(),$.string())),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.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.").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(nr).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(nr).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=$.parse(xa,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(N.red(`You cannot provide both ${N.bold("--project")} and ${N.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${N.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${N.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 Ca(e,r):await Sa(r),outro(N.green("All done!"));}),Ca=async(e,t)=>{let r=Te(t.cwd),o=spinner(),n,i={},s=Nt(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(N.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let R=await text({message:"Please enter a default path to install the blocks",validate(d){if(d.trim()==="")return "Please provide a value";if(!d.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(d).length===0)return w}},placeholder:"./src/blocks",initialValue:a});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),a=R;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let R=r.isErr()?"none":r.unwrap().formatter??"none";de.existsSync(Z.join(t.cwd,".prettierrc"))&&(R="prettier"),de.existsSync(Z.join(t.cwd,"biome.json"))&&(R="biome");let d=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(w=>({value:w.toLowerCase(),label:w})),initialValue:R});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d!=="none"&&(t.formatter=d);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,f=new Set,m=async R=>{let d=await Ra({url:R,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let w of d.dependencies)l.add(w);for(let w of d.devDependencies)f.add(w);n=d.paths,i=d.configFiles;};if(c.length>0)for(let R of c){if(!e.find(d=>d===R)&&r.isOk()&&r.unwrap().repos.find(d=>d===R)){let d=await confirm({message:`Initialize ${R}?`,initialValue:t.yes});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)continue}log.info(`Initializing ${N.cyan(R)}`),await m(R);}for(;!t.yes;){{let d=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)break}let R=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:d=>{if(d.trim().length===0)return "Please provide a value";if(!z$1(d))return `Invalid provider! Valid providers (${y.map(w=>w.name).join(", ")})`}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),await m(R),c.push(R);}let h={$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,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${yt}\``);let{prettierOptions:b,biomeOptions:p}=await Ct({formatter:h.formatter,cwd:t.cwd}),u=Z.join(t.cwd,yt),v=await br.format(JSON.stringify(h,null," "),{biomeOptions:p,prettierOptions:b,filePath:u,formatter:h.formatter});de.existsSync(t.cwd)||de.mkdirSync(t.cwd,{recursive:true}),de.writeFileSync(u,v),o.stop(`Wrote config to \`${yt}\`.`);let g=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await Ze(l,f,{yes:t.yes,cwd:t.cwd,pm:g});if(S.dependencies.size>0||S.devDependencies.size>0){let R=[];if(!S.installed){if(l.size>0){let w=resolveCommand$1(g,"add",[...l]);R.push(`Install dependencies \`${N.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(f.size>0){let w=resolveCommand$1(g,"add",[...f,"-D"]);R.push(`Install dev dependencies \`${N.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}R=R.map((w,x)=>`${x+1}. ${w}`),S.installed||R.push(""),R.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let d=ft(R);process.stdout.write(d);}};async function Ra({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new pe,a=z$1(e);a||program.error(N.red(`Invalid provider! Valid providers (${y.map(p=>p.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let p=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(p.url).origin}`;}if(!s.get(c$1)&&!n.yes){let p=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p){let u=await password({message:"Paste your token",validate(v){if(v.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,u);}}i.start(`Fetching manifest from ${N.cyan(e)}`);let f=(await lt(e,{noCache:!n.cache})).match(p=>p,p=>program.error(N.red(p))),m=(await Ft(f)).match(p=>p,p=>program.error(N.red(p)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Mt(f,m,n.cwd);let h=[],b=[];if(m.configFiles){let{prettierOptions:p,biomeOptions:u}=await Ct({formatter:o,cwd:n.cwd});for(let v of m.configFiles){if(v.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${v.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...v.dependencies??[]),b.push(...v.devDependencies??[]),!r[v.name])if(n.configFiles?.[v.name])r[v.name]=n.configFiles[v.name];else if(n.yes)v.expectedPath||program.error(N.red(`You must provide a path for ${v.name} when using --yes!`)),r[v.name]=v.expectedPath;else {let x=await text({message:`Where is your ${v.name} file?`,defaultValue:v.expectedPath,initialValue:v.expectedPath,placeholder:v.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[v.name]=x;}let g=Z.join(n.cwd,r[v.name]),S;if(de.existsSync(g))S=de.readFileSync(g).toString();else {let x=Z.dirname(g);if(de.existsSync(x)){let C=rn(g);if(C){S=de.readFileSync(C).toString();let j=Z.relative(n.cwd,C);log.warn(`Located ${N.bold(r[v.name])} at ${N.bold(j)}`),r[v.name]=j,g=Z.join(n.cwd,j);}}}i.start(`Fetching the ${N.cyan(v.name)} from ${N.cyan(e)}`);let R=(await Ge(f,v.path)).match(x=>x,x=>program.error(N.red(x))),d=await yr({file:{content:R,destPath:g},biomeOptions:u,prettierOptions:p,formatter:o});i.stop(`Fetched the ${N.cyan(v.name)} from ${N.cyan(e)}`);let w=n.yes||S===void 0;if(S){if(!n.yes){let x=c(f.url,v.name),C=await Dt({config:{biomeOptions:u,prettierOptions:p,formatter:o},current:{content:S,path:g},incoming:{content:d,path:x},options:{...n,loading:i,no:false}});C.applyChanges&&(w=true,S=C.updatedContent);}}else {let x=Z.dirname(g);de.existsSync(x)||de.mkdirSync(x,{recursive:true}),S=d;}w&&S&&(i.start(`Writing ${N.cyan(v.name)} to ${N.cyan(g)}`),de.writeFileSync(g,S),i.stop(`Wrote ${N.cyan(v.name)} to ${N.cyan(g)}`));}}if(!n.yes){let p=await multiselect({message:"Which category paths would you like to configure?",options:m.categories.map(u=>({label:u.name,value:u.name,hint:m.defaultPaths?.[u.name]?`Default: ${m.defaultPaths?.[u.name]}`:void 0})),required:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p.length>0)for(let u of p){let v=t[u]??m.defaultPaths?.[u],g=await text({message:`Where should ${u} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:v||`./src/${u}`,defaultValue:v,initialValue:v});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),t[u]=g;}}for(let p of m.categories){if(t[p.name]!==void 0)continue;let u=m.defaultPaths?.[p.name];u&&(t[p.name]=u);}return {paths:t,configFiles:r,dependencies:h,devDependencies:b}}var Sa=async e=>{let t=spinner(),r=Z.join(e.cwd,"package.json");de.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=At(e.cwd).match(p=>p,p=>program.error(N.red(p)));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}),o.$schema=`https://unpkg.com/jsrepo@${Fe.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let u=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),!u)break}let p=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(p);}let n=JSON.parse(de.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let p=await confirm({message:`Configure to publish to ${We}?`,initialValue:true});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),i=p;}if(i){if(!o.name){let p=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.name=p;}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{de.writeFileSync(r,JSON.stringify(n,null," "));}catch(p){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${p}`));}}}),f.push({loadingMessage:`Writing config to \`${N.cyan(vt)}\``,completedMessage:`Wrote config to \`${N.cyan(vt)}\``,run:async()=>{let p=Z.join(e.cwd,vt);try{de.writeFileSync(Z.join(p),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(p)}\`. Error: ${u}`));}}}),await Ko(f,{loading:t});let m=s;s||(m=(await Ze(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!m){let p=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Qe} as a dev dependency \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let p=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to publish the registry.`);}else {let p=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((p,u)=>`${u+1}. ${p}`);let b=ft(h);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 \`${N.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 Oa={name:"list-components",description:"Lists all available components/utilities for the provided registries.",inputSchema:{type:"object",properties:{registries:{type:"array",description:"Registries from the user's jsrepo.json `repos` key or any well-known jsrepo registry.",items:{type:"string"}}},required:["registries"]}};async function Ta(e){let t=(await ze(e)).match(o=>o,o=>{throw new Error(`Error getting registry state for ${o.repo}: ${o.message}`)}),r=(await bt(t)).match(o=>o,o=>{throw new Error(`Error getting components for ${o.repo}: ${o.message}`)});return {components:fr(r,(o,n)=>n).map(o=>{let n=`${o.category}/${o.name}`,i=c(o.sourceRepo.url,n);return {fullName:n,...o,sourceRepo:void 0,commands:{add:`jsrepo add ${i} -y -A`,update:`jsrepo update ${i} -y -A`}}})}}var Da={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}},required:["component"]}};async function Na({component:e,includeTests:t=false}){let r=z$1(e);if(!r)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:o,specifier:n}=r.parse(e,{fullyQualified:true});if(!n)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let i=(await lt(o)).match(m=>m,m=>{throw new Error(`Error getting state for ${o}: ${m}`)}),s=(await Bt([i])).match(m=>m,m=>{throw new Error(`Error getting manifest for ${o}: ${m}`)}),c$1=Lt(s).get(c(o,n));if(!c$1)throw new Error(`${n} does not exist in ${o}`);let l=_t([c$1],{includeTests:t}),f=(await Promise.all(l.map(m=>m.files))).flatMap(m=>[...m.map(h=>({name:h.name,content:h.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:o,component:n,files:f,commands:{add:`jsrepo add ${e} -y -A`,update:`jsrepo update ${e} -y -A`}}}var Aa={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 components from. (If not provided will return all for the current config file.)",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 Fa({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 Ft(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 La={name:"discover-registries",description:"Searches jsrepo.com for registries that could include components the user needs in their project.",inputSchema:{type:"object",properties:{primaryLanguage:{type:"string",description:"File extension of the primary language of the registry. i.e. TypeScript -> ts, React -> tsx/jsx"}},required:["primaryLanguage"]}};async function Ba({primaryLanguage:e}){let t=await ke(`${w}/api/registries?lang=${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 _a={name:"cli-reference",description:"A reference for the usage of the jsrepo CLI.",inputSchema:{type:"object"}};function Tr(){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: ${N.bold(r.params.name)}`);try{switch(r.params.name){case "list-components":{let o=r.params.arguments,n=await Ta(o.registries);return {content:[{type:"text",text:JSON.stringify({...n,cliReference:Tr()})}]}}case "get-component-code":{let o=r.params.arguments,n=await Na(o);return {content:[{type:"text",text:JSON.stringify({...n,cliReference:Tr()})}]}}case "get-config-files":{let o=r.params.arguments,n=await Fa(o);return {content:[{type:"text",text:JSON.stringify({...n,cliReference:Tr()})}]}}case "discover-registries":{let o=r.params.arguments,n=await Ba(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "cli-reference":{let o=Tr();return {content:[{type:"text",text:JSON.stringify(o)}]}}}throw new Error(`Invalid tool ${r.params.name}`)}catch(o){return console.error(N.red(`Error executing tool ${N.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:[Oa,Da,Aa,La,_a]}));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 Ga=$.object({private:$.boolean(),dryRun:$.boolean(),name:$.optional($.string()),ver:$.optional($.string()),dirs:$.optional($.array($.string())),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),verbose:$.boolean(),cwd:$.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("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Ga,e);await ie(),await za(t),outro(N.green("All done!"));});async function za(e){let t=d=>{e.verbose&&console.info(`${Pe} ${d}`);},r=he({verbose:e.verbose?t:void 0}),o=At(e.cwd).match(d=>{if(d===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};let w=d;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),w.rules={...Zt,...w.rules},w},d=>program.error(N.red(d)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[d,w,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!d.startsWith("@"))throw new Error;if(!d.slice(1).match(v))throw new Error;if(!w.match(v))throw new Error}catch{program.error(N.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(N.red(`To publish to ${N.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=Z.join(e.cwd,"package.json");de.existsSync(w)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:x}=JSON.parse(de.readFileSync(w).toString());o.version=x;}Jo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(N.red(`To publish to ${N.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(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${We}.`));let i=[],s=ra();try{let d=de.readFileSync(Z.join(e.cwd,".gitignore")).toString();s.add(d);}catch{}s.add(Er);for(let d of o.dirs){let w=Z.join(e.cwd,d);r.start(`Building ${N.cyan(w)}`);let x=Cr(w,{cwd:e.cwd,ignore:s,config:o});for(let C of x){if(i.find(j=>j.name===C.name)!==void 0){console.warn(`${D} ${ue} Skipped adding \`${N.cyan(`${d}/${C.name}`)}\` because a category with the same name already exists!`);continue}i.push(C);}r.stop(`Built ${N.cyan(w)}`);}let a=Rr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:f}=xr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||f.length>0)&&console.log(D);for(let d of l)console.log(d);if(f.length>0){for(let d of f)console.log(d);program.error(N.red(`Completed checking manifest with ${N.bold(`${f.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[m,h]=Sr(c.categories);c.categories=m,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let b=Z.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${b}`),de.mkdirSync(b,{recursive:true}),t("Writing manifest to temp dir"),de.writeFileSync(Z.resolve(b,"jsrepo-manifest.json"),JSON.stringify(c));let p$1=Z.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),de.copyFileSync(p$1,Z.join(b,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let d of c.configFiles){let w=Z.join(e.cwd,d.path),x=Z.join(b,d.path),C=Z.join(x,"../");de.existsSync(C)||de.mkdirSync(C,{recursive:true}),de.copyFileSync(w,x);}t("Copied config files");}t("Copying registry files");for(let d of c.categories)for(let w of d.blocks){let x=Z.join(e.cwd,w.directory),C=Z.join(b,w.directory);for(let j of w.files){let X=Z.join(C,j,"../");de.existsSync(X)||de.mkdirSync(X,{recursive:true}),de.copyFileSync(Z.join(x,j),Z.join(C,j));}}t("Copied registry files");let u=Z.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),v$1=de.readdirSync(b);t("Creating archive file"),await ni.create({z:true,cwd:b,file:u},v$1),t("Created archive file"),t("Removing temp directory"),de.rmSync(b,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u)}...`);let g=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${N.cyan(g)}`),r.start(`Publishing ${N.bold(c.name)} to ${We}...`);let S=de.readFileSync(u);t("Removing archive file"),de.rmSync(u,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let R=await ke(`${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":g},method:"POST"});if(r.stop(`Got response from ${We}.`),R.ok){let d=await R.json();d.status==="dry-run"?log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} published ${N.greenBright(`@${d.scope}`)}/${d.registry}${N.greenBright(`@${d.version}`)}!`);}else {let d=await R.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(R.status)} ${d.message}`));}}var nc=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.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=$.parse(nc,t);await ie(),await ic(e,r),outro(N.green("All done!"));});async function ic(e,t){let r=g=>{t.verbose&&console.info(`${Pe} ${g}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Te(t.cwd).match(g=>g,g=>program.error(N.red(g))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let g=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await ze(i,{noCache:!t.cache})).match(g=>g,({repo:g,message:S})=>{n.stop(`Failed to get info for ${N.cyan(g)}`),program.error(N.red(S));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await bt(s,{verbose:t.verbose?r:void 0})).match(g=>g,({repo:g,message:S})=>{n.stop(`Failed fetching blocks from ${N.cyan(g)}`),program.error(N.red(S));});r(`Retrieved blocks from ${N.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`);let c$1=Z.resolve(Z.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${N.bold(c$1)}.`),de.mkdirSync(c$1,{recursive:true});let l=()=>{de.rmSync(c$1,{recursive:true,force:true});},f=xt(a,o,t.cwd).map(g=>g.specifier),m=e;e.length===0&&(m=f),m.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let g of m){let S,R=z$1(g);if(R){let{url:d}=R.parse(g,{fullyQualified:true}),w=(await lt(d)).match(C=>C,C=>program.error(N.red(C))),x=(await bt([w])).match(C=>C,C=>program.error(N.red(C)));for(let[C,j]of x)a.set(C,j);S=a.get(g);}else for(let d of i){let w=z$1(d);if(!w)continue;let{url:x,specifier:C}=w.parse(c(d,g),{fullyQualified:true}),j=a.get(c(x,C));if(j!==void 0){S=j;break}}S||program.error(N.red(`Invalid block! ${N.bold(g)} does not exist!`)),h.push({name:g,block:S});}let b=Ue(o.paths,t.cwd).match(g=>g,g=>program.error(N.red(g)));for(let{block:g}of h){let S=g.sourceRepo,R=c(g.sourceRepo.url,g.category,g.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(R)}`),!g.tests){n.stop(`No tests found for ${N.cyan(R)}`);continue}let d=tr(g,b,t.cwd);d=Z.relative(c$1,d);let w=async C=>{let j=await Ge(S,C);return j.isErr()&&(n.stop(N.red(`Error fetching ${N.bold(C)}`)),program.error(N.red(`There was an error trying to get ${R}`))),j.unwrap()};r(`Downloading and copying test files for ${R}`);let x=[];for(let C of g.files.filter(j=>ct(j))){let j=await w(Z.join(g.directory,C)),X=Z.join(c$1,C);de.writeFileSync(X,j),x.push(X);}for(let C of x){r(`Opening test file ${C}`);let j=de.readFileSync(C).toString(),X=ps.parseSync(C,j);for(let oe of X.module.staticImports){let Y=oe.moduleRequest.value,k;if(Y.startsWith(".")&&(g.subdirectory?k=Z.join(d,g.name,Y):k=Z.join(d,Y)),k){let A=new RegExp(`(['"])${rs(Y)}\\1`,"g");j=j.replaceAll(A,`$1${k}$1`);}}de.writeFileSync(C,j);}r(`Completed ${N.cyan.bold(R)} test file`),t.verbose||n.stop(`Completed setup for ${N.bold(R)}`);}r("Beginning testing");let p=await detect({cwd:t.cwd});p==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(p.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${p.agent}'.`));let v=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(v)} on ${N.cyan(t.cwd)}`);try{let g=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let S of g)process.stdout.write(`${S}
96
+ `,t}var $a=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(qr),paths:$.optional($.record($.string(),$.string())),configFiles:$.optional($.record($.string(),$.string())),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),lo=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.").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(nr).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(nr).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=$.parse($a,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(N.red(`You cannot provide both ${N.bold("--project")} and ${N.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${N.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${N.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 xa(e,r):await Ra(r),outro(N.green("All done!"));}),xa=async(e,t)=>{let r=ye(t.cwd),o=spinner(),n,i={},s=Nt(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(N.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let R=await text({message:"Please enter a default path to install the blocks",validate(d){if(d.trim()==="")return "Please provide a value";if(!d.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(d).length===0)return w}},placeholder:"./src/blocks",initialValue:a});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),a=R;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let R=r.isErr()?"none":r.unwrap().formatter??"none";de.existsSync(Z.join(t.cwd,".prettierrc"))&&(R="prettier"),de.existsSync(Z.join(t.cwd,"biome.json"))&&(R="biome");let d=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(w=>({value:w.toLowerCase(),label:w})),initialValue:R});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d!=="none"&&(t.formatter=d);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,f=new Set,m=async R=>{let d=await Ca({url:R,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let w of d.dependencies)l.add(w);for(let w of d.devDependencies)f.add(w);n=d.paths,i=d.configFiles;};if(c.length>0)for(let R of c){if(!e.find(d=>d===R)&&r.isOk()&&r.unwrap().repos.find(d=>d===R)){let d=await confirm({message:`Initialize ${R}?`,initialValue:t.yes});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)continue}log.info(`Initializing ${N.cyan(R)}`),await m(R);}for(;!t.yes;){{let d=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)break}let R=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:d=>{if(d.trim().length===0)return "Please provide a value";if(!z(d))return `Invalid provider! Valid providers (${y.map(w=>w.name).join(", ")})`}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),await m(R),c.push(R);}let h={$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,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${yt}\``);let{prettierOptions:b,biomeOptions:p}=await Ct({formatter:h.formatter,cwd:t.cwd}),u=Z.join(t.cwd,yt),v=await br.format(JSON.stringify(h,null," "),{biomeOptions:p,prettierOptions:b,filePath:u,formatter:h.formatter});de.existsSync(t.cwd)||de.mkdirSync(t.cwd,{recursive:true}),de.writeFileSync(u,v),o.stop(`Wrote config to \`${yt}\`.`);let g=(await detect$1({cwd:t.cwd}))?.agent??"npm",j=await Ze(l,f,{yes:t.yes,cwd:t.cwd,pm:g});if(j.dependencies.size>0||j.devDependencies.size>0){let R=[];if(!j.installed){if(l.size>0){let w=resolveCommand$1(g,"add",[...l]);R.push(`Install dependencies \`${N.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(f.size>0){let w=resolveCommand$1(g,"add",[...f,"-D"]);R.push(`Install dev dependencies \`${N.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}R=R.map((w,x)=>`${x+1}. ${w}`),j.installed||R.push(""),R.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let d=ft(R);process.stdout.write(d);}};async function Ca({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new pe,a=z(e);a||program.error(N.red(`Invalid provider! Valid providers (${y.map(p=>p.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let p=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(p.url).origin}`;}if(!s.get(c$1)&&!n.yes){let p=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p){let u=await password({message:"Paste your token",validate(v){if(v.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,u);}}i.start(`Fetching manifest from ${N.cyan(e)}`);let f=(await lt(e,{noCache:!n.cache})).match(p=>p,p=>program.error(N.red(p))),m=(await Ft(f)).match(p=>p,p=>program.error(N.red(p)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Mt(f,m,n.cwd);let h=[],b=[];if(m.configFiles){let{prettierOptions:p,biomeOptions:u}=await Ct({formatter:o,cwd:n.cwd});for(let v of m.configFiles){if(v.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${v.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...v.dependencies??[]),b.push(...v.devDependencies??[]),!r[v.name])if(n.configFiles?.[v.name])r[v.name]=n.configFiles[v.name];else if(n.yes)v.expectedPath||program.error(N.red(`You must provide a path for ${v.name} when using --yes!`)),r[v.name]=v.expectedPath;else {let x=await text({message:`Where is your ${v.name} file?`,defaultValue:v.expectedPath,initialValue:v.expectedPath,placeholder:v.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[v.name]=x;}let g=Z.join(n.cwd,r[v.name]),j;if(de.existsSync(g))j=de.readFileSync(g).toString();else {let x=Z.dirname(g);if(de.existsSync(x)){let C=tn(g);if(C){j=de.readFileSync(C).toString();let S=Z.relative(n.cwd,C);log.warn(`Located ${N.bold(r[v.name])} at ${N.bold(S)}`),r[v.name]=S,g=Z.join(n.cwd,S);}}}i.start(`Fetching the ${N.cyan(v.name)} from ${N.cyan(e)}`);let R=(await Ge(f,v.path)).match(x=>x,x=>program.error(N.red(x))),d=await yr({file:{content:R,destPath:g},biomeOptions:u,prettierOptions:p,formatter:o});i.stop(`Fetched the ${N.cyan(v.name)} from ${N.cyan(e)}`);let w=n.yes||j===void 0;if(j){if(!n.yes){let x=c(f.url,v.name),C=await Dt({config:{biomeOptions:u,prettierOptions:p,formatter:o},current:{content:j,path:g},incoming:{content:d,path:x},options:{...n,loading:i,no:false}});C.applyChanges&&(w=true,j=C.updatedContent);}}else {let x=Z.dirname(g);de.existsSync(x)||de.mkdirSync(x,{recursive:true}),j=d;}w&&j&&(i.start(`Writing ${N.cyan(v.name)} to ${N.cyan(g)}`),de.writeFileSync(g,j),i.stop(`Wrote ${N.cyan(v.name)} to ${N.cyan(g)}`));}}if(!n.yes){let p=await multiselect({message:"Which category paths would you like to configure?",options:m.categories.map(u=>({label:u.name,value:u.name,hint:m.defaultPaths?.[u.name]?`Default: ${m.defaultPaths?.[u.name]}`:void 0})),required:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p.length>0)for(let u of p){let v=t[u]??m.defaultPaths?.[u],g=await text({message:`Where should ${u} be added in your project?`,validate(j){if(j.trim()==="")return "Please provide a value"},placeholder:v||`./src/${u}`,defaultValue:v,initialValue:v});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),t[u]=g;}}for(let p of m.categories){if(t[p.name]!==void 0)continue;let u=m.defaultPaths?.[p.name];u&&(t[p.name]=u);}return {paths:t,configFiles:r,dependencies:h,devDependencies:b}}var Ra=async e=>{let t=spinner(),r=Z.join(e.cwd,"package.json");de.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=At(e.cwd).match(p=>p,p=>program.error(N.red(p)));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}),o.$schema=`https://unpkg.com/jsrepo@${Fe.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let u=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),!u)break}let p=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(p);}let n=JSON.parse(de.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let p=await confirm({message:`Configure to publish to ${We}?`,initialValue:true});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),i=p;}if(i){if(!o.name){let p=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.name=p;}o.version||(o.version="0.0.1"),e.publishScript=await Zn(e.publishScript,n,e,"release:registry");}else e.buildScript=await Zn(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{de.writeFileSync(r,JSON.stringify(n,null," "));}catch(p){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${p}`));}}}),f.push({loadingMessage:`Writing config to \`${N.cyan(vt)}\``,completedMessage:`Wrote config to \`${N.cyan(vt)}\``,run:async()=>{let p=Z.join(e.cwd,vt);try{de.writeFileSync(Z.join(p),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(p)}\`. Error: ${u}`));}}}),await Ho(f,{loading:t});let m=s;s||(m=(await Ze(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!m){let p=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Qe} as a dev dependency \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let p=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to publish the registry.`);}else {let p=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((p,u)=>`${u+1}. ${p}`);let b=ft(h);process.stdout.write(b);};async function Zn(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${N.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 Ia={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 Oa({registries:e,cwd:t}){if(!e){let n=ye(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:fr(o,(n,i)=>i).map(n=>c(n.sourceRepo.url,`${n.category}/${n.name}`))}}var Ta={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}},required:["component"]}};async function Da({component:e,includeTests:t=false}){let r=z(e);if(!r)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:o,specifier:n}=r.parse(e,{fullyQualified:true});if(!n)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let i=(await lt(o)).match(m=>m,m=>{throw new Error(`Error getting state for ${o}: ${m}`)}),s=(await Bt([i])).match(m=>m,m=>{throw new Error(`Error getting manifest for ${o}: ${m}`)}),c$1=Lt(s).get(c(o,n));if(!c$1)throw new Error(`${n} does not exist in ${o}`);let l=_t([c$1],{includeTests:t}),f=(await Promise.all(l.map(m=>m.files))).flatMap(m=>[...m.map(h=>({name:h.name,content:h.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:o,component:n,files:f,commands:{add:`jsrepo add ${e} -y -A`,addMultiple:`jsrepo add ${e} ... -y -A`,update:`jsrepo update ${e} -y -A`}}}var Na={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 Aa({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 Ft(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 Fa={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 La({query:e}){let t=await $e(`${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 Ba={name:"cli-reference",description:"A reference for the usage of the jsrepo CLI.",inputSchema:{type:"object"}};function _a(){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 ri(){let e=new Server({name:"jsrepo",version:Fe.version},{capabilities:{tools:{}}});e.setRequestHandler(CallToolRequestSchema,async r=>{console.error(`Received CallToolRequest calling: ${N.bold(r.params.name)}`);try{switch(r.params.name){case "list-components":{let o=r.params.arguments,n=await Oa(o);return {content:[{type:"text",text:`Available components:
97
+ ${JSON.stringify(n.components)}
98
+ Add a component to your project with:
99
+ jsrepo add ${n.components[0]} -y -A
100
+ Add multiple components to your project in parallel with:
101
+ jsrepo add ${n.components[0]} ${n.components[1]??n.components[0]} ... -y -A
102
+ Update existing components with:
103
+ jsrepo update ${n.components[0]} -y -A
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 Da(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "get-config-files":{let o=r.params.arguments,n=await Aa(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "search-registries":{let o=r.params.arguments,n=await La(o);return {content:[{type:"text",text:JSON.stringify(n)}]}}case "cli-reference":{let o=_a();return {content:[{type:"text",text:JSON.stringify(o)}]}}}throw new Error(`Invalid tool ${r.params.name}`)}catch(o){return console.error(N.red(`Error executing tool ${N.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:[Ia,Ta,Na,Fa,Ba]}));let t=new StdioServerTransport;console.error("Connecting server to transport..."),await e.connect(t),console.error("Server connected");}var fo=new Command("mcp").description("Interact with jsrepo through an MCP server.").option("--cwd <path>","The current working directory.",process.cwd()).action(async()=>{await ri().catch(e=>{console.error(e),process.exit(1);});});var Ga=$.object({private:$.boolean(),dryRun:$.boolean(),name:$.optional($.string()),ver:$.optional($.string()),dirs:$.optional($.array($.string())),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),verbose:$.boolean(),cwd:$.string()}),mo=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("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Ga,e);await ie(),await qa(t),outro(N.green("All done!"));});async function qa(e){let t=d=>{e.verbose&&console.info(`${Ee} ${d}`);},r=he({verbose:e.verbose?t:void 0}),o=At(e.cwd).match(d=>{if(d===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};let w=d;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),w.rules={...Zt,...w.rules},w},d=>program.error(N.red(d)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[d,w,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!d.startsWith("@"))throw new Error;if(!d.slice(1).match(v))throw new Error;if(!w.match(v))throw new Error}catch{program.error(N.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(N.red(`To publish to ${N.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=Z.join(e.cwd,"package.json");de.existsSync(w)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:x}=JSON.parse(de.readFileSync(w).toString());o.version=x;}Vo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(N.red(`To publish to ${N.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(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${We}.`));let i=[],s=ta();try{let d=de.readFileSync(Z.join(e.cwd,".gitignore")).toString();s.add(d);}catch{}s.add(Er);for(let d of o.dirs){let w=Z.join(e.cwd,d);r.start(`Building ${N.cyan(w)}`);let x=Cr(w,{cwd:e.cwd,ignore:s,config:o});for(let C of x){if(i.find(S=>S.name===C.name)!==void 0){console.warn(`${D} ${ue} Skipped adding \`${N.cyan(`${d}/${C.name}`)}\` because a category with the same name already exists!`);continue}i.push(C);}r.stop(`Built ${N.cyan(w)}`);}let a=Rr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:f}=xr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||f.length>0)&&console.log(D);for(let d of l)console.log(d);if(f.length>0){for(let d of f)console.log(d);program.error(N.red(`Completed checking manifest with ${N.bold(`${f.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[m,h]=jr(c.categories);c.categories=m,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let b=Z.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${b}`),de.mkdirSync(b,{recursive:true}),t("Writing manifest to temp dir"),de.writeFileSync(Z.resolve(b,"jsrepo-manifest.json"),JSON.stringify(c));let p$1=Z.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),de.copyFileSync(p$1,Z.join(b,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let d of c.configFiles){let w=Z.join(e.cwd,d.path),x=Z.join(b,d.path),C=Z.join(x,"../");de.existsSync(C)||de.mkdirSync(C,{recursive:true}),de.copyFileSync(w,x);}t("Copied config files");}t("Copying registry files");for(let d of c.categories)for(let w of d.blocks){let x=Z.join(e.cwd,w.directory),C=Z.join(b,w.directory);for(let S of w.files){let X=Z.join(C,S,"../");de.existsSync(X)||de.mkdirSync(X,{recursive:true}),de.copyFileSync(Z.join(x,S),Z.join(C,S));}}t("Copied registry files");let u=Z.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),v$1=de.readdirSync(b);t("Creating archive file"),await oi.create({z:true,cwd:b,file:u},v$1),t("Created archive file"),t("Removing temp directory"),de.rmSync(b,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u)}...`);let g=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${N.cyan(g)}`),r.start(`Publishing ${N.bold(c.name)} to ${We}...`);let j=de.readFileSync(u);t("Removing archive file"),de.rmSync(u,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let R=await $e(`${w}/api/publish`,{body:j,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":g},method:"POST"});if(r.stop(`Got response from ${We}.`),R.ok){let d=await R.json();d.status==="dry-run"?log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} published ${N.greenBright(`@${d.scope}`)}/${d.registry}${N.greenBright(`@${d.version}`)}!`);}else {let d=await R.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(R.status)} ${d.message}`));}}var nc=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),uo=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=$.parse(nc,t);await ie(),await ic(e,r),outro(N.green("All done!"));});async function ic(e,t){let r=g=>{t.verbose&&console.info(`${Ee} ${g}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=ye(t.cwd).match(g=>g,g=>program.error(N.red(g))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let g=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(g=>g,({repo:g,message:j})=>{n.stop(`Failed to get info for ${N.cyan(g)}`),program.error(N.red(j));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await bt(s,{verbose:t.verbose?r:void 0})).match(g=>g,({repo:g,message:j})=>{n.stop(`Failed fetching blocks from ${N.cyan(g)}`),program.error(N.red(j));});r(`Retrieved blocks from ${N.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`);let c$1=Z.resolve(Z.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${N.bold(c$1)}.`),de.mkdirSync(c$1,{recursive:true});let l=()=>{de.rmSync(c$1,{recursive:true,force:true});},f=xt(a,o,t.cwd).map(g=>g.specifier),m=e;e.length===0&&(m=f),m.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let g of m){let j,R=z(g);if(R){let{url:d}=R.parse(g,{fullyQualified:true}),w=(await lt(d)).match(C=>C,C=>program.error(N.red(C))),x=(await bt([w])).match(C=>C,C=>program.error(N.red(C)));for(let[C,S]of x)a.set(C,S);j=a.get(g);}else for(let d of i){let w=z(d);if(!w)continue;let{url:x,specifier:C}=w.parse(c(d,g),{fullyQualified:true}),S=a.get(c(x,C));if(S!==void 0){j=S;break}}j||program.error(N.red(`Invalid block! ${N.bold(g)} does not exist!`)),h.push({name:g,block:j});}let b=Ue(o.paths,t.cwd).match(g=>g,g=>program.error(N.red(g)));for(let{block:g}of h){let j=g.sourceRepo,R=c(g.sourceRepo.url,g.category,g.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(R)}`),!g.tests){n.stop(`No tests found for ${N.cyan(R)}`);continue}let d=tr(g,b,t.cwd);d=Z.relative(c$1,d);let w=async C=>{let S=await Ge(j,C);return S.isErr()&&(n.stop(N.red(`Error fetching ${N.bold(C)}`)),program.error(N.red(`There was an error trying to get ${R}`))),S.unwrap()};r(`Downloading and copying test files for ${R}`);let x=[];for(let C of g.files.filter(S=>ct(S))){let S=await w(Z.join(g.directory,C)),X=Z.join(c$1,C);de.writeFileSync(X,S),x.push(X);}for(let C of x){r(`Opening test file ${C}`);let S=de.readFileSync(C).toString(),X=ls.parseSync(C,S);for(let oe of X.module.staticImports){let Y=oe.moduleRequest.value,k;if(Y.startsWith(".")&&(g.subdirectory?k=Z.join(d,g.name,Y):k=Z.join(d,Y)),k){let A=new RegExp(`(['"])${ts(Y)}\\1`,"g");S=S.replaceAll(A,`$1${k}$1`);}}de.writeFileSync(C,S);}r(`Completed ${N.cyan.bold(R)} test file`),t.verbose||n.stop(`Completed setup for ${N.bold(R)}`);}r("Beginning testing");let p=await detect({cwd:t.cwd});p==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(p.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${p.agent}'.`));let v=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(v)} on ${N.cyan(t.cwd)}`);try{let g=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let j of g)process.stdout.write(`${j}
97
106
  `);l();}catch(g){t.debug?console.info(`${N.bold("--debug")} flag provided. Skipping cleanup. Run '${N.bold(v)}' to retry tests.
98
- `):l(),program.error(N.red(`Tests failed! Error ${g}`));}}var dc=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Gt=["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(Gt.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=$.parse(dc,t);await ie(),await fc(e,r),outro(N.green("All done!"));});async function fc(e,t){let r=Te(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=Gt.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 Gt){if(s==="http"){await si(n);continue}if(n.get(s)===void 0){log.step(N.gray(`Already logged out of ${N.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${N.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:Gt.map(a=>({label:a,value:a})),initialValue:Gt[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:Gt[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 ${N.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 ${N.bold(i)}.`);}async function si(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(N.gray(`Already logged out of ${N.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${N.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var vc=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.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=$.parse(vc,t);await ie(),await wc(e,r),outro(N.green("All done!"));});async function wc(e,t){let r=d=>{t.verbose&&console.info(`${Pe} ${d}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Te(t.cwd).match(d=>d,d=>program.error(N.red(d))),i=n.repos;t.repo&&(i=[t.repo]);for(let d of e)y.find(w=>d.startsWith(w.name))&&program.error(N.red(`Invalid value provided for block names \`${N.bold(d)}\`. Block names are expected to be provided in the format of \`${N.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${N.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await ze(i,{noCache:!t.cache})).match(d=>d,({repo:d,message:w})=>{o.stop(`Failed to get info for ${N.cyan(d)}`),program.error(N.red(w));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Bt(s)).match(d=>d,({repo:d,message:w})=>{o.stop(`Failed fetching blocks from ${N.cyan(d)}`),program.error(N.red(w));}),c$1=Lt(a);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`),r(`Retrieved blocks from ${N.cyan(i.join(", "))}`);for(let d of a)Mt(d.state,d.manifest,t.cwd);let l=xt(c$1,n,t.cwd);l.length===0&&program.error(N.red(`You haven't installed any blocks yet. Did you mean to \`${N.bold("add")}\`?`));let f=e;if(t.all&&(f=l.map(d=>d.specifier)),f.length===0){let d=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(w=>w.block.list).map(w=>({label:`${N.cyan(w.block.category)}/${w.block.name}`,value:w.specifier})),required:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),f=d;}r(`Preparing to update ${N.cyan(f.join(", "))}`);let m=(await $t(f,c$1,s)).match(d=>d,program.error),h=new Set,b=new Set,{prettierOptions:p,biomeOptions:u}=await Ct({formatter:n.formatter,cwd:t.cwd}),v=Ue(n.paths,t.cwd).match(d=>d,d=>program.error(N.red(d))),g=_t(m,n);for(let d of g){let w=c(d.block.sourceRepo.url,d.block.category,d.block.name),x=ir(d.block.sourceRepo.url);r(`Attempting to update ${w}`),n.includeTests&&d.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let j of d.block.devDependencies)h.add(j);for(let j of d.block.dependencies)b.add(j);let C=await d.files;process.stdout.write(`${D}
107
+ `):l(),program.error(N.red(`Tests failed! Error ${g}`));}}var dc=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Gt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),go=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Gt.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=$.parse(dc,t);await ie(),await fc(e,r),outro(N.green("All done!"));});async function fc(e,t){let r=ye(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=Gt.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new pe;if(t.logout){if(o!==void 0){if(o==="http"){await ii(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of Gt){if(s==="http"){await ii(n);continue}if(n.get(s)===void 0){log.step(N.gray(`Already logged out of ${N.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${N.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:Gt.map(a=>({label:a,value:a})),initialValue:Gt[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:Gt[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 ${N.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 ${N.bold(i)}.`);}async function ii(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(N.gray(`Already logged out of ${N.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${N.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var vc=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),yo=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=$.parse(vc,t);await ie(),await wc(e,r),outro(N.green("All done!"));});async function wc(e,t){let r=d=>{t.verbose&&console.info(`${Ee} ${d}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=ye(t.cwd).match(d=>d,d=>program.error(N.red(d))),i=n.repos;t.repo&&(i=[t.repo]);for(let d of e)y.find(w=>d.startsWith(w.name))&&program.error(N.red(`Invalid value provided for block names \`${N.bold(d)}\`. Block names are expected to be provided in the format of \`${N.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${N.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await qe(i,{noCache:!t.cache})).match(d=>d,({repo:d,message:w})=>{o.stop(`Failed to get info for ${N.cyan(d)}`),program.error(N.red(w));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Bt(s)).match(d=>d,({repo:d,message:w})=>{o.stop(`Failed fetching blocks from ${N.cyan(d)}`),program.error(N.red(w));}),c$1=Lt(a);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`),r(`Retrieved blocks from ${N.cyan(i.join(", "))}`);for(let d of a)Mt(d.state,d.manifest,t.cwd);let l=xt(c$1,n,t.cwd);l.length===0&&program.error(N.red(`You haven't installed any blocks yet. Did you mean to \`${N.bold("add")}\`?`));let f=e;if(t.all&&(f=l.map(d=>d.specifier)),f.length===0){let d=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(w=>w.block.list).map(w=>({label:`${N.cyan(w.block.category)}/${w.block.name}`,value:w.specifier})),required:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),f=d;}r(`Preparing to update ${N.cyan(f.join(", "))}`);let m=(await $t(f,c$1,s)).match(d=>d,program.error),h=new Set,b=new Set,{prettierOptions:p,biomeOptions:u}=await Ct({formatter:n.formatter,cwd:t.cwd}),v=Ue(n.paths,t.cwd).match(d=>d,d=>program.error(N.red(d))),g=_t(m,n);for(let d of g){let w=c(d.block.sourceRepo.url,d.block.category,d.block.name),x=ir(d.block.sourceRepo.url);r(`Attempting to update ${w}`),n.includeTests&&d.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let S of d.block.devDependencies)h.add(S);for(let S of d.block.dependencies)b.add(S);let C=await d.files;process.stdout.write(`${D}
99
108
  `),process.stdout.write(`${D} ${w}
100
- `);for(let j of C){let X=j.content.match(y=>y,y=>program.error(N.red(y))),oe=or(j.name,d.block,v,t.cwd),Y=(await Xt({file:{content:X,destPath:oe},biomeOptions:u,prettierOptions:p,config:n,imports:d.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(y=>y,y=>program.error(N.red(y))),k="";de.existsSync(oe)&&(k=de.readFileSync(oe).toString());let A=await Dt({config:{biomeOptions:u,prettierOptions:p,formatter:n.formatter},current:{path:oe,content:k},incoming:{path:c(w,j.name),content:Y},options:{...t,loading:o,verbose:t.verbose?r:void 0}});A.applyChanges&&(o.start(`Writing changes to ${N.cyan(oe)}`),de.writeFileSync(oe,A.updatedContent),o.stop(`Wrote changes to ${N.cyan(oe)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",R=await Ze(b,h,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(R.dependencies.size>0||R.devDependencies.size>0){let d=[];if(!R.installed){if(b.size>0){let x=resolveCommand(S,"add",[...b]);d.push(`Install dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(h.size>0){let x=resolveCommand(S,"add",[...h,"-D"]);d.push(`Install dev dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}d=d.map((x,C)=>`${C+1}. ${x}`),R.installed||d.push(""),d.push("Import and use the blocks!");let w=ft(d);process.stdout.write(w);}}var Et=program.name(Ot.name).description(Ot.description).version(Ot.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
109
+ `);for(let S of C){let X=S.content.match(y=>y,y=>program.error(N.red(y))),oe=or(S.name,d.block,v,t.cwd),Y=(await Xt({file:{content:X,destPath:oe},biomeOptions:u,prettierOptions:p,config:n,imports:d.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(y=>y,y=>program.error(N.red(y))),k="";de.existsSync(oe)&&(k=de.readFileSync(oe).toString());let A=await Dt({config:{biomeOptions:u,prettierOptions:p,formatter:n.formatter},current:{path:oe,content:k},incoming:{path:c(w,S.name),content:Y},options:{...t,loading:o,verbose:t.verbose?r:void 0}});A.applyChanges&&(o.start(`Writing changes to ${N.cyan(oe)}`),de.writeFileSync(oe,A.updatedContent),o.stop(`Wrote changes to ${N.cyan(oe)}.`));}}let j=(await detect({cwd:t.cwd}))?.agent??"npm",R=await Ze(b,h,{yes:t.yes,no:t.no,cwd:t.cwd,pm:j});if(R.dependencies.size>0||R.devDependencies.size>0){let d=[];if(!R.installed){if(b.size>0){let x=resolveCommand(j,"add",[...b]);d.push(`Install dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(h.size>0){let x=resolveCommand(j,"add",[...h,"-D"]);d.push(`Install dev dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}d=d.map((x,C)=>`${C+1}. ${x}`),R.installed||d.push(""),d.push("Import and use the blocks!");let w=ft(d);process.stdout.write(w);}}var Et=program.name(Ot.name).description(Ot.description).version(Ot.version).addCommand(Qr).addCommand(eo).addCommand(to).addCommand(no).addCommand(io).addCommand(lo).addCommand(fo).addCommand(mo).addCommand(uo).addCommand(go).addCommand(yo);Et.parse();//# sourceMappingURL=index.js.map
101
110
  //# sourceMappingURL=index.js.map