jsrepo 2.0.2 → 2.0.4

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,y,c,v,l,n,o,x as x$1,a,u,t,b,A,z,k}from'./chunk-KTZ3UFRE.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import le from'node: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 X from'pathe';import*as $ from'valibot';import Zn from'is-unicode-supported';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import un from'validate-npm-package-name';import ri from'node:os';import {stripVTControlCharacters}from'node:util';import Mi from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import To from'boxen';import {diffLines,diffChars}from'diff';import Po from'semver';import {cursor,erase}from'sisteransi';import ci from'@anthropic-ai/sdk';import fi from'ollama';import mi from'openai';import ai from'conf';import vi from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as Vo from'css-dependency';import*as Jo from'prettier';import*as Go from'parse5';import Hi from'oxc-parser';import {walk}from'estree-walker';import*as nn from'svelte/compiler';import*as ln from'vue/compiler-sfc';import Fs from'node-machine-id';import Ws from'ignore';import*as Vn from'tar';var Rt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.0.2"};var ei=Zn(),ce=(e,t)=>ei?e:t,fo=ce("\u25C6","*"),mo=ce("\u25C6","*"),uo=ce("\u25A0","x"),T=N.gray(ce("\u2502","|")),Bt=N.gray(ce("\u2500","-")),go=N.gray(ce("\u2510","+")),ho=N.gray(ce("\u2518","+")),_t=N.gray(ce("\u251C","+")),yo=N.gray(ce("\u252C","+"));N.gray(ce("\u250C","T"));var vo=N.gray(ce("\u2514","-")),fe=N.bgRgb(245,149,66).black(" WARN "),je=N.bgBlueBright.white(" INFO "),Mt=N.bgRedBright.white(" ERROR "),Ge=N.hex("#f7df1e")("jsrepo"),Be=N.hex("#f7df1e").bold("jsrepo.com");function wo(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function bo(e,t){let r=0;for(let o of e)r=r+t(o);return r}function Wt(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}var oi=/\n|\r\n/g;function J(e){return e.split(oi)}function U(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Wt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(ri.EOL)}var ni={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},ii={"install-as-dev-dependency":"-D"},si={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},$o={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},xo={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Pr={bun:ni,npm:si,pnpm:$o,deno:ii,yarn:xo,"yarn@berry":xo,"pnpm@6":$o};function _e(){return new ai({projectName:"jsrepo"})}var Ir="http-registries-w-tokens",ge=class{#e;constructor(t){this.#e=t??_e();}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(Ir,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(Ir,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Ir);return t||[]}};var Dr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await Co("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Er({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 gi({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:Or(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 Co("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=Er({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 ui({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:Or(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=Er({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 hi({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Or(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function ui({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new mi({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 gi({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 hi({prompt:e,messages:t,model:r}){return (await fi.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function Er({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,y,a,v,u,b,B,A,l}from'./chunk-GJE55QJV.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import le from'node: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 ei from'is-unicode-supported';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import gn from'validate-npm-package-name';import oi from'node:os';import {stripVTControlCharacters}from'node:util';import Wi from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import No from'boxen';import {diffLines,diffChars}from'diff';import Io from'semver';import {cursor,erase}from'sisteransi';import li from'@anthropic-ai/sdk';import mi from'ollama';import ui from'openai';import ci from'conf';import wi from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as Jo from'css-dependency';import*as Uo from'prettier';import*as zo from'parse5';import qi from'oxc-parser';import {walk}from'estree-walker';import*as sn from'svelte/compiler';import*as dn from'vue/compiler-sfc';import Ls from'node-machine-id';import Vs from'ignore';import*as Jn from'tar';var Rt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.0.4"};var ti=ei(),ce=(e,t)=>ti?e:t,mo=ce("\u25C6","*"),uo=ce("\u25C6","*"),go=ce("\u25A0","x"),T=N.gray(ce("\u2502","|")),Bt=N.gray(ce("\u2500","-")),ho=N.gray(ce("\u2510","+")),yo=N.gray(ce("\u2518","+")),_t=N.gray(ce("\u251C","+")),vo=N.gray(ce("\u252C","+"));N.gray(ce("\u250C","T"));var wo=N.gray(ce("\u2514","-")),fe=N.bgRgb(245,149,66).black(" WARN "),je=N.bgBlueBright.white(" INFO "),Mt=N.bgRedBright.white(" ERROR "),Ge=N.hex("#f7df1e")("jsrepo"),Be=N.hex("#f7df1e").bold("jsrepo.com");function bo(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function ko(e,t){let r=0;for(let o of e)r=r+t(o);return r}function Wt(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}var ni=/\n|\r\n/g;function J(e){return e.split(ni)}function G(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Wt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(oi.EOL)}var ii={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},si={"install-as-dev-dependency":"-D"},ai={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},xo={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Co={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Pr={bun:ii,npm:ai,pnpm:xo,deno:si,yarn:Co,"yarn@berry":Co,"pnpm@6":xo};function _e(){return new ci({projectName:"jsrepo"})}var Ir="http-registries-w-tokens",ge=class{#e;constructor(t){this.#e=t??_e();}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(Ir,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(Ir,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Ir);return t||[]}};var Dr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await Ro("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Er({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 hi({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:Or(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 Ro("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=Er({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 gi({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:Or(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=Er({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 yi({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Or(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function gi({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new ui({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 hi({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new li({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 yi({prompt:e,messages:t,model:r}){return (await mi.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function Er({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}
@@ -14,70 +14,70 @@ ${t.content}
14
14
  </code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
15
15
  `}}function Or(e){let t=e.trim();if(t.startsWith("```")&&(t=J(t).slice(1).join(`
16
16
  `).trim()),t.endsWith("```")){let r=J(t);t=r.slice(0,r.length-1).join(`
17
- `).trim();}return t}async function Co(e){let t=new ge,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 ze=Rt;function Ro(e){return /^\s+$/g.test(e)}function St(e){let t=e.length-1;for(;Ro(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 So({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:p,intro:g}){let h="",w=bo(r,b=>b.count??0).toString().length+1,d=0;if(r.length===1&&!r[0].added&&!r[0].removed)return p({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:p,intro:g});h+=g({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:p,intro:g});let u=b=>N.gray(`${l?.()??""}${Wt(`${b+1+d} `,w)} `);for(let b=0;b<r.length;b++){let m=r[b],S=r[b-1]?.added||r[b-1]?.removed,v=r[b+1]?.added||r[b+1]?.removed;if(!m.added&&!m.removed){if(!o&&m.count!==void 0&&m.count>n){let x=d,R=J(St(m.value)),I=0;if(v&&(I+=n),S&&(I+=n),I>=R.length){h+=`${U(R,{prefix:u})}
19
- `,d+=R.length;continue}if(S&&(h+=`${U(R.slice(0,n),{prefix:u})}
20
- `),R.length>I){let re=R.length-I;h+=`${U(J(N.gray(`+ ${re} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Wt(" ",w)} `})}
21
- `;}v&&(d=d+R.length-n,h+=`${U(R.slice(R.length-n),{prefix:u})}
22
- `),d=x+m.count;continue}h+=`${U(J(St(m.value)),{prefix:u})}
23
- `,d+=m.count??0;continue}let f=x=>x.added?s(St(x.value)):x.removed?i(St(x.value)):x.value,C=x=>x.added?c(St(x.value)):x.removed?a(St(x.value)):x.value;if(m.removed&&m.count===1&&r[b+1]?.added&&r[b+1]?.count===1){let R=diffChars(m.value,r[b+1].value).map(I=>C(I)).join("");h+=`${u(0)}${R}`,d+=1,b++;}else Ro(m.value)?(h+=`${U(J(C(m)),{prefix:x=>`${u(x)}${C({removed:true,value:" ",added:false})}`})}
24
- `,m.removed||(d+=m.count??0)):(h+=`${U(J(f(m)),{prefix:u})}
17
+ `).trim();}return t}async function Ro(e){let t=new ge,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 ze=Rt;function So(e){return /^\s+$/g.test(e)}function St(e){let t=e.length-1;for(;So(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 jo({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:p,intro:g}){let h="",w=ko(r,b=>b.count??0).toString().length+1,d=0;if(r.length===1&&!r[0].added&&!r[0].removed)return p({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:p,intro:g});h+=g({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:p,intro:g});let u=b=>N.gray(`${l?.()??""}${Wt(`${b+1+d} `,w)} `);for(let b=0;b<r.length;b++){let m=r[b],S=r[b-1]?.added||r[b-1]?.removed,R=r[b+1]?.added||r[b+1]?.removed;if(!m.added&&!m.removed){if(!o&&m.count!==void 0&&m.count>n){let x=d,C=J(St(m.value)),j=0;if(R&&(j+=n),S&&(j+=n),j>=C.length){h+=`${G(C,{prefix:u})}
19
+ `,d+=C.length;continue}if(S&&(h+=`${G(C.slice(0,n),{prefix:u})}
20
+ `),C.length>j){let Q=C.length-j;h+=`${G(J(N.gray(`+ ${Q} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Wt(" ",w)} `})}
21
+ `;}R&&(d=d+C.length-n,h+=`${G(C.slice(C.length-n),{prefix:u})}
22
+ `),d=x+m.count;continue}h+=`${G(J(St(m.value)),{prefix:u})}
23
+ `,d+=m.count??0;continue}let f=x=>x.added?s(St(x.value)):x.removed?i(St(x.value)):x.value,v=x=>x.added?c(St(x.value)):x.removed?a(St(x.value)):x.value;if(m.removed&&m.count===1&&r[b+1]?.added&&r[b+1]?.count===1){let C=diffChars(m.value,r[b+1].value).map(j=>v(j)).join("");h+=`${u(0)}${C}`,d+=1,b++;}else So(m.value)?(h+=`${G(J(v(m)),{prefix:x=>`${u(x)}${v({removed:true,value:" ",added:false})}`})}
24
+ `,m.removed||(d+=m.count??0)):(h+=`${G(J(f(m)),{prefix:u})}
25
25
  `,m.removed||(d+=m.count??0));}return h.endsWith(`
26
26
  `)||(h=h+=`
27
- `),h}var Ne=vi.defaults({cachePath:X.join(import.meta.dirname,"cache")});var Tr="latest-version",bi=60*60*1e3;async function jo({noCache:e=false}={}){try{let t=_e(),r;if(!e){let i=t.get(Tr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Tr);}}let o=await Ne("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(Tr,{expiration:Date.now()+bi,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var ki=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,$i=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Ke(e){let t=ki.exec(e)||$i.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Ar(e,t){let r=X.join(e,"package.json");if(le.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Ar(o.slice(0,o.length-1).join("/"),t)}function Fr(e){if(!le.existsSync(e))return b(`${e} doesn't exist`);let t=le.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function rr(e){return e[0]==="^"?e.slice(1):e}function Eo(e,t,{cwd:r}){let o=e,n=t,i=Fr(X.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=Ke(a).unwrap(),p=s.dependencies[c];if(l===void 0&&p){o.delete(a);continue}p&&Po.satisfies(rr(p),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Ke(a).unwrap(),p=s.devDependencies[c];if(l===void 0&&p){n.delete(a);continue}p&&Po.satisfies(rr(p),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function No(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 Ao({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 dt(e){let t=To(e.join(`
28
- `),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(_t),bottomLeft:stripVTControlCharacters(_t),topRight:stripVTControlCharacters(go),top:stripVTControlCharacters(Bt),bottom:stripVTControlCharacters(Bt),bottomRight:stripVTControlCharacters(ho),left:stripVTControlCharacters(T),right:stripVTControlCharacters(T)}});return `${T}
27
+ `),h}var Ne=wi.defaults({cachePath:Z.join(import.meta.dirname,"cache")});var Tr="latest-version",ki=60*60*1e3;async function Po({noCache:e=false}={}){try{let t=_e(),r;if(!e){let i=t.get(Tr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Tr);}}let o=await Ne("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(Tr,{expiration:Date.now()+ki,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var $i=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,xi=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function Ke(e){let t=$i.exec(e)||xi.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Ar(e,t){let r=Z.join(e,"package.json");if(le.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Ar(o.slice(0,o.length-1).join("/"),t)}function Fr(e){if(!le.existsSync(e))return b(`${e} doesn't exist`);let t=le.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function or(e){return e[0]==="^"?e.slice(1):e}function Oo(e,t,{cwd:r}){let o=e,n=t,i=Fr(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}=Ke(a).unwrap(),p=s.dependencies[c];if(l===void 0&&p){o.delete(a);continue}p&&Io.satisfies(or(p),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=Ke(a).unwrap(),p=s.devDependencies[c];if(l===void 0&&p){n.delete(a);continue}p&&Io.satisfies(or(p),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function Ao(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 Fo({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 dt(e){let t=No(e.join(`
28
+ `),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(_t),bottomLeft:stripVTControlCharacters(_t),topRight:stripVTControlCharacters(ho),top:stripVTControlCharacters(Bt),bottom:stripVTControlCharacters(Bt),bottomRight:stripVTControlCharacters(yo),left:stripVTControlCharacters(T),right:stripVTControlCharacters(T)}});return `${T}
29
29
  ${t}
30
- `}function Fo(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 Ni(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 To(i.join(`
31
- `),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await jo();e.isOk()&&Po.lt(ze.version,e.unwrap())&&console.info(await Ni(ze.name,ze.version,e.unwrap())),intro(`${N.bgHex("#f7df1e").black(` ${ze.name} `)}${N.gray(` v${ze.version} `)}`);}var Do="model-preference";async function jt({incoming:e,current:t,config:r,options:o}){let n=_e();process.stdout.write(`${T}
32
- `);let i=false,s=e.content,a=n.get(Do,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),p=So({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:g,to:h,prefix:w})=>`${w?.()??""}${N.cyan(g)} \u2192 ${N.gray(h)} ${N.gray("(unchanged)")}
30
+ `}function Lo(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 Ai(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 No(i.join(`
31
+ `),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await Po();e.isOk()&&Io.lt(ze.version,e.unwrap())&&console.info(await Ai(ze.name,ze.version,e.unwrap())),intro(`${N.bgHex("#f7df1e").black(` ${ze.name} `)}${N.gray(` v${ze.version} `)}`);}var To="model-preference";async function jt({incoming:e,current:t,config:r,options:o}){let n=_e();process.stdout.write(`${T}
32
+ `);let i=false,s=e.content,a=n.get(To,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),p=jo({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:g,to:h,prefix:w})=>`${w?.()??""}${N.cyan(g)} \u2192 ${N.gray(h)} ${N.gray("(unchanged)")}
33
33
  `,intro:({from:g,to:h,changes:w,prefix:d})=>{let u=w.filter(b=>b.added||b.removed).length;return `${d?.()??""}${N.cyan(g)} \u2192 ${N.gray(h)} (${u} change${u===1?"":"s"})
34
34
  ${d?.()??""}
35
- `}});if(process.stdout.write(p),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let g=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?g.push({label:`\u2728 ${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"}):g.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:g});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let w=await select({message:"Select a model",options:Object.keys(Dr).map(u=>({label:u,value:u})),initialValue:a});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!==a&&n.set(Do,w),a=w;let d=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(d)&&(cancel("Canceled!"),process.exit(0));try{let{content:u,prompt:b}=await Dr[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?s:e.content,path:e.path},additionalInstructions:d!=="None"?d:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=u,c.push({role:"user",content:b}),c.push({role:"assistant",content:u});}catch(u){o.loading.stop(),log.error(N.red(`Error getting completions: ${u}`)),process.stdout.write(`${T}
36
- `);continue}s=await ir({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${T}
37
- `);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function He(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Eo(e,t,{cwd:n});if(a.size>0||c.size>0){let p=r;if(!r&&!o){let g=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),p=g;}if(p)return a.size>0&&await Lr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Lr({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 Lo(e){let t=N.dim(T),r=N.green(fo),o=N.green(mo),n=N.red(uo);process.stdout.write(`${t}
35
+ `}});if(process.stdout.write(p),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let g=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?g.push({label:`\u2728 ${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"}):g.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:g});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let w=await select({message:"Select a model",options:Object.keys(Dr).map(u=>({label:u,value:u})),initialValue:a});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!==a&&n.set(To,w),a=w;let d=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(d)&&(cancel("Canceled!"),process.exit(0));try{let{content:u,prompt:b}=await Dr[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?s:e.content,path:e.path},additionalInstructions:d!=="None"?d:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=u,c.push({role:"user",content:b}),c.push({role:"assistant",content:u});}catch(u){o.loading.stop(),log.error(N.red(`Error getting completions: ${u}`)),process.stdout.write(`${T}
36
+ `);continue}s=await sr({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${T}
37
+ `);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function He(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Oo(e,t,{cwd:n});if(a.size>0||c.size>0){let p=r;if(!r&&!o){let g=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),p=g;}if(p)return a.size>0&&await Lr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Lr({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 Bo(e){let t=N.dim(T),r=N.green(mo),o=N.green(uo),n=N.red(go);process.stdout.write(`${t}
38
38
  `),process.stdout.write(`${r} ${e}
39
39
  `);let i="",s="",a=(l=false)=>{if(!s)return;let p=process.stdout.columns,h=s.split(`
40
40
  `).reduce((w,d)=>w+Math.ceil(d.length/p),0)+(l?1:0);process.stdout.write(cursor.up(h)),process.stdout.write(erase.down());},c=(l=0)=>{let p=i.split(`
41
41
  `).slice(-l);s="";for(let g of p)s+=`${t} ${g}
42
42
  `;process.stdout.write(N.dim(s));};return {set text(l){a(),i+=l;let p=Math.ceil(process.stdout.rows/2);c(p);},fail(l){a(true),process.stdout.write(`${n} ${l}
43
43
  `),c();},success(l){a(true),process.stdout.write(`${o} ${l}
44
- `);}}}async function Lr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Pr[e]["install-as-dev-dependency"]);let s=Pr[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=Lo(`Installing dependencies with ${e}...`);try{let l=x(a.command,[...a.args],{nodeOptions:{cwd:o}});for await(let p of l)c.text=`${p}
45
- `;c.success(`Installed ${N.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var Bi=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function _o({template:e,config:t,destPath:r,cwd:o}){let n=X.join(r,"../");return e.replace(Bi,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=X.relative(n,X.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return X.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=X.relative(n,X.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return X.join(t.paths[s],a)})}async function Jt({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=ft.find(p=>p.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
44
+ `);}}}async function Lr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Pr[e]["install-as-dev-dependency"]);let s=Pr[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=Bo(`Installing dependencies with ${e}...`);try{let l=x(a.command,[...a.args],{nodeOptions:{cwd:o}});for await(let p of l)c.text=`${p}
45
+ `;c.success(`Installed ${N.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var _i=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function Mo({template:e,config:t,destPath:r,cwd:o}){let n=Z.join(r,"../");return e.replace(_i,(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 Jt({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=ft.find(p=>p.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(p){return b(`Error formatting ${N.bold(e.destPath)} ${p}`)}}for(let[p,g]of Object.entries(r)){let h=_o({template:g,config:t,destPath:e.destPath,cwd:s}),w=new RegExp(`(['"])${Mi(p)}\\1`,"g");l=l.replaceAll(w,`$1${h}$1`);}return a(l)}async function ir({file:e,formatter:t,prettierOptions:r,biomeOptions:o}){let n=ft.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 Wo(e){let t=[".js",".ts",".cjs",".mjs"];if(!k(e,t))return;let r=X.dirname(e),o=le.readdirSync(r),n=X.parse(e);for(let i of o)if(k(i,t)&&X.parse(i).name===n.name)return X.join(r,i)}function Pt(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 Uo={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=Vo.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ee({moduleSpecifiers:c.map(p=>p.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).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(p){return b(`Error formatting ${N.bold(e.destPath)} ${p}`)}}for(let[p,g]of Object.entries(r)){let h=Mo({template:g,config:t,destPath:e.destPath,cwd:s}),w=new RegExp(`(['"])${Wi(p)}\\1`,"g");l=l.replaceAll(w,`$1${h}$1`);}return a(l)}async function sr({file:e,formatter:t,prettierOptions:r,biomeOptions:o}){let n=ft.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 Vo(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=Z.dirname(e),o=le.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 Pt(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 Go={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=Jo.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ee({moduleSpecifiers:c.map(p=>p.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).join(`
48
48
  `)):a(l.unwrap())},comment:e=>`/*
49
- ${U(J(e),{prefix:()=>" "})}
50
- */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Jo.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 Ko={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=Go.parse(s),c=[],l=(g,h)=>{if(g&&(h(g),g.childNodes&&g.childNodes.length>0))for(let w of g.childNodes)l(w,h);};for(let g of a$1.childNodes)l(g,h=>{if(h.tagName==="script")for(let w of h.attrs)w.name==="src"&&c.push(w.value);if(h.tagName==="link"&&h.attrs.find(w=>w.name==="rel"&&w.value==="stylesheet"))for(let w of h.attrs)w.name==="href"&&!w.value.startsWith("http")&&c.push(w.value);});let p=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return p.isErr()?b(p.unwrapErr().map(g=>Ie(g)).join(`
49
+ ${G(J(e),{prefix:()=>" "})}
50
+ */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Uo.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 Ho={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=zo.parse(s),c=[],l=(g,h)=>{if(g&&(h(g),g.childNodes&&g.childNodes.length>0))for(let w of g.childNodes)l(w,h);};for(let g of a$1.childNodes)l(g,h=>{if(h.tagName==="script")for(let w of h.attrs)w.name==="src"&&c.push(w.value);if(h.tagName==="link"&&h.attrs.find(w=>w.name==="rel"&&w.value==="stylesheet"))for(let w of h.attrs)w.name==="href"&&!w.value.startsWith("http")&&c.push(w.value);});let p=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return p.isErr()?b(p.unwrapErr().map(g=>Ie(g)).join(`
51
51
  `)):a(p.unwrap())},comment:e=>`<!--
52
- ${U(J(e),{prefix:()=>" "})}
53
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Jo.format(e,{parser:"html",...r}):e};function ar(e,t){let r=Hi.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 qo={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=le.readFileSync(e).toString(),a$1=ar(e,s),c=Ee({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
+ ${G(J(e),{prefix:()=>" "})}
53
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"html",...r}):e};function cr(e,t){let r=qi.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 Yo={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=le.readFileSync(e).toString(),a$1=cr(e,s),c=Ee({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(`
54
54
  `)):a(c.unwrap())},comment:e=>`/*
55
- ${U(J(e),{prefix:()=>" "})}
56
- */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Jo.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 Qo=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Jo.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},cr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:Qo},Xo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
57
- ${U(J(e),{prefix:()=>" "})}
58
- */`,format:Qo};var tn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=Vo.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ee({moduleSpecifiers:c.map(p=>p.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).join(`
55
+ ${G(J(e),{prefix:()=>" "})}
56
+ */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Uo.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 Xo=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Uo.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},lr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:Xo},Zo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
57
+ ${G(J(e),{prefix:()=>" "})}
58
+ */`,format:Xo};var rn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=Jo.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ee({moduleSpecifiers:c.map(p=>p.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).join(`
59
59
  `)):a(l.unwrap())},comment:e=>`/*
60
- ${U(J(e),{prefix:()=>" "})}
61
- */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Jo.format(e,{parser:"scss",...r}):e};var sn={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=nn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=g=>{(g.type==="ImportDeclaration"||g.type==="ExportAllDeclaration"||g.type==="ExportNamedDeclaration")&&typeof g.source?.value=="string"&&c.push(g.source.value),g.type==="ImportExpression"&&g.source.type==="Literal"&&typeof g.source.value=="string"&&c.push(g.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let p=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return p.isErr()?b(p.unwrapErr().map(g=>Ie(g)).join(`
60
+ ${G(J(e),{prefix:()=>" "})}
61
+ */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"scss",...r}):e};var an={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=sn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=g=>{(g.type==="ImportDeclaration"||g.type==="ExportAllDeclaration"||g.type==="ExportNamedDeclaration")&&typeof g.source?.value=="string"&&c.push(g.source.value),g.type==="ImportExpression"&&g.source.type==="Literal"&&typeof g.source.value=="string"&&c.push(g.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let p=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return p.isErr()?b(p.unwrapErr().map(g=>Ie(g)).join(`
62
62
  `)):a(p.unwrap())},comment:e=>`<!--
63
- ${U(J(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 Jo.format(e,{filepath:r,...o}):e};var an={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
65
- ${U(J(e),{prefix:()=>" "})}
66
- -->`,format:async e=>e};var dn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=ln.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let p=ar("noop.ts",a$1.descriptor.script.content);c.push(...p);}if(a$1.descriptor.scriptSetup?.content){let p=ar("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...p);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).join(`
63
+ ${G(J(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 Uo.format(e,{filepath:r,...o}):e};var cn={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
65
+ ${G(J(e),{prefix:()=>" "})}
66
+ -->`,format:async e=>e};var pn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=le.readFileSync(e).toString(),a$1=dn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let p=cr("noop.ts",a$1.descriptor.script.content);c.push(...p);}if(a$1.descriptor.scriptSetup?.content){let p=cr("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...p);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Ee({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(p=>Ie(p)).join(`
67
67
  `)):a(l.unwrap())},comment:e=>`<!--
68
- ${U(J(e),{prefix:()=>" "})}
69
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Jo.format(e,{parser:"vue",...r}):e};var fn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>U(J(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Jo.format(e,{parser:"yaml",...r}):e};function Ie(e){return `${U(J(e),{prefix:t=>t===0?`${T} ${Mt} `:`${T} `})}`}function Ee({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,p={};for(let w of e){if(builtinModules.includes(w)||w.startsWith("node:"))continue;if(w.startsWith(".")){let m=gn(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(m.isErr()){a$1.push(m.unwrapErr());continue}let S=m.unwrap();S&&(l.add(S.dependency),p[w]=S.template);continue}let d=Ke(w);if(!d.isErr()){let m=d.unwrap();if(un(m.name).validForNewPackages){c.add(w);continue}}let u=rs(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(u.isErr()){a$1.push(u.unwrapErr());continue}let b=u.unwrap();b?(l.add(b.dependency),p[w]=b.template):console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(w)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:g,dependencies:h}=is(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:g,local:Array.from(l),imports:p})}function gn(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?X.join(o,"../"):X.join(r,"../"),l=X.join(X.join(r,"../"),e),p=X.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(p))return a(mn(l.slice(p.length),n));for(let g of s){let h=X.resolve(X.join(a$1,g)),w=X.resolve(l);if(w.startsWith(h))return a(mn(w.slice(h.length+1),n))}return b(`${r}:
70
- ${i||e} references code not contained in ${N.bold(s.join(", "))} and cannot be resolved.`)}function mn(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-X.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=X.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function rs(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Pt(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 p of l){let g=ns(p);if(!g)continue;let h=X.relative(X.resolve(X.join(r,"../")),g.prettyPath),w=os(g.prettyPath,g.path,[".js",".ts"]),d=gn(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:g.type==="file"});if(d.isErr())return b(d.unwrapErr());if(d.unwrap())return a(d.unwrap());break}}return a(void 0)}function os(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=X.parse(e),n=X.parse(t),i=X.join(o.dir,o.name),s=X.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function ns(e){if(le.existsSync(e))return {path:e,prettyPath:e,type:le.statSync(e).isDirectory()?"directory":"file"};let t=X.join(e,"../");if(!le.existsSync(t))return;let r=X.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(le.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=le.readdirSync(t);for(let n of o){let i=X.parse(n);if(i.name===r.base){let s=X.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:le.statSync(s).isDirectory()?"directory":"file"}}}}function is(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Ar(X.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(le.readFileSync(n,"utf-8"));for(let l of e){let p=Ke(l);if(p.isErr()){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let g=p.unwrap();if(!un(g.name).validForNewPackages){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(g.name))continue;let h;if(c!==void 0&&(h=c[g.name]),h!==void 0){i.add(`${g.name}@${h}`);continue}if(a!==void 0&&(h=a[g.name]),h!==void 0){s.add(`${g.name}@${h}`);continue}i.add(g.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ft=[Uo,Ko,cr,Xo,tn,sn,an,qo,dn,fn];var yn=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"]),vn=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),as=$.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")]),wn={"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=dr(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(dr(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=>Ke(o).unwrap().name).filter(o=>yn.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)le.existsSync(X.join(t,o.path))||r.push(`The ${N.bold(o.name)} config file doesn't exist at ${N.bold(X.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=>Ke(n).unwrap().name).filter(n=>yn.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}}}},bn=$.record(as,$.union([vn,$.tupleWithRest([vn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),Ut={"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 pr(e,t,r,o=Ut){let n=[],i=[];for(let[s,a]of Object.entries(wn)){if(a.scope==="block")continue;let c=o[s],l,p=[];if(Array.isArray(c)?(l=c[0],p.push(...c.slice(1))):l=c,l==="off")continue;let g=a.check({manifest:e,options:p,cwd:r,config:t});if(g){if(l==="error"){i.push(...g.map(h=>`${T} ${Mt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...g.map(h=>`${T} ${fe} ${h} ${N.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(wn)){if(l.scope==="global")continue;let p=o[c],g,h=[];if(Array.isArray(p)?(g=p[0],h.push(...p.slice(1))):g=p,g==="off")continue;let w=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(w){if(g==="error"){i.push(...w.map(d=>`${T} ${Mt} ${N.red(d)} ${N.gray(c)}`));continue}n.push(...w.map(d=>`${T} ${fe} ${d} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function dr(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(p=>p.name===s)?.blocks.find(p=>p.name===a);if(!c)continue;let l=dr(e,c,r,n);if(l)return [...l,e]}}function kn(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(dr(e,o,t))return true}return false}var Rn=[".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 nt(e){return Rn.find(t=>e.endsWith(t))!==void 0}function fr(e,{cwd:t,ignore:r,config:o}){let n;try{n=le.readdirSync(e);}catch{program.error(N.red(`Couldn't read the ${N.bold(e)} directory.`));}let i=[];for(let s of n){let a=X.join(e,s);if(le.statSync(a).isFile())continue;let c=`${X.relative(t,a)}/`;if(r.ignores(c))continue;let l=X.basename(s);if(!ls(l,o))continue;let p=cs(l,o),g={name:l,blocks:[]},h=le.readdirSync(a);for(let w of h){let d=X.join(a,w);if(le.statSync(d).isFile()){if(nt(w))continue;let u=ds(w),b=$n(u,o);if(!xn(u,o))continue;let m=ft.find(I=>I.matches(w));if(!m){console.warn(`${T} ${fe} Skipped \`${N.bold(d)}\` \`*${N.bold(X.parse(w).ext)}\` files are not currently supported!`);continue}let S=h.find(I=>Rn.find(re=>I===`${u}${re}`)),{dependencies:v,devDependencies:f,local:C,imports:x}=m.resolveDependencies({filePath:d,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(I=>I,I=>{program.error(N.red(I));}),R={name:u,directory:X.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:p?b:false,files:[w],localDependencies:C,_imports_:x,dependencies:v,devDependencies:f};S!==void 0&&R.files.push(S),g.blocks.push(R);}else {let u=w,b=$n(u,o);if(!xn(u,o))continue;let m=new Set,S=new Set,v=new Set,f={},C=false,x=[],R=(re,oe)=>{for(let q of oe){let k=X.join(re,q),A=k.slice(d.length+1);if(nt(q)){C=true,x.push(A);continue}if(le.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${fe} Skipped \`${N.bold(X.join(d,q))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let V=le.readdirSync(k);R(k,V);continue}let y=ft.find(V=>V.matches(q));if(!y){console.warn(`${T} ${fe} Skipped \`${k}\` \`*${N.bold(X.parse(q).ext)}\` files are not currently supported!`);continue}let{local:M,dependencies:j,devDependencies:W,imports:ee}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:d,filePath:k,cwd:t}).match(V=>V,V=>{program.error(N.red(V));});for(let V of M)V!==`${l}/${u}`&&m.add(V);for(let V of j)S.add(V);for(let V of W)v.add(V);for(let[V,et]of Object.entries(ee))f[V]=et;x.push(A);}};R(d,le.readdirSync(d));let I={name:u,directory:X.relative(t,d),category:l,tests:C,subdirectory:true,list:p?b:false,files:x,localDependencies:Array.from(m.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(v.keys()),_imports_:f};g.blocks.push(I);}}i.push(g);}return i}function mr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ft.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:X.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 $n(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function xn(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 ls(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function ds(e){return X.parse(X.basename(e)).name}function ur(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!kn(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var yr=[".git","node_modules"],gt="jsrepo.json",ht="jsrepo-build-config.json",_r=$.union([$.literal("prettier"),$.literal("biome")]),fs=$.objectWithRest({"*":$.string()},$.string()),Mr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:fs,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(_r)});function Oe(e){if(!le.existsSync(X.join(e,gt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(Mr,JSON.parse(le.readFileSync(X.join(e,gt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${gt}\` file!`)}var ms=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),meta:$.optional(f),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(bn)});function It(e){if(!le.existsSync(X.join(e,ht)))return a(null);let t=$.safeParse(ms,JSON.parse(le.readFileSync(X.join(e,ht)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ht}\` file!`)}function We(e,t){let r=Pt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=X.relative(t,X.join(X.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=us(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 us(e,t,r){let o=t(e);return o.length>0?X.relative(r,o[0]):void 0}function zt(e,t,r){let o;return t[e.category]!==void 0?o=X.join(r,t[e.category]):o=X.join(r,t["*"],e.category),o}async function it(e,t,{verbose:r}={}){return await z(e,t,{verbose:r,fetch:Ne,token:Wr(e.provider,e.url)})}async function vr(e,{verbose:t}={}){return await A(e,{verbose:t,fetch:Ne,token:Wr(e.provider,e.url)})}function Wr(e,t){let r=new ge;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function Kt(e,{noCache:t$1=false}={}){let r=y(e);if(r){let o=_e();if(r.name!==t.name&&!t$1)if(t$1)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:Wr(r,n.url),fetch:Ne});return r.name!==t.name&&!t$1&&o.set(`${e}-state`,i),a(i)}return b(`Only ${x$1.map((o,n)=>`${n===x$1.length-1?"and ":""}${N.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function st(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Kt(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 Ht(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await vr(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 wr(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 br(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await vr(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 yt(e,t,r,o=new Map){let n=new Map;for(let i of e){let s,a=y(i);if(a){let{url:l,specifier:p}=a.parse(i,{fullyQualified:true});s=t.get(c(l,p));}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:p,specifier:g}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(p,g));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 yt(s.localDependencies.filter(p=>!n.has(p)&&!o.has(p)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let p of l.unwrap())n.set(`${p.category}/${p.name}`,p);}}return a(wo(n,(i,s)=>s))}function vt(e,t,r){let o=[],n=We(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=zt(s,n,r),c=X.join(a,s.files[0]);s.subdirectory&&(c=X.join(a,s.name)),le.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function $r(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>nt(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await it(o.sourceRepo,X.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function Yt(e,t,r,o){let n=zt(t,r,o);return t.subdirectory?X.join(n,t.name,e):X.join(n,e)}function Sn(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 jn(e){return new Promise(t=>t(e))}async function wt({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await Jo.resolveConfig(X.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=X.join(t,"biome.json");le.existsSync(n)&&(o=JSON.parse(le.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function Qt(e){return `Installed from ${e}`}function Dt(e,t,r){if(!t.peerDependencies)return;let o=Fr(X.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 p=n[s];if(!p){i.push({name:s,expected:c,message:l,version:p,exists:false});continue}Po.satisfies(rr(p),c)||i.push({name:s,expected:c,message:l,version:p,exists:true});}if(i.length>0){process.stdout.write(`${T}
71
- ${N.yellow("\u25B2")} ${yo} Issues with ${N.bold(e.url)} peer dependencies
72
- `);let s=i.map((a,c)=>{let l=i.length-1===c,p;a.exists?p=`${N.yellowBright("x unmet peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)} >> found ${N.yellowBright.bold(a.version)}`:p=`${N.red("x missing peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)}`;let g=`${T} ${l?vo:_t}${Bt} ${p}`;return a.message?`${g}
68
+ ${G(J(e),{prefix:()=>" "})}
69
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"vue",...r}):e};var mn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>G(J(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"yaml",...r}):e};function Ie(e){return `${G(J(e),{prefix:t=>t===0?`${T} ${Mt} `:`${T} `})}`}function Ee({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,p={};for(let w of e){if(builtinModules.includes(w)||w.startsWith("node:"))continue;if(w.startsWith(".")){let m=hn(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(m.isErr()){a$1.push(m.unwrapErr());continue}let S=m.unwrap();S&&(l.add(S.dependency),p[w]=S.template);continue}let d=Ke(w);if(!d.isErr()){let m=d.unwrap();if(gn(m.name).validForNewPackages){c.add(w);continue}}let u=os(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(u.isErr()){a$1.push(u.unwrapErr());continue}let b=u.unwrap();b?(l.add(b.dependency),p[w]=b.template):console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(w)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:g,dependencies:h}=ss(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:g,local:Array.from(l),imports:p})}function hn(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),p=Z.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(p))return a(un(l.slice(p.length),n));let g=Z.resolve(l),h=null;for(let w of s){let d=Z.resolve(Z.join(a$1,w));g.startsWith(d)&&(h===null||h.length<d.length)&&(h=d);}return h!==null?a(un(g.slice(h.length+1),n)):b(`${r}:
70
+ ${i||e} references code not contained in ${N.bold(s.join(", "))} and cannot be resolved.`)}function un(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 os(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Pt(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 p of l){let g=is(p);if(!g)continue;let h=Z.relative(Z.resolve(Z.join(r,"../")),g.prettyPath),w=ns(g.prettyPath,g.path,[".js",".ts"]),d=hn(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:g.type==="file"});if(d.isErr())return b(d.unwrapErr());if(d.unwrap())return a(d.unwrap());break}}return a(void 0)}function ns(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 is(e){if(le.existsSync(e))return {path:e,prettyPath:e,type:le.statSync(e).isDirectory()?"directory":"file"};let t=Z.join(e,"../");if(!le.existsSync(t))return;let r=Z.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(le.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=le.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:le.statSync(s).isDirectory()?"directory":"file"}}}}function ss(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Ar(Z.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(le.readFileSync(n,"utf-8"));for(let l of e){let p=Ke(l);if(p.isErr()){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let g=p.unwrap();if(!gn(g.name).validForNewPackages){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(g.name))continue;let h;if(c!==void 0&&(h=c[g.name]),h!==void 0){i.add(`${g.name}@${h}`);continue}if(a!==void 0&&(h=a[g.name]),h!==void 0){s.add(`${g.name}@${h}`);continue}i.add(g.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ft=[Go,Ho,lr,Zo,rn,an,cn,Yo,pn,mn];var vn=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"]),wn=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),cs=$.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")]),bn={"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=pr(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(pr(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=>Ke(o).unwrap().name).filter(o=>vn.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)le.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=>Ke(n).unwrap().name).filter(n=>vn.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}}}},kn=$.record(cs,$.union([wn,$.tupleWithRest([wn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),Ut={"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 fr(e,t,r,o=Ut){let n=[],i=[];for(let[s,a]of Object.entries(bn)){if(a.scope==="block")continue;let c=o[s],l,p=[];if(Array.isArray(c)?(l=c[0],p.push(...c.slice(1))):l=c,l==="off")continue;let g=a.check({manifest:e,options:p,cwd:r,config:t});if(g){if(l==="error"){i.push(...g.map(h=>`${T} ${Mt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...g.map(h=>`${T} ${fe} ${h} ${N.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(bn)){if(l.scope==="global")continue;let p=o[c],g,h=[];if(Array.isArray(p)?(g=p[0],h.push(...p.slice(1))):g=p,g==="off")continue;let w=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(w){if(g==="error"){i.push(...w.map(d=>`${T} ${Mt} ${N.red(d)} ${N.gray(c)}`));continue}n.push(...w.map(d=>`${T} ${fe} ${d} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function pr(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(p=>p.name===s)?.blocks.find(p=>p.name===a);if(!c)continue;let l=pr(e,c,r,n);if(l)return [...l,e]}}function $n(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(pr(e,o,t))return true}return false}var Sn=[".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 nt(e){return Sn.find(t=>e.endsWith(t))!==void 0}function mr(e,{cwd:t,ignore:r,config:o}){let n;try{n=le.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(le.statSync(a).isFile())continue;let c=`${Z.relative(t,a)}/`;if(r.ignores(c))continue;let l=Z.basename(s);if(!ds(l,o))continue;let p=ls(l,o),g={name:l,blocks:[]},h=le.readdirSync(a);for(let w of h){let d=Z.join(a,w);if(le.statSync(d).isFile()){if(nt(w))continue;let u=ps(w),b=xn(u,o);if(!Cn(u,o))continue;let m=ft.find(j=>j.matches(w));if(!m){console.warn(`${T} ${fe} Skipped \`${N.bold(d)}\` \`*${N.bold(Z.parse(w).ext)}\` files are not currently supported!`);continue}let S=h.find(j=>Sn.find(Q=>j===`${u}${Q}`)),{dependencies:R,devDependencies:f,local:v,imports:x}=m.resolveDependencies({filePath:d,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:p?b:false,files:[w],localDependencies:v,_imports_:x,dependencies:R,devDependencies:f};S!==void 0&&C.files.push(S),g.blocks.push(C);}else {let u=w,b=xn(u,o);if(!Cn(u,o))continue;let m=new Set,S=new Set,R=new Set,f={},v=false,x=[],C=(Q,oe)=>{for(let q of oe){let k=Z.join(Q,q),A=k.slice(d.length+1);if(nt(q)){v=true,x.push(A);continue}if(le.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${fe} Skipped \`${N.bold(Z.join(d,q))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let V=le.readdirSync(k);C(k,V);continue}let y=ft.find(V=>V.matches(q));if(!y){console.warn(`${T} ${fe} Skipped \`${k}\` \`*${N.bold(Z.parse(q).ext)}\` files are not currently supported!`);continue}let{local:M,dependencies:P,devDependencies:W,imports:te}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:d,filePath:k,cwd:t}).match(V=>V,V=>{program.error(N.red(V));});for(let V of M)V!==`${l}/${u}`&&m.add(V);for(let V of P)S.add(V);for(let V of W)R.add(V);for(let[V,et]of Object.entries(te))f[V]=et;x.push(A);}};C(d,le.readdirSync(d));let j={name:u,directory:Z.relative(t,d),category:l,tests:v,subdirectory:true,list:p?b:false,files:x,localDependencies:Array.from(m.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(R.keys()),_imports_:f};g.blocks.push(j);}}i.push(g);}return i}function ur(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ft.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 xn(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function Cn(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function ls(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function ds(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function ps(e){return Z.parse(Z.basename(e)).name}function gr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!$n(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var vr=[".git","node_modules"],gt="jsrepo.json",ht="jsrepo-build-config.json",_r=$.union([$.literal("prettier"),$.literal("biome")]),ms=$.objectWithRest({"*":$.string()},$.string()),Mr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:ms,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(_r)});function Oe(e){if(!le.existsSync(Z.join(e,gt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(Mr,JSON.parse(le.readFileSync(Z.join(e,gt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${gt}\` file!`)}var us=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),access:$.optional(j),meta:$.optional(f),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(kn)});function It(e){if(!le.existsSync(Z.join(e,ht)))return a(null);let t=$.safeParse(us,JSON.parse(le.readFileSync(Z.join(e,ht)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ht}\` file!`)}function We(e,t){let r=Pt(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=gs(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 gs(e,t,r){let o=t(e);return o.length>0?Z.relative(r,o[0]):void 0}function zt(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 it(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:Ne,token:Wr(e.provider,e.url)})}async function wr(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Ne,token:Wr(e.provider,e.url)})}function Wr(e,t){let r=new ge;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function Kt(e,{noCache:t=false}={}){let r=z(e);if(r){let o=_e();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:Wr(r,n.url),fetch:Ne});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 st(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Kt(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 Ht(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await wr(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 br(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 kr(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await wr(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 yt(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:p}=a.parse(i,{fullyQualified:true});s=t.get(c(l,p));}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:p,specifier:g}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(p,g));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 yt(s.localDependencies.filter(p=>!n.has(p)&&!o.has(p)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let p of l.unwrap())n.set(`${p.category}/${p.name}`,p);}}return a(bo(n,(i,s)=>s))}function vt(e,t,r){let o=[],n=We(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=zt(s,n,r),c=Z.join(a,s.files[0]);s.subdirectory&&(c=Z.join(a,s.name)),le.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function xr(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>nt(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await it(o.sourceRepo,Z.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function Yt(e,t,r,o){let n=zt(t,r,o);return t.subdirectory?Z.join(n,t.name,e):Z.join(n,e)}function jn(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 Pn(e){return new Promise(t=>t(e))}async function wt({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await Uo.resolveConfig(Z.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Z.join(t,"biome.json");le.existsSync(n)&&(o=JSON.parse(le.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function Qt(e){return `Installed from ${e}`}function Dt(e,t,r){if(!t.peerDependencies)return;let o=Fr(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 p=n[s];if(!p){i.push({name:s,expected:c,message:l,version:p,exists:false});continue}Io.satisfies(or(p),c)||i.push({name:s,expected:c,message:l,version:p,exists:true});}if(i.length>0){process.stdout.write(`${T}
71
+ ${N.yellow("\u25B2")} ${vo} Issues with ${N.bold(e.url)} peer dependencies
72
+ `);let s=i.map((a,c)=>{let l=i.length-1===c,p;a.exists?p=`${N.yellowBright("x unmet peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)} >> found ${N.yellowBright.bold(a.version)}`:p=`${N.red("x missing peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)}`;let g=`${T} ${l?wo:_t}${Bt} ${p}`;return a.message?`${g}
73
73
  ${T} ${l?"":T} ${N.gray(a.message)}`:g}).join(`
74
74
  `);process.stdout.write(`${s}
75
- `);}}var Ps=$.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()}),Ur=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.",Sn,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(Ps,t);await ie(),await Is(e,r),outro(N.green("All done!"));});async function Is(e,t){let r=k=>{t.verbose&&console.info(`${je} ${k}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(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 ${Ge} 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=y(k);if(!A){l=true;continue}let{url:y$1}=A.parse(k,{fullyQualified:true});if(!(!s.repos.find(j=>j===y$1)&&!c$1.has(y$1))){if(!t.allow){let j=await confirm({message:`Allow ${Ge} to download and run code from ${N.cyan(y$1)}?`,initialValue:true});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(y$1);}c$1.add(y$1);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let k=await confirm({message:`Allow ${Ge} 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 p=(await st(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 g=(await br(p,{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=wr(g);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(a.join(", "))}`),r(`Retrieved blocks from ${N.cyan(a.join(", "))}`);for(let k of g)Dt(k.state,k.manifest,t.cwd);let w=vt(h,s,t.cwd).map(k=>k.specifier),d=e;if(d.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 M=`${y.category}/${y.name}`,j=w.findIndex(ee=>ee===M)!==-1,W;return a.length>1?W=`${N.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:W=`${N.cyan(y.category)}/${y.name}`,{label:j?N.gray(W):W,value:A,hint:j?"Installed":void 0}}),required:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),d=k;}r(`Installing blocks ${N.cyan(d.join(", "))}`);let u=(await yt(d,h,p)).match(k=>k,k=>program.error(k)),b=new Set,m=new Set,S=_e();if(i){let k=`${t.cwd}-zero-config`,A=$.safeParse(Mr,S.get(k)),y=A.success?A.output:s,M=Array.from(new Set(u.map(j=>j.category)));if(t.paths===void 0)for(let j of M){let W=await text({message:`Where would you like to add ${N.cyan(j)}?`,placeholder:y?y.paths[j]:`./src/${j}`,initialValue:y?y.paths[j]:`./src/${j}`,defaultValue:y?y.paths[j]:`./src/${j}`,validate(ee){if(ee.trim()==="")return "Please provide a value"}});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),s.paths[j]=W;}if(!t.yes&&t.tests===void 0){let j=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=j;}if(!t.yes&&t.watermark===void 0){let j=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),s.watermark=j;}if(t.formatter===void 0){let j="none";le.existsSync(X.join(t.cwd,".prettierrc"))&&(j="prettier"),le.existsSync(X.join(t.cwd,"biome.json"))&&(j="biome");let W=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(ee=>({value:ee.toLowerCase(),label:ee})),initialValue:j==="none"?y.formatter?y.formatter:"none":j});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),W!=="none"&&(s.formatter=W);}S.set(k,s),w=vt(h,s,t.cwd).map(j=>j.specifier);}let{prettierOptions:v,biomeOptions:f}=await wt({formatter:s.formatter,cwd:t.cwd}),C=We(s.paths,t.cwd).match(k=>k,k=>program.error(N.red(k))),x=new Set,R,I=$r(u,s),re=[];for(let k of I){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 M=w.find(j=>y===j);s.includeTests&&k.block.tests&&(r("Trying to include tests"),b.add("vitest"));for(let j of k.block.devDependencies)b.add(j);for(let j of k.block.dependencies)m.add(j);if(M&&!t.yes&&!R){if(R===void 0){let j=u.map(ee=>`${ee.category}/${ee.name}`).filter(ee=>w.find(V=>V===ee));log.warn(`The following components ${N.bold.yellow("already exist")}: ${N.cyan(Fo(j))}`);let W=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(W)&&(cancel("Canceled!"),process.exit(0)),R=W;}if(!R){let j=await k.files;process.stdout.write(`${T}
75
+ `);}}var Is=$.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()}),Ur=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.",jn,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(Is,t);await ie(),await Es(e,r),outro(N.green("All done!"));});async function Es(e,t){let r=k=>{t.verbose&&console.info(`${je} ${k}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(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 ${Ge} 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 ${Ge} 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 ${Ge} 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 p=(await st(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 g=(await kr(p,{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=br(g);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(a.join(", "))}`),r(`Retrieved blocks from ${N.cyan(a.join(", "))}`);for(let k of g)Dt(k.state,k.manifest,t.cwd);let w=vt(h,s,t.cwd).map(k=>k.specifier),d=e;if(d.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 M=`${y.category}/${y.name}`,P=w.findIndex(te=>te===M)!==-1,W;return a.length>1?W=`${N.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:W=`${N.cyan(y.category)}/${y.name}`,{label:P?N.gray(W):W,value:A,hint:P?"Installed":void 0}}),required:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),d=k;}r(`Installing blocks ${N.cyan(d.join(", "))}`);let u=(await yt(d,h,p)).match(k=>k,k=>program.error(k)),b=new Set,m=new Set,S=_e();if(i){let k=`${t.cwd}-zero-config`,A=$.safeParse(Mr,S.get(k)),y=A.success?A.output:s,M=Array.from(new Set(u.map(P=>P.category)));if(t.paths===void 0)for(let P of M){let W=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(W)&&(cancel("Canceled!"),process.exit(0)),s.paths[P]=W;}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";le.existsSync(Z.join(t.cwd,".prettierrc"))&&(P="prettier"),le.existsSync(Z.join(t.cwd,"biome.json"))&&(P="biome");let W=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(W)&&(cancel("Canceled!"),process.exit(0)),W!=="none"&&(s.formatter=W);}S.set(k,s),w=vt(h,s,t.cwd).map(P=>P.specifier);}let{prettierOptions:R,biomeOptions:f}=await wt({formatter:s.formatter,cwd:t.cwd}),v=We(s.paths,t.cwd).match(k=>k,k=>program.error(N.red(k))),x=new Set,C,j=xr(u,s),Q=[];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 M=w.find(P=>y===P);s.includeTests&&k.block.tests&&(r("Trying to include tests"),b.add("vitest"));for(let P of k.block.devDependencies)b.add(P);for(let P of k.block.dependencies)m.add(P);if(M&&!t.yes&&!C){if(C===void 0){let P=u.map(te=>`${te.category}/${te.name}`).filter(te=>w.find(V=>V===te));log.warn(`The following components ${N.bold.yellow("already exist")}: ${N.cyan(Lo(P))}`);let W=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(W)&&(cancel("Canceled!"),process.exit(0)),C=W;}if(!C){let P=await k.files;process.stdout.write(`${T}
76
76
  `),process.stdout.write(`${T} ${A}
77
- `);for(let W of j){let ee=W.content.match(Se=>Se,Se=>program.error(N.red(Se))),V=Yt(W.name,k.block,C,t.cwd),et=(await Jt({file:{content:ee,destPath:V},biomeOptions:f,prettierOptions:v,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Se=>Se,Se=>program.error(N.red(Se))),Re="";le.existsSync(V)&&(Re=le.readFileSync(V).toString());let te=await jt({config:{biomeOptions:f,prettierOptions:v,formatter:s.formatter},current:{path:V,content:Re},incoming:{path:c(A,W.name),content:et},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});te.applyChanges&&(re.push(jn({destination:V,content:te.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(j=>{j.map(async W=>{let ee=W.content.match(Re=>Re,Re=>program.error(N.red(Re))),V=Yt(W.name,k.block,C,t.cwd),et=Jt({file:{content:ee,destPath:V},biomeOptions:f,prettierOptions:v,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Re=>(Re.isErr()&&program.error(N.red(Re.unwrapErr())),{destination:V,content:Re.unwrap(),block:k.block}));re.push(et);});}),x.add(y);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(I.map(k=>k.files)),await Promise.all(re.map(async k=>{let A=await k,y=X.dirname(A.destination);le.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),le.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),le.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",q=await He(m,b,{yes:t.yes,cwd:t.cwd,pm:oe});if(q.dependencies.size>0||q.devDependencies.size>0){let k=[];if(!q.installed){if(m.size>0){let y=resolveCommand(oe,"add",[...m]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(b.size>0){let y=resolveCommand(oe,"add",[...b,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,M)=>`${M+1}. ${y}`),q.installed||k.push(""),k.push("Import and use the blocks!");let A=dt(k);process.stdout.write(A);}}function Nn(e){return new Promise(t=>setTimeout(t,e))}var Ls=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),zr=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(Ls,e);await ie(),await Bs(t),outro(N.green("All done!"));});async function Bs(e){let t=new ge;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Be}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Be}!`);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=Fs.machineIdSync(true),o;try{let a=await Ne(`${v}/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(`${v}/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 Nn(5e3);let a=`${v}/api/login/device/${o}`;try{let c=await Ne(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 ${Be}!`);break}catch{}}}var Vs=$.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()}),Kr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${l}\` 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 \`${l}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Vs,e);await ie(),await Js(t),outro(N.green("All done!"));});async function Js(e){let t=d=>{e.verbose&&console.info(`${je} ${d}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n$1=It(e.cwd).match(d=>{if(d===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let u=d;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={...Ut,...u.rules},u},d=>program.error(N.red(d))),i;n$1.outputDir?i=X.join(e.cwd,n$1.outputDir):i=e.cwd;let s=X.join(i,l);if(e.output&&le.existsSync(s)){if(n$1.outputDir){let d=n(le.readFileSync(s).toString());if(d.isOk())for(let u of d.unwrap().categories)for(let b of u.blocks){let m=X.join(i,b.directory);le.existsSync(m)&&le.rmSync(m,{recursive:true});}}le.rmSync(s);}let a=Ws();try{let d=le.readFileSync(X.join(e.cwd,".gitignore")).toString();a.add(d);}catch{}a.add(yr);for(let d of n$1.dirs){let u=X.join(e.cwd,d);r.start(`Building ${N.cyan(u)}`);let b=fr(u,{cwd:e.cwd,ignore:a,config:n$1});for(let m of b){if(o$1.find(S=>S.name===m.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${d}/${m.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(m);}r.stop(`Built ${N.cyan(u)}`);}let c=mr(n$1,{cwd:e.cwd}),l$1=o(o$1,c,n$1);r.start("Checking manifest");let{warnings:p,errors:g}=pr(l$1,n$1,e.cwd,n$1.rules);r.stop("Completed checking manifest."),(p.length>0||g.length>0)&&console.log(T);for(let d of p)console.log(d);if(g.length>0){for(let d of g)console.log(d);program.error(N.red(`Completed checking manifest with ${N.bold(`${g.length} error(s)`)} and ${N.bold(`${p.length} warning(s)`)}`));}let[h,w]=ur(l$1.categories);if(l$1.categories=h,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n$1.preview){let d=l$1.categories.flatMap(u=>u.blocks.filter(b=>b.list).map(b=>`${N.cyan(b.category)}/${b.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of d)console.log(`${T} \u25FB ${u}`);}if(e.output){if(n$1.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l$1.configFiles)for(let d of l$1.configFiles){let u=X.join(e.cwd,d.path),b=X.join(i,d.path),m=X.join(b,"../");le.existsSync(m)||le.mkdirSync(m,{recursive:true}),le.copyFileSync(u,b);}for(let d of l$1.categories)for(let u of d.blocks){let b=X.join(e.cwd,u.directory),m=X.join(i,u.directory);for(let S of u.files){let v=X.join(m,S,"../");le.existsSync(v)||le.mkdirSync(v,{recursive:true}),le.copyFileSync(X.join(b,S),X.join(m,S));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),le.writeFileSync(s,JSON.stringify(l$1,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var Ys=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),Yr=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(Ys,t);await ie(),await Qs(e,o,r);});async function Qs(e,t,r){let o=y=>{t.verbose&&console.info(`${je} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=Oe(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 p=n?y(n):void 0;if(n&&p){let{url:y}=p.parse(n,{fullyQualified:true});if(!l.find(M=>M===y)){if(!t.allow){let M=await confirm({message:`Allow ${Ge} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(M)||!M)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Ge} 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 g=(await st(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(M));}),h=(await Ht(g,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(M));});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(([M,j])=>j.list).map(([M,j])=>{let W;return l.length>1?W=`${N.cyan(c(j.sourceRepo.url,j.category))}/${j.name}`:W=`${N.cyan(j.category)}/${j.name}`,{label:W,value:M}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let w=(await yt([n],h,g)).match(y=>y,y=>program.error(y)),d="temp-jsrepo-exec",u=`./${d}/${encodeURIComponent(n)}`,b=X.join(process.cwd(),u);c$1.paths["*"]=u,le.mkdirSync(b,{recursive:true});let m=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],v=new Set,f=new Set,C=We(c$1.paths,t.cwd);C.isErr()&&program.error(N.red(C.unwrapErr()));let x$1=C.unwrap(),R=[];for(let y of w){let M=`${y.sourceRepo.url}/${y.category}/${y.name}`,j=`${y.category}/${y.name}`,W=y.sourceRepo,ee=X.join(t.cwd,x$1["*"],y.category);R.push(j),S.push({run:async({message:V})=>{V(`Adding ${N.cyan(M)}`),le.mkdirSync(ee,{recursive:true});let et=[],Re=async te=>{let Se=await it(W,te);return Se.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(te)}`)),program.error(N.red(`There was an error trying to get ${M}`))),Se.unwrap()};for(let te of y.files){if(!c$1.includeTests&&nt(te))continue;let Se=X.join(y.directory,te),Lt;y.subdirectory?Lt=X.join(ee,y.name,te):Lt=X.join(ee,te);let Yn=await Re(Se),Qn=Lt.slice(0,Lt.length-te.length);le.mkdirSync(Qn,{recursive:true}),et.push({content:Yn,destPath:Lt});}for(let te of et)le.writeFileSync(te.destPath,te.content);if(c$1.includeTests&&y.tests){let{devDependencies:te}=JSON.parse(le.readFileSync(X.join(t.cwd,"package.json")).toString());(te===void 0||te.vitest===void 0)&&v.add("vitest");}for(let te of y.devDependencies)v.add(te);for(let te of y.dependencies)f.add(te);}});}if(await Ao({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(R.join(", "))}`,loading:i,tasks:S}),f.size>0||v.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},M=X.join(b,"package.json");le.writeFileSync(M,JSON.stringify(y,null," "));}await He(f,v,{yes:true,no:false,cwd:b,pm:m,ignoreWorkspace:true});let re=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];re!==-1&&(oe=r.parent.rawArgs.slice(re+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let q=w[0],k;q.subdirectory?k=X.join(b,`${q.category}/${q.name}/index.js`):k=X.join(b,`${q.category}/${q.name}.js`);let A=resolveCommand(m,"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 M of y)process.stdout.write(`${M}
78
- `);}finally{le.rmSync(X.join(process.cwd(),d),{recursive:true,force:true});}}var na=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(_r),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),Zr=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"])).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(na,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 ia(e,r):await aa(r),outro(N.green("All done!"));}),ia=async(e,t)=>{let r=Oe(t.cwd),o=spinner(),n,i={},s=Pt(t.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(v){if(v.trim()==="")return "Please provide a value";if(!v.startsWith("./")){let f="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return f;let C=createPathsMatcher(s);if(C&&C(v).length===0)return f}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},!t.formatter){let v=r.isErr()?"none":r.unwrap().formatter??"none";le.existsSync(X.join(t.cwd,".prettierrc"))&&(v="prettier"),le.existsSync(X.join(t.cwd,"biome.json"))&&(v="biome");let f=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(C=>({value:C.toLowerCase(),label:C})),initialValue:v});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f!=="none"&&(t.formatter=f);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,p=new Set,g=async v=>{let f=await sa({url:v,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let C of f.dependencies)l.add(C);for(let C of f.devDependencies)p.add(C);n=f.paths,i=f.configFiles;};if(c.length>0)for(let v of c){if(!e.find(f=>f===v)&&r.isOk()&&r.unwrap().repos.find(f=>f===v)){let f=await confirm({message:`Initialize ${v}?`,initialValue:t.yes});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)continue}log.info(`Initializing ${N.cyan(v)}`),await g(v);}for(;;){let v=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),!v)break;let f=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:C=>{if(C.trim().length===0)return "Please provide a value";if(!y(C))return `Invalid provider! Valid providers (${x$1.map(x=>x.name).join(", ")})`}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),await g(f),c.push(f);}let h={$schema:`https://unpkg.com/jsrepo@${ze.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 \`${gt}\``);let{prettierOptions:w,biomeOptions:d}=await wt({formatter:h.formatter,cwd:t.cwd}),u=X.join(t.cwd,gt),b=await cr.format(JSON.stringify(h,null," "),{biomeOptions:d,prettierOptions:w,filePath:u,formatter:h.formatter});le.existsSync(t.cwd)||le.mkdirSync(t.cwd,{recursive:true}),le.writeFileSync(u,b),o.stop(`Wrote config to \`${gt}\`.`);let m=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await He(l,p,{yes:t.yes,cwd:t.cwd,pm:m});if(S.dependencies.size>0||S.devDependencies.size>0){let v=[];if(!S.installed){if(l.size>0){let C=resolveCommand$1(m,"add",[...l]);v.push(`Install dependencies \`${N.cyan(`${C?.command} ${C?.args.join(" ")}`)}\``);}if(p.size>0){let C=resolveCommand$1(m,"add",[...p,"-D"]);v.push(`Install dev dependencies \`${N.cyan(`${C?.command} ${C?.args.join(" ")}`)}\``);}}v=v.map((C,x)=>`${x+1}. ${C}`),S.installed||v.push(""),v.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let f=dt(v);process.stdout.write(f);}};async function sa({url:e,paths:t$1,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new ge,a=y(e);a||program.error(N.red(`Invalid provider! Valid providers (${x$1.map(d=>d.name).join(", ")})`));let c$1=a.name;if(a.name===t.name){let d=t.parse(e,{fullyQualified:false});c$1=`http-${new URL(d.url).origin}`;}if(!s.get(c$1)&&!n.yes){let d=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d){let u=await password({message:"Paste your token",validate(b){if(b.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 p=(await Kt(e,{noCache:!n.cache})).match(d=>d,d=>program.error(N.red(d))),g=(await vr(p)).match(d=>d,d=>program.error(N.red(d)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Dt(p,g,n.cwd);let h=[],w=[];if(g.configFiles){let{prettierOptions:d,biomeOptions:u}=await wt({formatter:o,cwd:n.cwd});for(let b of g.configFiles){if(b.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${b.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...b.dependencies??[]),w.push(...b.devDependencies??[]),!r[b.name]){let x=await text({message:`Where is your ${b.name} file?`,defaultValue:b.expectedPath,initialValue:b.expectedPath,placeholder:b.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[b.name]=x;}let m=X.join(n.cwd,r[b.name]),S;if(le.existsSync(m))S=le.readFileSync(m).toString();else {let x=X.dirname(m);if(le.existsSync(x)){let R=Wo(m);if(R){S=le.readFileSync(R).toString();let I=X.relative(n.cwd,R);log.warn(`Located ${N.bold(r[b.name])} at ${N.bold(I)}`),r[b.name]=I,m=X.join(n.cwd,I);}}}i.start(`Fetching the ${N.cyan(b.name)} from ${N.cyan(e)}`);let v=(await it(p,b.path)).match(x=>x,x=>program.error(N.red(x))),f=await ir({file:{content:v,destPath:m},biomeOptions:u,prettierOptions:d,formatter:o});i.stop(`Fetched the ${N.cyan(b.name)} from ${N.cyan(e)}`);let C=n.yes||S===void 0;if(S){if(!n.yes){let x=c(p.url,b.name),R=await jt({config:{biomeOptions:u,prettierOptions:d,formatter:o},current:{content:S,path:m},incoming:{content:f,path:x},options:{...n,loading:i,no:false}});R.applyChanges&&(C=true,S=R.updatedContent);}}else {let x=X.dirname(m);le.existsSync(x)||le.mkdirSync(x,{recursive:true}),S=f;}C&&S&&(i.start(`Writing ${N.cyan(b.name)} to ${N.cyan(m)}`),le.writeFileSync(m,S),i.stop(`Wrote ${N.cyan(b.name)} to ${N.cyan(m)}`));}}if(!n.yes){let d=await multiselect({message:"Which category paths would you like to configure?",options:g.categories.map(u=>({label:u.name,value:u.name})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let u of d){let b=t$1[u],m=await text({message:`Where should ${u} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:b||`./src/${u}`,defaultValue:b,initialValue:b});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),t$1[u]=m;}}return {paths:t$1,configFiles:r,dependencies:h,devDependencies:w}}var aa=async e=>{let t=spinner(),r=X.join(e.cwd,"package.json");le.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=It(e.cwd).match(d=>d,d=>program.error(N.red(d)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${ze.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 d=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(d)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(d);}let n=JSON.parse(le.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let d=await confirm({message:`Configure to publish to ${Be}?`,initialValue:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),i=d;}if(i){if(!o.name){let d=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.name=d;}o.version||(o.version="0.0.1"),e.publishScript=await _n(e.publishScript,n,e,"release:registry");}else e.buildScript=await _n(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 p=[];p.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{le.writeFileSync(r,JSON.stringify(n,null," "));}catch(d){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${d}`));}}}),p.push({loadingMessage:`Writing config to \`${N.cyan(ht)}\``,completedMessage:`Wrote config to \`${N.cyan(ht)}\``,run:async()=>{let d=X.join(e.cwd,ht);try{le.writeFileSync(X.join(d),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(d)}\`. Error: ${u}`));}}}),await No(p,{loading:t});let g=s;s||(g=(await He(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!g){let d=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Ge} as a dev dependency \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let d=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to publish the registry.`);}else {let d=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((d,u)=>`${u+1}. ${d}`);let w=dt(h);process.stdout.write(w);};async function _n(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 fa=$.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()}),eo=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(fa,e);await ie(),await ma(t),outro(N.green("All done!"));});async function ma(e){let t=v=>{e.verbose&&console.info(`${je} ${v}`);},r=he({verbose:e.verbose?t:void 0}),o$1=It(e.cwd).match(v=>{if(v===null)return {$schema:"",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 f=v;return e.name&&(f.name=e.name),e.ver&&(f.version=e.ver),e.dirs&&(f.dirs=e.dirs),e.doNotListBlocks&&(f.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(f.doNotListCategories=e.doNotListCategories),e.listBlocks&&(f.listBlocks=e.listBlocks),e.listCategories&&(f.listCategories=e.listCategories),e.includeBlocks&&(f.includeBlocks=e.includeBlocks),e.includeCategories&&(f.includeCategories=e.includeCategories),e.excludeBlocks&&(f.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(f.excludeCategories=e.excludeCategories),e.excludeDeps&&(f.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(f.allowSubdirectories=e.allowSubdirectories),f.rules={...Ut,...f.rules},f},v=>program.error(N.red(v)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o$1.name!==void 0)try{let[v,f,...C]=o$1.name.split("/");if(C.length>0)throw new Error;if(!v.startsWith("@"))throw new Error;if(!v.slice(1).match(u))throw new Error;if(!f.match(u))throw new Error}catch{program.error(N.red(`\`${o$1.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$1.version!==void 0){if(o$1.version==="package"){let f=X.join(e.cwd,"package.json");le.existsSync(f)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:C}=JSON.parse(le.readFileSync(f).toString());o$1.version=C;}Po.valid(o$1.version)||program.error(`\`${o$1.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 ge().get("jsrepo");n===void 0&&program.error(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${Be}.`));let i=[],s=Ws();try{let v=le.readFileSync(X.join(e.cwd,".gitignore")).toString();s.add(v);}catch{}s.add(yr);for(let v of o$1.dirs){let f=X.join(e.cwd,v);r.start(`Building ${N.cyan(f)}`);let C=fr(f,{cwd:e.cwd,ignore:s,config:o$1});for(let x of C){if(i.find(R=>R.name===x.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${v}/${x.name}`)}\` because a category with the same name already exists!`);continue}i.push(x);}r.stop(`Built ${N.cyan(f)}`);}let a=mr(o$1,{cwd:e.cwd}),c=o(i,a,o$1);r.start("Checking manifest");let{warnings:l,errors:p}=pr(c,o$1,e.cwd,o$1.rules);r.stop("Completed checking manifest."),(l.length>0||p.length>0)&&console.log(T);for(let v of l)console.log(v);if(p.length>0){for(let v of p)console.log(v);program.error(N.red(`Completed checking manifest with ${N.bold(`${p.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[g,h]=ur(c.categories);c.categories=g,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let w=X.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${w}`),le.mkdirSync(w,{recursive:true}),t("Writing manifest to temp dir"),le.writeFileSync(X.resolve(w,"jsrepo-manifest.json"),JSON.stringify(c));let d=X.resolve(e.cwd,o$1.readme);try{t("Attempting to copy readme"),le.copyFileSync(d,X.join(w,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let v of c.configFiles){let f=X.join(e.cwd,v.path),C=X.join(w,v.path),x=X.join(C,"../");le.existsSync(x)||le.mkdirSync(x,{recursive:true}),le.copyFileSync(f,C);}t("Copied config files");}t("Copying registry files");for(let v of c.categories)for(let f of v.blocks){let C=X.join(e.cwd,f.directory),x=X.join(w,f.directory);for(let R of f.files){let I=X.join(x,R,"../");le.existsSync(I)||le.mkdirSync(I,{recursive:true}),le.copyFileSync(X.join(C,R),X.join(x,R));}}t("Copied registry files");let u$1=X.resolve(e.cwd,`${o$1.name.replace("/","_")}-package.tar.gz`),b=le.readdirSync(w);t("Creating archive file"),await Vn.create({z:true,cwd:w,file:u$1},b),t("Created archive file"),t("Removing temp directory"),le.rmSync(w,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u$1)}...`),r.start(`Publishing ${N.bold(c.name)} to ${Be}...`);let m=le.readFileSync(u$1);t("Removing archive file"),le.rmSync(u$1,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${v}/api/publish`}`);let S=await Ne(`${v}/api/publish`,{body:m,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-private":e.private?"1":"0"},method:"POST"});if(r.stop(`Got response from ${Be}.`),S.ok){let v=await S.json();v.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(`@${v.scope}`)}/${v.registry}${N.greenBright(`@${v.version}`)}!`);}else {let v=await S.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(S.status)} ${v.message}`));}}var Ra=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),to=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(Ra,t);await ie(),await Sa(e,r),outro(N.green("All done!"));});async function Sa(e,t){let r=m=>{t.verbose&&console.info(`${je} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Oe(t.cwd).match(m=>m,m=>program.error(N.red(m))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await st(i,{noCache:!t.cache})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed to get info for ${N.cyan(m)}`),program.error(N.red(S));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Ht(s,{verbose:t.verbose?r:void 0})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed fetching blocks from ${N.cyan(m)}`),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=X.resolve(X.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${N.bold(c$1)}.`),le.mkdirSync(c$1,{recursive:true});let l=()=>{le.rmSync(c$1,{recursive:true,force:true});},p=vt(a,o,t.cwd).map(m=>m.specifier),g=e;e.length===0&&(g=p),g.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let m of g){let S,v=y(m);if(v){let{url:f}=v.parse(m,{fullyQualified:true}),C=(await Kt(f)).match(R=>R,R=>program.error(N.red(R))),x=(await Ht([C])).match(R=>R,R=>program.error(N.red(R)));for(let[R,I]of x)a.set(R,I);S=a.get(m);}else for(let f of i){let C=y(f);if(!C)continue;let{url:x,specifier:R}=C.parse(c(f,m),{fullyQualified:true}),I=a.get(c(x,R));if(I!==void 0){S=I;break}}S||program.error(N.red(`Invalid block! ${N.bold(m)} does not exist!`)),h.push({name:m,block:S});}let w=We(o.paths,t.cwd).match(m=>m,m=>program.error(N.red(m)));for(let{block:m}of h){let S=m.sourceRepo,v=c(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(v)}`),!m.tests){n.stop(`No tests found for ${N.cyan(v)}`);continue}let f=zt(m,w,t.cwd);f=X.relative(c$1,f);let C=async R=>{let I=await it(S,R);return I.isErr()&&(n.stop(N.red(`Error fetching ${N.bold(R)}`)),program.error(N.red(`There was an error trying to get ${v}`))),I.unwrap()};r(`Downloading and copying test files for ${v}`);let x=[];for(let R of m.files.filter(I=>nt(I))){let I=await C(X.join(m.directory,R)),re=X.join(c$1,R);le.writeFileSync(re,I),x.push(re);}for(let R of x){r(`Opening test file ${R}`);let I=le.readFileSync(R).toString(),re=Hi.parseSync(R,I);for(let oe of re.module.staticImports){let q=oe.moduleRequest.value,k;if(q.startsWith(".")&&(m.subdirectory?k=X.join(f,m.name,q):k=X.join(f,q)),k){let A=new RegExp(`(['"])${Mi(q)}\\1`,"g");I=I.replaceAll(A,`$1${k}$1`);}}le.writeFileSync(R,I);}r(`Completed ${N.cyan.bold(v)} test file`),t.verbose||n.stop(`Completed setup for ${N.bold(v)}`);}r("Beginning testing");let d=await detect({cwd:t.cwd});d==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(d.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${d.agent}'.`));let b=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(b)} on ${N.cyan(t.cwd)}`);try{let m=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let S of m)process.stdout.write(`${S}
77
+ `);for(let W of P){let te=W.content.match(Se=>Se,Se=>program.error(N.red(Se))),V=Yt(W.name,k.block,v,t.cwd),et=(await Jt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Se=>Se,Se=>program.error(N.red(Se))),Re="";le.existsSync(V)&&(Re=le.readFileSync(V).toString());let re=await jt({config:{biomeOptions:f,prettierOptions:R,formatter:s.formatter},current:{path:V,content:Re},incoming:{path:c(A,W.name),content:et},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});re.applyChanges&&(Q.push(Pn({destination:V,content:re.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(P=>{P.map(async W=>{let te=W.content.match(Re=>Re,Re=>program.error(N.red(Re))),V=Yt(W.name,k.block,v,t.cwd),et=Jt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Re=>(Re.isErr()&&program.error(N.red(Re.unwrapErr())),{destination:V,content:Re.unwrap(),block:k.block}));Q.push(et);});}),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(Q.map(async k=>{let A=await k,y=Z.dirname(A.destination);le.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),le.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),le.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",q=await He(m,b,{yes:t.yes,cwd:t.cwd,pm:oe});if(q.dependencies.size>0||q.devDependencies.size>0){let k=[];if(!q.installed){if(m.size>0){let y=resolveCommand(oe,"add",[...m]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(b.size>0){let y=resolveCommand(oe,"add",[...b,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,M)=>`${M+1}. ${y}`),q.installed||k.push(""),k.push("Import and use the blocks!");let A=dt(k);process.stdout.write(A);}}function An(e){return new Promise(t=>setTimeout(t,e))}var Bs=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),zr=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(Bs,e);await ie(),await _s(t),outro(N.green("All done!"));});async function _s(e){let t=new ge;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Be}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Be}!`);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=Ls.machineIdSync(true),o;try{let a=await Ne(`${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 An(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Ne(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 ${Be}!`);break}catch{}}}var Js=$.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()}),Kr=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(Js,e);await ie(),await Us(t),outro(N.green("All done!"));});async function Us(e){let t=d=>{e.verbose&&console.info(`${je} ${d}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n=It(e.cwd).match(d=>{if(d===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let u=d;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={...Ut,...u.rules},u},d=>program.error(N.red(d))),i;n.outputDir?i=Z.join(e.cwd,n.outputDir):i=e.cwd;let s=Z.join(i,m);if(e.output&&le.existsSync(s)){if(n.outputDir){let d=o(le.readFileSync(s).toString());if(d.isOk())for(let u of d.unwrap().categories)for(let b of u.blocks){let m=Z.join(i,b.directory);le.existsSync(m)&&le.rmSync(m,{recursive:true});}}le.rmSync(s);}let a=Vs();try{let d=le.readFileSync(Z.join(e.cwd,".gitignore")).toString();a.add(d);}catch{}a.add(vr);for(let d of n.dirs){let u=Z.join(e.cwd,d);r.start(`Building ${N.cyan(u)}`);let b=mr(u,{cwd:e.cwd,ignore:a,config:n});for(let m of b){if(o$1.find(S=>S.name===m.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${d}/${m.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(m);}r.stop(`Built ${N.cyan(u)}`);}let c=ur(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:p$1,errors:g}=fr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(p$1.length>0||g.length>0)&&console.log(T);for(let d of p$1)console.log(d);if(g.length>0){for(let d of g)console.log(d);program.error(N.red(`Completed checking manifest with ${N.bold(`${g.length} error(s)`)} and ${N.bold(`${p$1.length} warning(s)`)}`));}let[h,w]=gr(l.categories);if(l.categories=h,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n.preview){let d=l.categories.flatMap(u=>u.blocks.filter(b=>b.list).map(b=>`${N.cyan(b.category)}/${b.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of d)console.log(`${T} \u25FB ${u}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l.configFiles)for(let d of l.configFiles){let u=Z.join(e.cwd,d.path),b=Z.join(i,d.path),m=Z.join(b,"../");le.existsSync(m)||le.mkdirSync(m,{recursive:true}),le.copyFileSync(u,b);}for(let d of l.categories)for(let u of d.blocks){let b=Z.join(e.cwd,u.directory),m=Z.join(i,u.directory);for(let S of u.files){let R=Z.join(m,S,"../");le.existsSync(R)||le.mkdirSync(R,{recursive:true}),le.copyFileSync(Z.join(b,S),Z.join(m,S));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),le.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var Qs=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),Yr=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(Qs,t);await ie(),await Xs(e,o,r);});async function Xs(e,t,r){let o=y=>{t.verbose&&console.info(`${je} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=Oe(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 p=n?z(n):void 0;if(n&&p){let{url:y}=p.parse(n,{fullyQualified:true});if(!l.find(M=>M===y)){if(!t.allow){let M=await confirm({message:`Allow ${Ge} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(M)||!M)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Ge} 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 g=(await st(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(M));}),h=(await Ht(g,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(M));});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(([M,P])=>P.list).map(([M,P])=>{let W;return l.length>1?W=`${N.cyan(c(P.sourceRepo.url,P.category))}/${P.name}`:W=`${N.cyan(P.category)}/${P.name}`,{label:W,value:M}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let w=(await yt([n],h,g)).match(y=>y,y=>program.error(y)),d="temp-jsrepo-exec",u=`./${d}/${encodeURIComponent(n)}`,b=Z.join(process.cwd(),u);c$1.paths["*"]=u,le.mkdirSync(b,{recursive:true});let m=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],R=new Set,f=new Set,v=We(c$1.paths,t.cwd);v.isErr()&&program.error(N.red(v.unwrapErr()));let x$1=v.unwrap(),C=[];for(let y of w){let M=`${y.sourceRepo.url}/${y.category}/${y.name}`,P=`${y.category}/${y.name}`,W=y.sourceRepo,te=Z.join(t.cwd,x$1["*"],y.category);C.push(P),S.push({run:async({message:V})=>{V(`Adding ${N.cyan(M)}`),le.mkdirSync(te,{recursive:true});let et=[],Re=async re=>{let Se=await it(W,re);return Se.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(re)}`)),program.error(N.red(`There was an error trying to get ${M}`))),Se.unwrap()};for(let re of y.files){if(!c$1.includeTests&&nt(re))continue;let Se=Z.join(y.directory,re),Lt;y.subdirectory?Lt=Z.join(te,y.name,re):Lt=Z.join(te,re);let Qn=await Re(Se),Xn=Lt.slice(0,Lt.length-re.length);le.mkdirSync(Xn,{recursive:true}),et.push({content:Qn,destPath:Lt});}for(let re of et)le.writeFileSync(re.destPath,re.content);if(c$1.includeTests&&y.tests){let{devDependencies:re}=JSON.parse(le.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)f.add(re);}});}if(await Fo({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(C.join(", "))}`,loading:i,tasks:S}),f.size>0||R.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},M=Z.join(b,"package.json");le.writeFileSync(M,JSON.stringify(y,null," "));}await He(f,R,{yes:true,no:false,cwd:b,pm:m,ignoreWorkspace:true});let Q=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];Q!==-1&&(oe=r.parent.rawArgs.slice(Q+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let q=w[0],k;q.subdirectory?k=Z.join(b,`${q.category}/${q.name}/index.js`):k=Z.join(b,`${q.category}/${q.name}.js`);let A=resolveCommand(m,"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 M of y)process.stdout.write(`${M}
78
+ `);}finally{le.rmSync(Z.join(process.cwd(),d),{recursive:true,force:true});}}var ia=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(_r),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),Zr=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"])).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(ia,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 sa(e,r):await ca(r),outro(N.green("All done!"));}),sa=async(e,t)=>{let r=Oe(t.cwd),o=spinner(),n,i={},s=Pt(t.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(R){if(R.trim()==="")return "Please provide a value";if(!R.startsWith("./")){let f="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return f;let v=createPathsMatcher(s);if(v&&v(R).length===0)return f}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},!t.formatter){let R=r.isErr()?"none":r.unwrap().formatter??"none";le.existsSync(Z.join(t.cwd,".prettierrc"))&&(R="prettier"),le.existsSync(Z.join(t.cwd,"biome.json"))&&(R="biome");let f=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(v=>({value:v.toLowerCase(),label:v})),initialValue:R});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f!=="none"&&(t.formatter=f);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,p=new Set,g=async R=>{let f=await aa({url:R,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let v of f.dependencies)l.add(v);for(let v of f.devDependencies)p.add(v);n=f.paths,i=f.configFiles;};if(c.length>0)for(let R of c){if(!e.find(f=>f===R)&&r.isOk()&&r.unwrap().repos.find(f=>f===R)){let f=await confirm({message:`Initialize ${R}?`,initialValue:t.yes});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)continue}log.info(`Initializing ${N.cyan(R)}`),await g(R);}for(;;){let R=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break;let f=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:v=>{if(v.trim().length===0)return "Please provide a value";if(!z(v))return `Invalid provider! Valid providers (${y.map(x=>x.name).join(", ")})`}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),await g(f),c.push(f);}let h={$schema:`https://unpkg.com/jsrepo@${ze.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 \`${gt}\``);let{prettierOptions:w,biomeOptions:d}=await wt({formatter:h.formatter,cwd:t.cwd}),u=Z.join(t.cwd,gt),b=await lr.format(JSON.stringify(h,null," "),{biomeOptions:d,prettierOptions:w,filePath:u,formatter:h.formatter});le.existsSync(t.cwd)||le.mkdirSync(t.cwd,{recursive:true}),le.writeFileSync(u,b),o.stop(`Wrote config to \`${gt}\`.`);let m=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await He(l,p,{yes:t.yes,cwd:t.cwd,pm:m});if(S.dependencies.size>0||S.devDependencies.size>0){let R=[];if(!S.installed){if(l.size>0){let v=resolveCommand$1(m,"add",[...l]);R.push(`Install dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(p.size>0){let v=resolveCommand$1(m,"add",[...p,"-D"]);R.push(`Install dev dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}R=R.map((v,x)=>`${x+1}. ${v}`),S.installed||R.push(""),R.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let f=dt(R);process.stdout.write(f);}};async function aa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new ge,a=z(e);a||program.error(N.red(`Invalid provider! Valid providers (${y.map(d=>d.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let d=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(d.url).origin}`;}if(!s.get(c$1)&&!n.yes){let d=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d){let u=await password({message:"Paste your token",validate(b){if(b.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 p=(await Kt(e,{noCache:!n.cache})).match(d=>d,d=>program.error(N.red(d))),g=(await wr(p)).match(d=>d,d=>program.error(N.red(d)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Dt(p,g,n.cwd);let h=[],w=[];if(g.configFiles){let{prettierOptions:d,biomeOptions:u}=await wt({formatter:o,cwd:n.cwd});for(let b of g.configFiles){if(b.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${b.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...b.dependencies??[]),w.push(...b.devDependencies??[]),!r[b.name]){let x=await text({message:`Where is your ${b.name} file?`,defaultValue:b.expectedPath,initialValue:b.expectedPath,placeholder:b.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[b.name]=x;}let m=Z.join(n.cwd,r[b.name]),S;if(le.existsSync(m))S=le.readFileSync(m).toString();else {let x=Z.dirname(m);if(le.existsSync(x)){let C=Vo(m);if(C){S=le.readFileSync(C).toString();let j=Z.relative(n.cwd,C);log.warn(`Located ${N.bold(r[b.name])} at ${N.bold(j)}`),r[b.name]=j,m=Z.join(n.cwd,j);}}}i.start(`Fetching the ${N.cyan(b.name)} from ${N.cyan(e)}`);let R=(await it(p,b.path)).match(x=>x,x=>program.error(N.red(x))),f=await sr({file:{content:R,destPath:m},biomeOptions:u,prettierOptions:d,formatter:o});i.stop(`Fetched the ${N.cyan(b.name)} from ${N.cyan(e)}`);let v=n.yes||S===void 0;if(S){if(!n.yes){let x=c(p.url,b.name),C=await jt({config:{biomeOptions:u,prettierOptions:d,formatter:o},current:{content:S,path:m},incoming:{content:f,path:x},options:{...n,loading:i,no:false}});C.applyChanges&&(v=true,S=C.updatedContent);}}else {let x=Z.dirname(m);le.existsSync(x)||le.mkdirSync(x,{recursive:true}),S=f;}v&&S&&(i.start(`Writing ${N.cyan(b.name)} to ${N.cyan(m)}`),le.writeFileSync(m,S),i.stop(`Wrote ${N.cyan(b.name)} to ${N.cyan(m)}`));}}if(!n.yes){let d=await multiselect({message:"Which category paths would you like to configure?",options:g.categories.map(u=>({label:u.name,value:u.name})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let u of d){let b=t[u],m=await text({message:`Where should ${u} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:b||`./src/${u}`,defaultValue:b,initialValue:b});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),t[u]=m;}}return {paths:t,configFiles:r,dependencies:h,devDependencies:w}}var ca=async e=>{let t=spinner(),r=Z.join(e.cwd,"package.json");le.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=It(e.cwd).match(d=>d,d=>program.error(N.red(d)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${ze.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 d=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(d)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(d);}let n=JSON.parse(le.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let d=await confirm({message:`Configure to publish to ${Be}?`,initialValue:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),i=d;}if(i){if(!o.name){let d=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.name=d;}o.version||(o.version="0.0.1"),e.publishScript=await Mn(e.publishScript,n,e,"release:registry");}else e.buildScript=await Mn(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 p=[];p.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{le.writeFileSync(r,JSON.stringify(n,null," "));}catch(d){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${d}`));}}}),p.push({loadingMessage:`Writing config to \`${N.cyan(ht)}\``,completedMessage:`Wrote config to \`${N.cyan(ht)}\``,run:async()=>{let d=Z.join(e.cwd,ht);try{le.writeFileSync(Z.join(d),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(d)}\`. Error: ${u}`));}}}),await Ao(p,{loading:t});let g=s;s||(g=(await He(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!g){let d=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Ge} as a dev dependency \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let d=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to publish the registry.`);}else {let d=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((d,u)=>`${u+1}. ${d}`);let w=dt(h);process.stdout.write(w);};async function Mn(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 ma=$.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()}),eo=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(ma,e);await ie(),await ua(t),outro(N.green("All done!"));});async function ua(e){let t=f=>{e.verbose&&console.info(`${je} ${f}`);},r=he({verbose:e.verbose?t:void 0}),o=It(e.cwd).match(f=>{if(f===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 v=f;return e.private&&(v.access="private"),e.name&&(v.name=e.name),e.ver&&(v.version=e.ver),e.dirs&&(v.dirs=e.dirs),e.doNotListBlocks&&(v.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(v.doNotListCategories=e.doNotListCategories),e.listBlocks&&(v.listBlocks=e.listBlocks),e.listCategories&&(v.listCategories=e.listCategories),e.includeBlocks&&(v.includeBlocks=e.includeBlocks),e.includeCategories&&(v.includeCategories=e.includeCategories),e.excludeBlocks&&(v.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(v.excludeCategories=e.excludeCategories),e.excludeDeps&&(v.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(v.allowSubdirectories=e.allowSubdirectories),v.rules={...Ut,...v.rules},v},f=>program.error(N.red(f)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[f,v$1,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!f.startsWith("@"))throw new Error;if(!f.slice(1).match(v))throw new Error;if(!v$1.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 v=Z.join(e.cwd,"package.json");le.existsSync(v)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:x}=JSON.parse(le.readFileSync(v).toString());o.version=x;}Io.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 ge().get("jsrepo");n===void 0&&program.error(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${Be}.`));let i=[],s=Vs();try{let f=le.readFileSync(Z.join(e.cwd,".gitignore")).toString();s.add(f);}catch{}s.add(vr);for(let f of o.dirs){let v=Z.join(e.cwd,f);r.start(`Building ${N.cyan(v)}`);let x=mr(v,{cwd:e.cwd,ignore:s,config:o});for(let C of x){if(i.find(j=>j.name===C.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${f}/${C.name}`)}\` because a category with the same name already exists!`);continue}i.push(C);}r.stop(`Built ${N.cyan(v)}`);}let a=ur(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:p$1}=fr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||p$1.length>0)&&console.log(T);for(let f of l)console.log(f);if(p$1.length>0){for(let f of p$1)console.log(f);program.error(N.red(`Completed checking manifest with ${N.bold(`${p$1.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[g,h]=gr(c.categories);c.categories=g,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let w$1=Z.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${w$1}`),le.mkdirSync(w$1,{recursive:true}),t("Writing manifest to temp dir"),le.writeFileSync(Z.resolve(w$1,"jsrepo-manifest.json"),JSON.stringify(c));let d=Z.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),le.copyFileSync(d,Z.join(w$1,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let f of c.configFiles){let v=Z.join(e.cwd,f.path),x=Z.join(w$1,f.path),C=Z.join(x,"../");le.existsSync(C)||le.mkdirSync(C,{recursive:true}),le.copyFileSync(v,x);}t("Copied config files");}t("Copying registry files");for(let f of c.categories)for(let v of f.blocks){let x=Z.join(e.cwd,v.directory),C=Z.join(w$1,v.directory);for(let j of v.files){let Q=Z.join(C,j,"../");le.existsSync(Q)||le.mkdirSync(Q,{recursive:true}),le.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`),b=le.readdirSync(w$1);t("Creating archive file"),await Jn.create({z:true,cwd:w$1,file:u},b),t("Created archive file"),t("Removing temp directory"),le.rmSync(w$1,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u)}...`);let m=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${N.cyan(m)}`),r.start(`Publishing ${N.bold(c.name)} to ${Be}...`);let S=le.readFileSync(u);t("Removing archive file"),le.rmSync(u,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let R=await Ne(`${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":m},method:"POST"});if(r.stop(`Got response from ${Be}.`),R.ok){let f=await R.json();f.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(`@${f.scope}`)}/${f.registry}${N.greenBright(`@${f.version}`)}!`);}else {let f=await R.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(R.status)} ${f.message}`));}}var Sa=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),to=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(Sa,t);await ie(),await ja(e,r),outro(N.green("All done!"));});async function ja(e,t){let r=m=>{t.verbose&&console.info(`${je} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Oe(t.cwd).match(m=>m,m=>program.error(N.red(m))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await st(i,{noCache:!t.cache})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed to get info for ${N.cyan(m)}`),program.error(N.red(S));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Ht(s,{verbose:t.verbose?r:void 0})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed fetching blocks from ${N.cyan(m)}`),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)}.`),le.mkdirSync(c$1,{recursive:true});let l=()=>{le.rmSync(c$1,{recursive:true,force:true});},p=vt(a,o,t.cwd).map(m=>m.specifier),g=e;e.length===0&&(g=p),g.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let m of g){let S,R=z(m);if(R){let{url:f}=R.parse(m,{fullyQualified:true}),v=(await Kt(f)).match(C=>C,C=>program.error(N.red(C))),x=(await Ht([v])).match(C=>C,C=>program.error(N.red(C)));for(let[C,j]of x)a.set(C,j);S=a.get(m);}else for(let f of i){let v=z(f);if(!v)continue;let{url:x,specifier:C}=v.parse(c(f,m),{fullyQualified:true}),j=a.get(c(x,C));if(j!==void 0){S=j;break}}S||program.error(N.red(`Invalid block! ${N.bold(m)} does not exist!`)),h.push({name:m,block:S});}let w=We(o.paths,t.cwd).match(m=>m,m=>program.error(N.red(m)));for(let{block:m}of h){let S=m.sourceRepo,R=c(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(R)}`),!m.tests){n.stop(`No tests found for ${N.cyan(R)}`);continue}let f=zt(m,w,t.cwd);f=Z.relative(c$1,f);let v=async C=>{let j=await it(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 m.files.filter(j=>nt(j))){let j=await v(Z.join(m.directory,C)),Q=Z.join(c$1,C);le.writeFileSync(Q,j),x.push(Q);}for(let C of x){r(`Opening test file ${C}`);let j=le.readFileSync(C).toString(),Q=qi.parseSync(C,j);for(let oe of Q.module.staticImports){let q=oe.moduleRequest.value,k;if(q.startsWith(".")&&(m.subdirectory?k=Z.join(f,m.name,q):k=Z.join(f,q)),k){let A=new RegExp(`(['"])${Wi(q)}\\1`,"g");j=j.replaceAll(A,`$1${k}$1`);}}le.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 d=await detect({cwd:t.cwd});d==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(d.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${d.agent}'.`));let b=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(b)} on ${N.cyan(t.cwd)}`);try{let m=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let S of m)process.stdout.write(`${S}
79
79
  `);l();}catch(m){t.debug?console.info(`${N.bold("--debug")} flag provided. Skipping cleanup. Run '${N.bold(b)}' to retry tests.
80
- `):l(),program.error(N.red(`Tests failed! Error ${m}`));}}var Da=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Ft=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),ro=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Ft.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(Da,t);await ie(),await Ta(e,r),outro(N.green("All done!"));});async function Ta(e,t$1){let r=Oe(t$1.cwd).match(s=>s.repos.filter(t.matches),()=>[]),o=Ft.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new ge;if(t$1.logout){if(o!==void 0){if(o==="http"){await Un(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of Ft){if(s==="http"){await Un(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:Ft.map(a=>({label:a,value:a})),initialValue:Ft[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:Ft[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$1.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$1.token=s;}n.set(o,t$1.token),log.success(`Logged into ${N.bold(i)}.`);}async function Un(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 _a=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),no=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(_a,t);await ie(),await Ma(e,r),outro(N.green("All done!"));});async function Ma(e,t){let r=f=>{t.verbose&&console.info(`${je} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(t.cwd).match(f=>f,f=>program.error(N.red(f))),i=n.repos;t.repo&&(i=[t.repo]);for(let f of e)x$1.find(C=>f.startsWith(C.name))&&program.error(N.red(`Invalid value provided for block names \`${N.bold(f)}\`. Block names are expected to be provided in the format of \`${N.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(f)||!f)&&(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 st(i,{noCache:!t.cache})).match(f=>f,({repo:f,message:C})=>{o.stop(`Failed to get info for ${N.cyan(f)}`),program.error(N.red(C));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await br(s)).match(f=>f,({repo:f,message:C})=>{o.stop(`Failed fetching blocks from ${N.cyan(f)}`),program.error(N.red(C));}),c$1=wr(a);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`),r(`Retrieved blocks from ${N.cyan(i.join(", "))}`);for(let f of a)Dt(f.state,f.manifest,t.cwd);let l=vt(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 p=e;if(t.all&&(p=l.map(f=>f.specifier)),p.length===0){let f=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(C=>C.block.list).map(C=>({label:`${N.cyan(C.block.category)}/${C.block.name}`,value:C.specifier})),required:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),p=f;}r(`Preparing to update ${N.cyan(p.join(", "))}`);let g=(await yt(p,c$1,s)).match(f=>f,program.error),h=new Set,w=new Set,{prettierOptions:d,biomeOptions:u}=await wt({formatter:n.formatter,cwd:t.cwd}),b=We(n.paths,t.cwd).match(f=>f,f=>program.error(N.red(f))),m=$r(g,n);for(let f of m){let C=c(f.block.sourceRepo.url,f.block.category,f.block.name),x=Qt(f.block.sourceRepo.url);r(`Attempting to update ${C}`),n.includeTests&&f.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let I of f.block.devDependencies)h.add(I);for(let I of f.block.dependencies)w.add(I);let R=await f.files;process.stdout.write(`${T}
81
- `),process.stdout.write(`${T} ${C}
82
- `);for(let I of R){let re=I.content.match(y=>y,y=>program.error(N.red(y))),oe=Yt(I.name,f.block,b,t.cwd),q=(await Jt({file:{content:re,destPath:oe},biomeOptions:u,prettierOptions:d,config:n,imports:f.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(y=>y,y=>program.error(N.red(y))),k="";le.existsSync(oe)&&(k=le.readFileSync(oe).toString());let A=await jt({config:{biomeOptions:u,prettierOptions:d,formatter:n.formatter},current:{path:oe,content:k},incoming:{path:c(C,I.name),content:q},options:{...t,loading:o,verbose:t.verbose?r:void 0}});A.applyChanges&&(o.start(`Writing changes to ${N.cyan(oe)}`),le.writeFileSync(oe,A.updatedContent),o.stop(`Wrote changes to ${N.cyan(oe)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",v=await He(w,h,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(v.dependencies.size>0||v.devDependencies.size>0){let f=[];if(!v.installed){if(w.size>0){let x=resolveCommand(S,"add",[...w]);f.push(`Install dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(h.size>0){let x=resolveCommand(S,"add",[...h,"-D"]);f.push(`Install dev dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}f=f.map((x,R)=>`${R+1}. ${x}`),v.installed||f.push(""),f.push("Import and use the blocks!");let C=dt(f);process.stdout.write(C);}}var qn=program.name(Rt.name).description(Rt.description).version(Rt.version).addCommand(Ur).addCommand(zr).addCommand(Kr).addCommand(Yr).addCommand(Zr).addCommand(eo).addCommand(to).addCommand(ro).addCommand(no);qn.parse();//# sourceMappingURL=index.js.map
80
+ `):l(),program.error(N.red(`Tests failed! Error ${m}`));}}var Ta=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Ft=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),ro=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Ft.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(Ta,t);await ie(),await Na(e,r),outro(N.green("All done!"));});async function Na(e,t){let r=Oe(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=Ft.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new ge;if(t.logout){if(o!==void 0){if(o==="http"){await Gn(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of Ft){if(s==="http"){await Gn(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:Ft.map(a=>({label:a,value:a})),initialValue:Ft[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:Ft[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 Gn(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 Ma=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),no=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(Ma,t);await ie(),await Wa(e,r),outro(N.green("All done!"));});async function Wa(e,t){let r=f=>{t.verbose&&console.info(`${je} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(t.cwd).match(f=>f,f=>program.error(N.red(f))),i=n.repos;t.repo&&(i=[t.repo]);for(let f of e)y.find(v=>f.startsWith(v.name))&&program.error(N.red(`Invalid value provided for block names \`${N.bold(f)}\`. Block names are expected to be provided in the format of \`${N.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(f)||!f)&&(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 st(i,{noCache:!t.cache})).match(f=>f,({repo:f,message:v})=>{o.stop(`Failed to get info for ${N.cyan(f)}`),program.error(N.red(v));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await kr(s)).match(f=>f,({repo:f,message:v})=>{o.stop(`Failed fetching blocks from ${N.cyan(f)}`),program.error(N.red(v));}),c$1=br(a);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`),r(`Retrieved blocks from ${N.cyan(i.join(", "))}`);for(let f of a)Dt(f.state,f.manifest,t.cwd);let l=vt(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 p=e;if(t.all&&(p=l.map(f=>f.specifier)),p.length===0){let f=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(v=>v.block.list).map(v=>({label:`${N.cyan(v.block.category)}/${v.block.name}`,value:v.specifier})),required:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),p=f;}r(`Preparing to update ${N.cyan(p.join(", "))}`);let g=(await yt(p,c$1,s)).match(f=>f,program.error),h=new Set,w=new Set,{prettierOptions:d,biomeOptions:u}=await wt({formatter:n.formatter,cwd:t.cwd}),b=We(n.paths,t.cwd).match(f=>f,f=>program.error(N.red(f))),m=xr(g,n);for(let f of m){let v=c(f.block.sourceRepo.url,f.block.category,f.block.name),x=Qt(f.block.sourceRepo.url);r(`Attempting to update ${v}`),n.includeTests&&f.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let j of f.block.devDependencies)h.add(j);for(let j of f.block.dependencies)w.add(j);let C=await f.files;process.stdout.write(`${T}
81
+ `),process.stdout.write(`${T} ${v}
82
+ `);for(let j of C){let Q=j.content.match(y=>y,y=>program.error(N.red(y))),oe=Yt(j.name,f.block,b,t.cwd),q=(await Jt({file:{content:Q,destPath:oe},biomeOptions:u,prettierOptions:d,config:n,imports:f.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(y=>y,y=>program.error(N.red(y))),k="";le.existsSync(oe)&&(k=le.readFileSync(oe).toString());let A=await jt({config:{biomeOptions:u,prettierOptions:d,formatter:n.formatter},current:{path:oe,content:k},incoming:{path:c(v,j.name),content:q},options:{...t,loading:o,verbose:t.verbose?r:void 0}});A.applyChanges&&(o.start(`Writing changes to ${N.cyan(oe)}`),le.writeFileSync(oe,A.updatedContent),o.stop(`Wrote changes to ${N.cyan(oe)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",R=await He(w,h,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(R.dependencies.size>0||R.devDependencies.size>0){let f=[];if(!R.installed){if(w.size>0){let x=resolveCommand(S,"add",[...w]);f.push(`Install dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(h.size>0){let x=resolveCommand(S,"add",[...h,"-D"]);f.push(`Install dev dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}f=f.map((x,C)=>`${C+1}. ${x}`),R.installed||f.push(""),f.push("Import and use the blocks!");let v=dt(f);process.stdout.write(v);}}var Yn=program.name(Rt.name).description(Rt.description).version(Rt.version).addCommand(Ur).addCommand(zr).addCommand(Kr).addCommand(Yr).addCommand(Zr).addCommand(eo).addCommand(to).addCommand(ro).addCommand(no);Yn.parse();//# sourceMappingURL=index.js.map
83
83
  //# sourceMappingURL=index.js.map